blob: 65cee82a9649edf678876d44b414bda58c6610f8 [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(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
98cl::opt<unsigned>
99MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Chris Lattner53e677a2004-04-02 20:23:17 +0000104namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +0000105 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +0000106 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +0000107}
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Chris Lattner53e677a2004-04-02 20:23:17 +0000117SCEV::~SCEV() {}
118void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000119 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000120}
121
122/// getValueRange - Return the tightest constant bounds that this value is
123/// known to have. This method is only valid on integer SCEV objects.
124ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000127 // Default to a full range if no better information is available.
Reid Spencerc6aedf72007-02-28 22:03:51 +0000128 return ConstantRange(getBitWidth());
Chris Lattner53e677a2004-04-02 20:23:17 +0000129}
130
Reid Spencer581b0d42007-02-28 19:57:34 +0000131uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
134 return 0;
135}
136
Chris Lattner53e677a2004-04-02 20:23:17 +0000137
138SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
Chris Lattner4dc534c2005-02-13 04:37:18 +0000155SCEVHandle SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000159 return this;
160}
161
Chris Lattner53e677a2004-04-02 20:23:17 +0000162void SCEVCouldNotCompute::print(std::ostream &OS) const {
163 OS << "***COULDNOTCOMPUTE***";
164}
165
166bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
168}
169
170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171// SCEVConstants - Only allow the creation of one SCEVConstant for any
172// particular value. Don't use a SCEVHandle here, or else the object will
173// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000174static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000175
Chris Lattner53e677a2004-04-02 20:23:17 +0000176
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000178 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000179}
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Dan Gohman246b2562007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000182 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183 if (R == 0) R = new SCEVConstant(V);
184 return R;
185}
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Dan Gohman246b2562007-10-22 18:31:58 +0000187SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
188 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000189}
190
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191ConstantRange SCEVConstant::getValueRange() const {
Reid Spencerdc5c1592007-02-28 18:57:32 +0000192 return ConstantRange(V->getValue());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193}
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000197void SCEVConstant::print(std::ostream &OS) const {
198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000204static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
205 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
208 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000209 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000211 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
212 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213}
Chris Lattner53e677a2004-04-02 20:23:17 +0000214
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000216 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219ConstantRange SCEVTruncateExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000220 return getOperand()->getValueRange().truncate(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221}
Chris Lattner53e677a2004-04-02 20:23:17 +0000222
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223void SCEVTruncateExpr::print(std::ostream &OS) const {
224 OS << "(truncate " << *Op << " to " << *Ty << ")";
225}
226
227// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
228// particular input. Don't use a SCEVHandle here, or else the object will never
229// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000230static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232
233SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000234 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000235 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000237 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
238 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000239}
240
241SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000242 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000243}
244
245ConstantRange SCEVZeroExtendExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000246 return getOperand()->getValueRange().zeroExtend(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000247}
248
249void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
251}
252
Dan Gohmand19534a2007-06-15 14:38:12 +0000253// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254// particular input. Don't use a SCEVHandle here, or else the object will never
255// be deleted!
256static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
257 SCEVSignExtendExpr*> > SCEVSignExtends;
258
259SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
260 : SCEV(scSignExtend), Op(op), Ty(ty) {
261 assert(Op->getType()->isInteger() && Ty->isInteger() &&
262 "Cannot sign extend non-integer value!");
263 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
264 && "This is not an extending conversion!");
265}
266
267SCEVSignExtendExpr::~SCEVSignExtendExpr() {
268 SCEVSignExtends->erase(std::make_pair(Op, Ty));
269}
270
271ConstantRange SCEVSignExtendExpr::getValueRange() const {
272 return getOperand()->getValueRange().signExtend(getBitWidth());
273}
274
275void SCEVSignExtendExpr::print(std::ostream &OS) const {
276 OS << "(signextend " << *Op << " to " << *Ty << ")";
277}
278
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000279// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
280// particular input. Don't use a SCEVHandle here, or else the object will never
281// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000282static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
283 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000284
285SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000286 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
287 std::vector<SCEV*>(Operands.begin(),
288 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000289}
290
291void SCEVCommutativeExpr::print(std::ostream &OS) const {
292 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
293 const char *OpStr = getOperationStr();
294 OS << "(" << *Operands[0];
295 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
296 OS << OpStr << *Operands[i];
297 OS << ")";
298}
299
Chris Lattner4dc534c2005-02-13 04:37:18 +0000300SCEVHandle SCEVCommutativeExpr::
301replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000302 const SCEVHandle &Conc,
303 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000304 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000305 SCEVHandle H =
306 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000307 if (H != getOperand(i)) {
308 std::vector<SCEVHandle> NewOps;
309 NewOps.reserve(getNumOperands());
310 for (unsigned j = 0; j != i; ++j)
311 NewOps.push_back(getOperand(j));
312 NewOps.push_back(H);
313 for (++i; i != e; ++i)
314 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000315 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000316
317 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000318 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000319 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000320 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000321 else if (isa<SCEVSMaxExpr>(this))
322 return SE.getSMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000323 else
324 assert(0 && "Unknown commutative expr!");
325 }
326 }
327 return this;
328}
329
330
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000331// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000332// input. Don't use a SCEVHandle here, or else the object will never be
333// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000334static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000335 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000337SCEVUDivExpr::~SCEVUDivExpr() {
338 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000339}
340
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000341void SCEVUDivExpr::print(std::ostream &OS) const {
342 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000343}
344
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000345const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000346 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000347}
348
349// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
350// particular input. Don't use a SCEVHandle here, or else the object will never
351// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000352static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
353 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000354
355SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000356 SCEVAddRecExprs->erase(std::make_pair(L,
357 std::vector<SCEV*>(Operands.begin(),
358 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000359}
360
Chris Lattner4dc534c2005-02-13 04:37:18 +0000361SCEVHandle SCEVAddRecExpr::
362replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000363 const SCEVHandle &Conc,
364 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000365 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000366 SCEVHandle H =
367 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000368 if (H != getOperand(i)) {
369 std::vector<SCEVHandle> NewOps;
370 NewOps.reserve(getNumOperands());
371 for (unsigned j = 0; j != i; ++j)
372 NewOps.push_back(getOperand(j));
373 NewOps.push_back(H);
374 for (++i; i != e; ++i)
375 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000376 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000377
Dan Gohman246b2562007-10-22 18:31:58 +0000378 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000379 }
380 }
381 return this;
382}
383
384
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
386 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000387 // contain L and if the start is invariant.
388 return !QueryLoop->contains(L->getHeader()) &&
389 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000390}
391
392
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000393void SCEVAddRecExpr::print(std::ostream &OS) const {
394 OS << "{" << *Operands[0];
395 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
396 OS << ",+," << *Operands[i];
397 OS << "}<" << L->getHeader()->getName() + ">";
398}
Chris Lattner53e677a2004-04-02 20:23:17 +0000399
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000400// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
401// value. Don't use a SCEVHandle here, or else the object will never be
402// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000403static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000404
Chris Lattnerb3364092006-10-04 21:49:37 +0000405SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000406
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000407bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
408 // All non-instruction values are loop invariant. All instructions are loop
409 // invariant if they are not contained in the specified loop.
410 if (Instruction *I = dyn_cast<Instruction>(V))
411 return !L->contains(I->getParent());
412 return true;
413}
Chris Lattner53e677a2004-04-02 20:23:17 +0000414
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000415const Type *SCEVUnknown::getType() const {
416 return V->getType();
417}
Chris Lattner53e677a2004-04-02 20:23:17 +0000418
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000419void SCEVUnknown::print(std::ostream &OS) const {
420 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000421}
422
Chris Lattner8d741b82004-06-20 06:23:15 +0000423//===----------------------------------------------------------------------===//
424// SCEV Utilities
425//===----------------------------------------------------------------------===//
426
427namespace {
428 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
429 /// than the complexity of the RHS. This comparator is used to canonicalize
430 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000431 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000432 bool operator()(SCEV *LHS, SCEV *RHS) {
433 return LHS->getSCEVType() < RHS->getSCEVType();
434 }
435 };
436}
437
438/// GroupByComplexity - Given a list of SCEV objects, order them by their
439/// complexity, and group objects of the same complexity together by value.
440/// When this routine is finished, we know that any duplicates in the vector are
441/// consecutive and that complexity is monotonically increasing.
442///
443/// Note that we go take special precautions to ensure that we get determinstic
444/// results from this routine. In other words, we don't want the results of
445/// this to depend on where the addresses of various SCEV objects happened to
446/// land in memory.
447///
448static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
449 if (Ops.size() < 2) return; // Noop
450 if (Ops.size() == 2) {
451 // This is the common case, which also happens to be trivially simple.
452 // Special case it.
453 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
454 std::swap(Ops[0], Ops[1]);
455 return;
456 }
457
458 // Do the rough sort by complexity.
459 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
460
461 // Now that we are sorted by complexity, group elements of the same
462 // complexity. Note that this is, at worst, N^2, but the vector is likely to
463 // be extremely short in practice. Note that we take this approach because we
464 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000465 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000466 SCEV *S = Ops[i];
467 unsigned Complexity = S->getSCEVType();
468
469 // If there are any objects of the same complexity and same value as this
470 // one, group them.
471 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
472 if (Ops[j] == S) { // Found a duplicate.
473 // Move it to immediately after i'th element.
474 std::swap(Ops[i+1], Ops[j]);
475 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000476 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000477 }
478 }
479 }
480}
481
Chris Lattner53e677a2004-04-02 20:23:17 +0000482
Chris Lattner53e677a2004-04-02 20:23:17 +0000483
484//===----------------------------------------------------------------------===//
485// Simple SCEV method implementations
486//===----------------------------------------------------------------------===//
487
488/// getIntegerSCEV - Given an integer or FP type, create a constant for the
489/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000490SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000491 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000492 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000493 C = Constant::getNullValue(Ty);
494 else if (Ty->isFloatingPoint())
Dale Johannesen43421b32007-09-06 18:13:44 +0000495 C = ConstantFP::get(Ty, APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
496 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000497 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000498 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000499 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000500}
501
502/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
503/// input value to the specified type. If the type must be extended, it is zero
504/// extended.
Dan Gohman246b2562007-10-22 18:31:58 +0000505static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty,
506 ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000507 const Type *SrcTy = V->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000508 assert(SrcTy->isInteger() && Ty->isInteger() &&
Chris Lattner53e677a2004-04-02 20:23:17 +0000509 "Cannot truncate or zero extend with non-integer arguments!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000510 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000511 return V; // No conversion
Reid Spencere7ca0422007-01-08 01:26:33 +0000512 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Dan Gohman246b2562007-10-22 18:31:58 +0000513 return SE.getTruncateExpr(V, Ty);
514 return SE.getZeroExtendExpr(V, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000515}
516
517/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
518///
Dan Gohman246b2562007-10-22 18:31:58 +0000519SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000520 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000521 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000522
Dan Gohman246b2562007-10-22 18:31:58 +0000523 return getMulExpr(V, getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000524}
525
526/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
527///
Dan Gohman246b2562007-10-22 18:31:58 +0000528SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
529 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000530 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000531 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000532}
533
534
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000535/// BinomialCoefficient - Compute BC(It, K). The result is of the same type as
536/// It. Assume, K > 0.
537static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
538 ScalarEvolution &SE) {
539 // We are using the following formula for BC(It, K):
540 //
541 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
542 //
543 // Suppose, W is the bitwidth of It (and of the return value as well). We
544 // must be prepared for overflow. Hence, we must assure that the result of
545 // our computation is equal to the accurate one modulo 2^W. Unfortunately,
546 // division isn't safe in modular arithmetic. This means we must perform the
547 // whole computation accurately and then truncate the result to W bits.
548 //
549 // The dividend of the formula is a multiplication of K integers of bitwidth
550 // W. K*W bits suffice to compute it accurately.
551 //
552 // FIXME: We assume the divisor can be accurately computed using 16-bit
553 // unsigned integer type. It is true up to K = 8 (AddRecs of length 9). In
554 // future we may use APInt to use the minimum number of bits necessary to
555 // compute it accurately.
556 //
557 // It is safe to use unsigned division here: the dividend is nonnegative and
558 // the divisor is positive.
559
560 // Handle the simplest case efficiently.
561 if (K == 1)
562 return It;
563
564 assert(K < 9 && "We cannot handle such long AddRecs yet.");
565
566 // FIXME: A temporary hack to remove in future. Arbitrary precision integers
567 // aren't supported by the code generator yet. For the dividend, the bitwidth
568 // we use is the smallest power of 2 greater or equal to K*W and less or equal
569 // to 64. Note that setting the upper bound for bitwidth may still lead to
570 // miscompilation in some cases.
571 unsigned DividendBits = 1U << Log2_32_Ceil(K * It->getBitWidth());
572 if (DividendBits > 64)
573 DividendBits = 64;
574#if 0 // Waiting for the APInt support in the code generator...
575 unsigned DividendBits = K * It->getBitWidth();
576#endif
577
578 const IntegerType *DividendTy = IntegerType::get(DividendBits);
579 const SCEVHandle ExIt = SE.getZeroExtendExpr(It, DividendTy);
580
581 // The final number of bits we need to perform the division is the maximum of
582 // dividend and divisor bitwidths.
583 const IntegerType *DivisionTy =
584 IntegerType::get(std::max(DividendBits, 16U));
585
586 // Compute K! We know K >= 2 here.
587 unsigned F = 2;
588 for (unsigned i = 3; i <= K; ++i)
589 F *= i;
590 APInt Divisor(DivisionTy->getBitWidth(), F);
591
Chris Lattner53e677a2004-04-02 20:23:17 +0000592 // Handle this case efficiently, it is common to have constant iteration
593 // counts while computing loop exit values.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000594 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ExIt)) {
595 const APInt& N = SC->getValue()->getValue();
596 APInt Dividend(N.getBitWidth(), 1);
597 for (; K; --K)
598 Dividend *= N-(K-1);
599 if (DividendTy != DivisionTy)
600 Dividend = Dividend.zext(DivisionTy->getBitWidth());
601 return SE.getConstant(Dividend.udiv(Divisor).trunc(It->getBitWidth()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000602 }
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000603
604 SCEVHandle Dividend = ExIt;
605 for (unsigned i = 1; i != K; ++i)
606 Dividend =
607 SE.getMulExpr(Dividend,
608 SE.getMinusSCEV(ExIt, SE.getIntegerSCEV(i, DividendTy)));
609 if (DividendTy != DivisionTy)
610 Dividend = SE.getZeroExtendExpr(Dividend, DivisionTy);
611 return
612 SE.getTruncateExpr(SE.getUDivExpr(Dividend, SE.getConstant(Divisor)),
613 It->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +0000614}
615
Chris Lattner53e677a2004-04-02 20:23:17 +0000616/// evaluateAtIteration - Return the value of this chain of recurrences at
617/// the specified iteration number. We can evaluate this recurrence by
618/// multiplying each element in the chain by the binomial coefficient
619/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
620///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000621/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000622///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000623/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000624///
Dan Gohman246b2562007-10-22 18:31:58 +0000625SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
626 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000627 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000628 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000629 // The computation is correct in the face of overflow provided that the
630 // multiplication is performed _after_ the evaluation of the binomial
631 // coefficient.
632 SCEVHandle Val = SE.getMulExpr(getOperand(i),
633 BinomialCoefficient(It, i, SE));
Dan Gohman246b2562007-10-22 18:31:58 +0000634 Result = SE.getAddExpr(Result, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000635 }
636 return Result;
637}
638
Chris Lattner53e677a2004-04-02 20:23:17 +0000639//===----------------------------------------------------------------------===//
640// SCEV Expression folder implementations
641//===----------------------------------------------------------------------===//
642
Dan Gohman246b2562007-10-22 18:31:58 +0000643SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000644 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000645 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000646 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000647
648 // If the input value is a chrec scev made out of constants, truncate
649 // all of the constants.
650 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
651 std::vector<SCEVHandle> Operands;
652 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
653 // FIXME: This should allow truncation of other expression types!
654 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000655 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000656 else
657 break;
658 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000659 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000660 }
661
Chris Lattnerb3364092006-10-04 21:49:37 +0000662 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000663 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
664 return Result;
665}
666
Dan Gohman246b2562007-10-22 18:31:58 +0000667SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000668 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000669 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000670 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000671
672 // FIXME: If the input value is a chrec scev, and we can prove that the value
673 // did not overflow the old, smaller, value, we can zero extend all of the
674 // operands (often constants). This would allow analysis of something like
675 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
676
Chris Lattnerb3364092006-10-04 21:49:37 +0000677 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000678 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
679 return Result;
680}
681
Dan Gohman246b2562007-10-22 18:31:58 +0000682SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000683 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000684 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000685 ConstantExpr::getSExt(SC->getValue(), Ty));
686
687 // FIXME: If the input value is a chrec scev, and we can prove that the value
688 // did not overflow the old, smaller, value, we can sign extend all of the
689 // operands (often constants). This would allow analysis of something like
690 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
691
692 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
693 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
694 return Result;
695}
696
Chris Lattner53e677a2004-04-02 20:23:17 +0000697// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000698SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000699 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000700 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000701
702 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000703 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000704
705 // If there are any constants, fold them together.
706 unsigned Idx = 0;
707 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
708 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000709 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000710 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
711 // We found two constants, fold them together!
Zhou Shengfdc1e162007-04-07 17:40:57 +0000712 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
713 RHSC->getValue()->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +0000714 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
Dan Gohman246b2562007-10-22 18:31:58 +0000715 Ops[0] = getConstant(CI);
Chris Lattner53e677a2004-04-02 20:23:17 +0000716 Ops.erase(Ops.begin()+1); // Erase the folded element
717 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000718 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000719 } else {
720 // If we couldn't fold the expression, move to the next constant. Note
721 // that this is impossible to happen in practice because we always
722 // constant fold constant ints to constant ints.
723 ++Idx;
724 }
725 }
726
727 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000728 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000729 Ops.erase(Ops.begin());
730 --Idx;
731 }
732 }
733
Chris Lattner627018b2004-04-07 16:16:11 +0000734 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000735
Chris Lattner53e677a2004-04-02 20:23:17 +0000736 // Okay, check to see if the same value occurs in the operand list twice. If
737 // so, merge them together into an multiply expression. Since we sorted the
738 // list, these values are required to be adjacent.
739 const Type *Ty = Ops[0]->getType();
740 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
741 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
742 // Found a match, merge the two values into a multiply, and add any
743 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000744 SCEVHandle Two = getIntegerSCEV(2, Ty);
745 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000746 if (Ops.size() == 2)
747 return Mul;
748 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
749 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000750 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000751 }
752
Dan Gohmanf50cd742007-06-18 19:30:09 +0000753 // Now we know the first non-constant operand. Skip past any cast SCEVs.
754 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
755 ++Idx;
756
757 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000758 if (Idx < Ops.size()) {
759 bool DeletedAdd = false;
760 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
761 // If we have an add, expand the add operands onto the end of the operands
762 // list.
763 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
764 Ops.erase(Ops.begin()+Idx);
765 DeletedAdd = true;
766 }
767
768 // If we deleted at least one add, we added operands to the end of the list,
769 // and they are not necessarily sorted. Recurse to resort and resimplify
770 // any operands we just aquired.
771 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000772 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000773 }
774
775 // Skip over the add expression until we get to a multiply.
776 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
777 ++Idx;
778
779 // If we are adding something to a multiply expression, make sure the
780 // something is not already an operand of the multiply. If so, merge it into
781 // the multiply.
782 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
783 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
784 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
785 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
786 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000787 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000788 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
789 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
790 if (Mul->getNumOperands() != 2) {
791 // If the multiply has more than two operands, we must get the
792 // Y*Z term.
793 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
794 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000795 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000796 }
Dan Gohman246b2562007-10-22 18:31:58 +0000797 SCEVHandle One = getIntegerSCEV(1, Ty);
798 SCEVHandle AddOne = getAddExpr(InnerMul, One);
799 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000800 if (Ops.size() == 2) return OuterMul;
801 if (AddOp < Idx) {
802 Ops.erase(Ops.begin()+AddOp);
803 Ops.erase(Ops.begin()+Idx-1);
804 } else {
805 Ops.erase(Ops.begin()+Idx);
806 Ops.erase(Ops.begin()+AddOp-1);
807 }
808 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000809 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000810 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000811
Chris Lattner53e677a2004-04-02 20:23:17 +0000812 // Check this multiply against other multiplies being added together.
813 for (unsigned OtherMulIdx = Idx+1;
814 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
815 ++OtherMulIdx) {
816 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
817 // If MulOp occurs in OtherMul, we can fold the two multiplies
818 // together.
819 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
820 OMulOp != e; ++OMulOp)
821 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
822 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
823 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
824 if (Mul->getNumOperands() != 2) {
825 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
826 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000827 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000828 }
829 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
830 if (OtherMul->getNumOperands() != 2) {
831 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
832 OtherMul->op_end());
833 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000834 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000835 }
Dan Gohman246b2562007-10-22 18:31:58 +0000836 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
837 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000838 if (Ops.size() == 2) return OuterMul;
839 Ops.erase(Ops.begin()+Idx);
840 Ops.erase(Ops.begin()+OtherMulIdx-1);
841 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000842 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000843 }
844 }
845 }
846 }
847
848 // If there are any add recurrences in the operands list, see if any other
849 // added values are loop invariant. If so, we can fold them into the
850 // recurrence.
851 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
852 ++Idx;
853
854 // Scan over all recurrences, trying to fold loop invariants into them.
855 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
856 // Scan all of the other operands to this add and add them to the vector if
857 // they are loop invariant w.r.t. the recurrence.
858 std::vector<SCEVHandle> LIOps;
859 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
860 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
861 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
862 LIOps.push_back(Ops[i]);
863 Ops.erase(Ops.begin()+i);
864 --i; --e;
865 }
866
867 // If we found some loop invariants, fold them into the recurrence.
868 if (!LIOps.empty()) {
869 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
870 LIOps.push_back(AddRec->getStart());
871
872 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000873 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000874
Dan Gohman246b2562007-10-22 18:31:58 +0000875 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000876 // If all of the other operands were loop invariant, we are done.
877 if (Ops.size() == 1) return NewRec;
878
879 // Otherwise, add the folded AddRec by the non-liv parts.
880 for (unsigned i = 0;; ++i)
881 if (Ops[i] == AddRec) {
882 Ops[i] = NewRec;
883 break;
884 }
Dan Gohman246b2562007-10-22 18:31:58 +0000885 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000886 }
887
888 // Okay, if there weren't any loop invariants to be folded, check to see if
889 // there are multiple AddRec's with the same loop induction variable being
890 // added together. If so, we can fold them.
891 for (unsigned OtherIdx = Idx+1;
892 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
893 if (OtherIdx != Idx) {
894 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
895 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
896 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
897 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
898 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
899 if (i >= NewOps.size()) {
900 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
901 OtherAddRec->op_end());
902 break;
903 }
Dan Gohman246b2562007-10-22 18:31:58 +0000904 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000905 }
Dan Gohman246b2562007-10-22 18:31:58 +0000906 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000907
908 if (Ops.size() == 2) return NewAddRec;
909
910 Ops.erase(Ops.begin()+Idx);
911 Ops.erase(Ops.begin()+OtherIdx-1);
912 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000913 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000914 }
915 }
916
917 // Otherwise couldn't fold anything into this recurrence. Move onto the
918 // next one.
919 }
920
921 // Okay, it looks like we really DO need an add expr. Check to see if we
922 // already have one, otherwise create a new one.
923 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000924 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
925 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000926 if (Result == 0) Result = new SCEVAddExpr(Ops);
927 return Result;
928}
929
930
Dan Gohman246b2562007-10-22 18:31:58 +0000931SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000932 assert(!Ops.empty() && "Cannot get empty mul!");
933
934 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000935 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000936
937 // If there are any constants, fold them together.
938 unsigned Idx = 0;
939 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
940
941 // C1*(C2+V) -> C1*C2 + C1*V
942 if (Ops.size() == 2)
943 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
944 if (Add->getNumOperands() == 2 &&
945 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000946 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
947 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000948
949
950 ++Idx;
951 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
952 // We found two constants, fold them together!
Zhou Shengfdc1e162007-04-07 17:40:57 +0000953 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
954 RHSC->getValue()->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +0000955 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
Dan Gohman246b2562007-10-22 18:31:58 +0000956 Ops[0] = getConstant(CI);
Chris Lattner53e677a2004-04-02 20:23:17 +0000957 Ops.erase(Ops.begin()+1); // Erase the folded element
958 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000959 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000960 } else {
961 // If we couldn't fold the expression, move to the next constant. Note
962 // that this is impossible to happen in practice because we always
963 // constant fold constant ints to constant ints.
964 ++Idx;
965 }
966 }
967
968 // If we are left with a constant one being multiplied, strip it off.
969 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
970 Ops.erase(Ops.begin());
971 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000972 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000973 // If we have a multiply of zero, it will always be zero.
974 return Ops[0];
975 }
976 }
977
978 // Skip over the add expression until we get to a multiply.
979 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
980 ++Idx;
981
982 if (Ops.size() == 1)
983 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000984
Chris Lattner53e677a2004-04-02 20:23:17 +0000985 // If there are mul operands inline them all into this expression.
986 if (Idx < Ops.size()) {
987 bool DeletedMul = false;
988 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
989 // If we have an mul, expand the mul operands onto the end of the operands
990 // list.
991 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
992 Ops.erase(Ops.begin()+Idx);
993 DeletedMul = true;
994 }
995
996 // If we deleted at least one mul, we added operands to the end of the list,
997 // and they are not necessarily sorted. Recurse to resort and resimplify
998 // any operands we just aquired.
999 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001000 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001001 }
1002
1003 // If there are any add recurrences in the operands list, see if any other
1004 // added values are loop invariant. If so, we can fold them into the
1005 // recurrence.
1006 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1007 ++Idx;
1008
1009 // Scan over all recurrences, trying to fold loop invariants into them.
1010 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1011 // Scan all of the other operands to this mul and add them to the vector if
1012 // they are loop invariant w.r.t. the recurrence.
1013 std::vector<SCEVHandle> LIOps;
1014 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1015 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1016 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1017 LIOps.push_back(Ops[i]);
1018 Ops.erase(Ops.begin()+i);
1019 --i; --e;
1020 }
1021
1022 // If we found some loop invariants, fold them into the recurrence.
1023 if (!LIOps.empty()) {
1024 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
1025 std::vector<SCEVHandle> NewOps;
1026 NewOps.reserve(AddRec->getNumOperands());
1027 if (LIOps.size() == 1) {
1028 SCEV *Scale = LIOps[0];
1029 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001030 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001031 } else {
1032 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1033 std::vector<SCEVHandle> MulOps(LIOps);
1034 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001035 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001036 }
1037 }
1038
Dan Gohman246b2562007-10-22 18:31:58 +00001039 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001040
1041 // If all of the other operands were loop invariant, we are done.
1042 if (Ops.size() == 1) return NewRec;
1043
1044 // Otherwise, multiply the folded AddRec by the non-liv parts.
1045 for (unsigned i = 0;; ++i)
1046 if (Ops[i] == AddRec) {
1047 Ops[i] = NewRec;
1048 break;
1049 }
Dan Gohman246b2562007-10-22 18:31:58 +00001050 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001051 }
1052
1053 // Okay, if there weren't any loop invariants to be folded, check to see if
1054 // there are multiple AddRec's with the same loop induction variable being
1055 // multiplied together. If so, we can fold them.
1056 for (unsigned OtherIdx = Idx+1;
1057 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1058 if (OtherIdx != Idx) {
1059 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1060 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1061 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1062 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001063 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001064 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001065 SCEVHandle B = F->getStepRecurrence(*this);
1066 SCEVHandle D = G->getStepRecurrence(*this);
1067 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1068 getMulExpr(G, B),
1069 getMulExpr(B, D));
1070 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1071 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001072 if (Ops.size() == 2) return NewAddRec;
1073
1074 Ops.erase(Ops.begin()+Idx);
1075 Ops.erase(Ops.begin()+OtherIdx-1);
1076 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001077 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001078 }
1079 }
1080
1081 // Otherwise couldn't fold anything into this recurrence. Move onto the
1082 // next one.
1083 }
1084
1085 // Okay, it looks like we really DO need an mul expr. Check to see if we
1086 // already have one, otherwise create a new one.
1087 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001088 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1089 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001090 if (Result == 0)
1091 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001092 return Result;
1093}
1094
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001095SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001096 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1097 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001098 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001099
1100 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1101 Constant *LHSCV = LHSC->getValue();
1102 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001103 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001104 }
1105 }
1106
1107 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1108
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001109 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1110 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001111 return Result;
1112}
1113
1114
1115/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1116/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001117SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001118 const SCEVHandle &Step, const Loop *L) {
1119 std::vector<SCEVHandle> Operands;
1120 Operands.push_back(Start);
1121 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1122 if (StepChrec->getLoop() == L) {
1123 Operands.insert(Operands.end(), StepChrec->op_begin(),
1124 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001125 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001126 }
1127
1128 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001129 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001130}
1131
1132/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1133/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001134SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001135 const Loop *L) {
1136 if (Operands.size() == 1) return Operands[0];
1137
1138 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
Reid Spencercae57542007-03-02 00:28:52 +00001139 if (StepC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001140 Operands.pop_back();
Dan Gohman246b2562007-10-22 18:31:58 +00001141 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
Chris Lattner53e677a2004-04-02 20:23:17 +00001142 }
1143
1144 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001145 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1146 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001147 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1148 return Result;
1149}
1150
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001151SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1152 const SCEVHandle &RHS) {
1153 std::vector<SCEVHandle> Ops;
1154 Ops.push_back(LHS);
1155 Ops.push_back(RHS);
1156 return getSMaxExpr(Ops);
1157}
1158
1159SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1160 assert(!Ops.empty() && "Cannot get empty smax!");
1161 if (Ops.size() == 1) return Ops[0];
1162
1163 // Sort by complexity, this groups all similar expression types together.
1164 GroupByComplexity(Ops);
1165
1166 // If there are any constants, fold them together.
1167 unsigned Idx = 0;
1168 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1169 ++Idx;
1170 assert(Idx < Ops.size());
1171 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1172 // We found two constants, fold them together!
1173 Constant *Fold = ConstantInt::get(
1174 APIntOps::smax(LHSC->getValue()->getValue(),
1175 RHSC->getValue()->getValue()));
1176 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
1177 Ops[0] = getConstant(CI);
1178 Ops.erase(Ops.begin()+1); // Erase the folded element
1179 if (Ops.size() == 1) return Ops[0];
1180 LHSC = cast<SCEVConstant>(Ops[0]);
1181 } else {
1182 // If we couldn't fold the expression, move to the next constant. Note
1183 // that this is impossible to happen in practice because we always
1184 // constant fold constant ints to constant ints.
1185 ++Idx;
1186 }
1187 }
1188
1189 // If we are left with a constant -inf, strip it off.
1190 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1191 Ops.erase(Ops.begin());
1192 --Idx;
1193 }
1194 }
1195
1196 if (Ops.size() == 1) return Ops[0];
1197
1198 // Find the first SMax
1199 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1200 ++Idx;
1201
1202 // Check to see if one of the operands is an SMax. If so, expand its operands
1203 // onto our operand list, and recurse to simplify.
1204 if (Idx < Ops.size()) {
1205 bool DeletedSMax = false;
1206 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1207 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1208 Ops.erase(Ops.begin()+Idx);
1209 DeletedSMax = true;
1210 }
1211
1212 if (DeletedSMax)
1213 return getSMaxExpr(Ops);
1214 }
1215
1216 // Okay, check to see if the same value occurs in the operand list twice. If
1217 // so, delete one. Since we sorted the list, these values are required to
1218 // be adjacent.
1219 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1220 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1221 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1222 --i; --e;
1223 }
1224
1225 if (Ops.size() == 1) return Ops[0];
1226
1227 assert(!Ops.empty() && "Reduced smax down to nothing!");
1228
1229 // Okay, it looks like we really DO need an add expr. Check to see if we
1230 // already have one, otherwise create a new one.
1231 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1232 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1233 SCEVOps)];
1234 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1235 return Result;
1236}
1237
Dan Gohman246b2562007-10-22 18:31:58 +00001238SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001239 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001240 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001241 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001242 if (Result == 0) Result = new SCEVUnknown(V);
1243 return Result;
1244}
1245
Chris Lattner53e677a2004-04-02 20:23:17 +00001246
1247//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001248// ScalarEvolutionsImpl Definition and Implementation
1249//===----------------------------------------------------------------------===//
1250//
1251/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1252/// evolution code.
1253///
1254namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001255 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001256 /// SE - A reference to the public ScalarEvolution object.
1257 ScalarEvolution &SE;
1258
Chris Lattner53e677a2004-04-02 20:23:17 +00001259 /// F - The function we are analyzing.
1260 ///
1261 Function &F;
1262
1263 /// LI - The loop information for the function we are currently analyzing.
1264 ///
1265 LoopInfo &LI;
1266
1267 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1268 /// things.
1269 SCEVHandle UnknownValue;
1270
1271 /// Scalars - This is a cache of the scalars we have analyzed so far.
1272 ///
1273 std::map<Value*, SCEVHandle> Scalars;
1274
1275 /// IterationCounts - Cache the iteration count of the loops for this
1276 /// function as they are computed.
1277 std::map<const Loop*, SCEVHandle> IterationCounts;
1278
Chris Lattner3221ad02004-04-17 22:58:41 +00001279 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1280 /// the PHI instructions that we attempt to compute constant evolutions for.
1281 /// This allows us to avoid potentially expensive recomputation of these
1282 /// properties. An instruction maps to null if we are unable to compute its
1283 /// exit value.
1284 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001285
Chris Lattner53e677a2004-04-02 20:23:17 +00001286 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001287 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1288 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001289
1290 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1291 /// expression and create a new one.
1292 SCEVHandle getSCEV(Value *V);
1293
Chris Lattnera0740fb2005-08-09 23:36:33 +00001294 /// hasSCEV - Return true if the SCEV for this value has already been
1295 /// computed.
1296 bool hasSCEV(Value *V) const {
1297 return Scalars.count(V);
1298 }
1299
1300 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1301 /// the specified value.
1302 void setSCEV(Value *V, const SCEVHandle &H) {
1303 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1304 assert(isNew && "This entry already existed!");
1305 }
1306
1307
Chris Lattner53e677a2004-04-02 20:23:17 +00001308 /// getSCEVAtScope - Compute the value of the specified expression within
1309 /// the indicated loop (which may be null to indicate in no loop). If the
1310 /// expression cannot be evaluated, return UnknownValue itself.
1311 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1312
1313
1314 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1315 /// an analyzable loop-invariant iteration count.
1316 bool hasLoopInvariantIterationCount(const Loop *L);
1317
1318 /// getIterationCount - If the specified loop has a predictable iteration
1319 /// count, return it. Note that it is not valid to call this method on a
1320 /// loop without a loop-invariant iteration count.
1321 SCEVHandle getIterationCount(const Loop *L);
1322
Dan Gohman5cec4db2007-06-19 14:28:31 +00001323 /// deleteValueFromRecords - This method should be called by the
1324 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001325 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001326 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001327
1328 private:
1329 /// createSCEV - We know that there is no SCEV for the specified value.
1330 /// Analyze the expression.
1331 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001332
1333 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1334 /// SCEVs.
1335 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001336
1337 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1338 /// for the specified instruction and replaces any references to the
1339 /// symbolic value SymName with the specified value. This is used during
1340 /// PHI resolution.
1341 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1342 const SCEVHandle &SymName,
1343 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001344
1345 /// ComputeIterationCount - Compute the number of times the specified loop
1346 /// will iterate.
1347 SCEVHandle ComputeIterationCount(const Loop *L);
1348
Chris Lattner673e02b2004-10-12 01:49:27 +00001349 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001350 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001351 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1352 Constant *RHS,
1353 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001354 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001355
Chris Lattner7980fb92004-04-17 18:36:24 +00001356 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1357 /// constant number of times (the condition evolves only from constants),
1358 /// try to evaluate a few iterations of the loop until we get the exit
1359 /// condition gets a value of ExitWhen (true or false). If we cannot
1360 /// evaluate the trip count of the loop, return UnknownValue.
1361 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1362 bool ExitWhen);
1363
Chris Lattner53e677a2004-04-02 20:23:17 +00001364 /// HowFarToZero - Return the number of times a backedge comparing the
1365 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001366 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001367 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1368
1369 /// HowFarToNonZero - Return the number of times a backedge checking the
1370 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001371 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001372 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001373
Chris Lattnerdb25de42005-08-15 23:33:51 +00001374 /// HowManyLessThans - Return the number of times a backedge containing the
1375 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001376 /// UnknownValue. isSigned specifies whether the less-than is signed.
1377 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1378 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001379
Chris Lattner3221ad02004-04-17 22:58:41 +00001380 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1381 /// in the header of its containing loop, we know the loop executes a
1382 /// constant number of times, and the PHI node is just a recurrence
1383 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001384 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001385 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001386 };
1387}
1388
1389//===----------------------------------------------------------------------===//
1390// Basic SCEV Analysis and PHI Idiom Recognition Code
1391//
1392
Dan Gohman5cec4db2007-06-19 14:28:31 +00001393/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001394/// client before it removes an instruction from the program, to make sure
1395/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001396void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1397 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001398
Dan Gohman5cec4db2007-06-19 14:28:31 +00001399 if (Scalars.erase(V)) {
1400 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001401 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001402 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001403 }
1404
1405 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001406 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001407 Worklist.pop_back();
1408
Dan Gohman5cec4db2007-06-19 14:28:31 +00001409 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001410 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001411 Instruction *Inst = cast<Instruction>(*UI);
1412 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001413 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001414 ConstantEvolutionLoopExitValue.erase(PN);
1415 Worklist.push_back(Inst);
1416 }
1417 }
1418 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001419}
1420
1421
1422/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1423/// expression and create a new one.
1424SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1425 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1426
1427 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1428 if (I != Scalars.end()) return I->second;
1429 SCEVHandle S = createSCEV(V);
1430 Scalars.insert(std::make_pair(V, S));
1431 return S;
1432}
1433
Chris Lattner4dc534c2005-02-13 04:37:18 +00001434/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1435/// the specified instruction and replaces any references to the symbolic value
1436/// SymName with the specified value. This is used during PHI resolution.
1437void ScalarEvolutionsImpl::
1438ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1439 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001440 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001441 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001442
Chris Lattner4dc534c2005-02-13 04:37:18 +00001443 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001444 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001445 if (NV == SI->second) return; // No change.
1446
1447 SI->second = NV; // Update the scalars map!
1448
1449 // Any instruction values that use this instruction might also need to be
1450 // updated!
1451 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1452 UI != E; ++UI)
1453 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1454}
Chris Lattner53e677a2004-04-02 20:23:17 +00001455
1456/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1457/// a loop header, making it a potential recurrence, or it doesn't.
1458///
1459SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1460 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1461 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1462 if (L->getHeader() == PN->getParent()) {
1463 // If it lives in the loop header, it has two incoming values, one
1464 // from outside the loop, and one from inside.
1465 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1466 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001467
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001469 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 assert(Scalars.find(PN) == Scalars.end() &&
1471 "PHI node already processed?");
1472 Scalars.insert(std::make_pair(PN, SymbolicName));
1473
1474 // Using this symbolic name for the PHI, analyze the value coming around
1475 // the back-edge.
1476 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1477
1478 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1479 // has a special value for the first iteration of the loop.
1480
1481 // If the value coming around the backedge is an add with the symbolic
1482 // value we just inserted, then we found a simple induction variable!
1483 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1484 // If there is a single occurrence of the symbolic value, replace it
1485 // with a recurrence.
1486 unsigned FoundIndex = Add->getNumOperands();
1487 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1488 if (Add->getOperand(i) == SymbolicName)
1489 if (FoundIndex == e) {
1490 FoundIndex = i;
1491 break;
1492 }
1493
1494 if (FoundIndex != Add->getNumOperands()) {
1495 // Create an add with everything but the specified operand.
1496 std::vector<SCEVHandle> Ops;
1497 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1498 if (i != FoundIndex)
1499 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001500 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001501
1502 // This is not a valid addrec if the step amount is varying each
1503 // loop iteration, but is not itself an addrec in this loop.
1504 if (Accum->isLoopInvariant(L) ||
1505 (isa<SCEVAddRecExpr>(Accum) &&
1506 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1507 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001508 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001509
1510 // Okay, for the entire analysis of this edge we assumed the PHI
1511 // to be symbolic. We now need to go back and update all of the
1512 // entries for the scalars that use the PHI (except for the PHI
1513 // itself) to use the new analyzed value instead of the "symbolic"
1514 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001515 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001516 return PHISCEV;
1517 }
1518 }
Chris Lattner97156e72006-04-26 18:34:07 +00001519 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1520 // Otherwise, this could be a loop like this:
1521 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1522 // In this case, j = {1,+,1} and BEValue is j.
1523 // Because the other in-value of i (0) fits the evolution of BEValue
1524 // i really is an addrec evolution.
1525 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1526 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1527
1528 // If StartVal = j.start - j.stride, we can use StartVal as the
1529 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001530 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1531 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001532 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001533 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001534
1535 // Okay, for the entire analysis of this edge we assumed the PHI
1536 // to be symbolic. We now need to go back and update all of the
1537 // entries for the scalars that use the PHI (except for the PHI
1538 // itself) to use the new analyzed value instead of the "symbolic"
1539 // value.
1540 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1541 return PHISCEV;
1542 }
1543 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001544 }
1545
1546 return SymbolicName;
1547 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001548
Chris Lattner53e677a2004-04-02 20:23:17 +00001549 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001550 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001551}
1552
Nick Lewycky83bb0052007-11-22 07:59:40 +00001553/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1554/// guaranteed to end in (at every loop iteration). It is, at the same time,
1555/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1556/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1557static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1558 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001559 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001560
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001561 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001562 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1563
1564 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1565 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1566 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1567 }
1568
1569 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1570 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1571 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1572 }
1573
Chris Lattnera17f0392006-12-12 02:26:09 +00001574 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001575 // The result is the min of all operands results.
1576 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1577 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1578 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1579 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001580 }
1581
1582 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001583 // The result is the sum of all operands results.
1584 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1585 uint32_t BitWidth = M->getBitWidth();
1586 for (unsigned i = 1, e = M->getNumOperands();
1587 SumOpRes != BitWidth && i != e; ++i)
1588 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1589 BitWidth);
1590 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001591 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001592
Chris Lattnera17f0392006-12-12 02:26:09 +00001593 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001594 // The result is the min of all operands results.
1595 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1596 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1597 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1598 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001599 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001600
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001601 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1602 // The result is the min of all operands results.
1603 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1604 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1605 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1606 return MinOpRes;
1607 }
1608
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001609 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001610 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001611}
Chris Lattner53e677a2004-04-02 20:23:17 +00001612
1613/// createSCEV - We know that there is no SCEV for the specified value.
1614/// Analyze the expression.
1615///
1616SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001617 if (!isa<IntegerType>(V->getType()))
1618 return SE.getUnknown(V);
1619
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 if (Instruction *I = dyn_cast<Instruction>(V)) {
1621 switch (I->getOpcode()) {
1622 case Instruction::Add:
Dan Gohman246b2562007-10-22 18:31:58 +00001623 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1624 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001625 case Instruction::Mul:
Dan Gohman246b2562007-10-22 18:31:58 +00001626 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1627 getSCEV(I->getOperand(1)));
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001628 case Instruction::UDiv:
1629 return SE.getUDivExpr(getSCEV(I->getOperand(0)),
Dan Gohman246b2562007-10-22 18:31:58 +00001630 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001631 case Instruction::Sub:
Dan Gohman246b2562007-10-22 18:31:58 +00001632 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1633 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001634 case Instruction::Or:
1635 // If the RHS of the Or is a constant, we may have something like:
Nick Lewyckycf96db22007-11-20 08:24:44 +00001636 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
Chris Lattnera17f0392006-12-12 02:26:09 +00001637 // optimizations will transparently handle this case.
Nick Lewyckycf96db22007-11-20 08:24:44 +00001638 //
1639 // In order for this transformation to be safe, the LHS must be of the
1640 // form X*(2^n) and the Or constant must be less than 2^n.
Chris Lattnera17f0392006-12-12 02:26:09 +00001641 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1642 SCEVHandle LHS = getSCEV(I->getOperand(0));
Nick Lewyckycf96db22007-11-20 08:24:44 +00001643 const APInt &CIVal = CI->getValue();
Nick Lewycky83bb0052007-11-22 07:59:40 +00001644 if (GetMinTrailingZeros(LHS) >=
Nick Lewyckycf96db22007-11-20 08:24:44 +00001645 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001646 return SE.getAddExpr(LHS, getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001647 }
1648 break;
Chris Lattner2811f2a2007-04-02 05:41:38 +00001649 case Instruction::Xor:
1650 // If the RHS of the xor is a signbit, then this is just an add.
1651 // Instcombine turns add of signbit into xor as a strength reduction step.
1652 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1653 if (CI->getValue().isSignBit())
Dan Gohman246b2562007-10-22 18:31:58 +00001654 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1655 getSCEV(I->getOperand(1)));
Chris Lattner2811f2a2007-04-02 05:41:38 +00001656 }
1657 break;
1658
Chris Lattner53e677a2004-04-02 20:23:17 +00001659 case Instruction::Shl:
1660 // Turn shift left of a constant amount into a multiply.
1661 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfdc1e162007-04-07 17:40:57 +00001662 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1663 Constant *X = ConstantInt::get(
1664 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohman246b2562007-10-22 18:31:58 +00001665 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
Chris Lattner53e677a2004-04-02 20:23:17 +00001666 }
1667 break;
1668
Reid Spencer3da59db2006-11-27 01:05:10 +00001669 case Instruction::Trunc:
Dan Gohman246b2562007-10-22 18:31:58 +00001670 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001671
1672 case Instruction::ZExt:
Dan Gohman246b2562007-10-22 18:31:58 +00001673 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001674
Dan Gohmand19534a2007-06-15 14:38:12 +00001675 case Instruction::SExt:
Dan Gohman246b2562007-10-22 18:31:58 +00001676 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmand19534a2007-06-15 14:38:12 +00001677
Reid Spencer3da59db2006-11-27 01:05:10 +00001678 case Instruction::BitCast:
1679 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner42a75512007-01-15 02:27:26 +00001680 if (I->getType()->isInteger() &&
1681 I->getOperand(0)->getType()->isInteger())
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001682 return getSCEV(I->getOperand(0));
1683 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001684
1685 case Instruction::PHI:
1686 return createNodeForPHI(cast<PHINode>(I));
1687
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001688 case Instruction::Select:
1689 // This could be an SCEVSMax that was lowered earlier. Try to recover it.
1690 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I->getOperand(0))) {
1691 Value *LHS = ICI->getOperand(0);
1692 Value *RHS = ICI->getOperand(1);
1693 switch (ICI->getPredicate()) {
1694 case ICmpInst::ICMP_SLT:
1695 case ICmpInst::ICMP_SLE:
1696 std::swap(LHS, RHS);
1697 // fall through
1698 case ICmpInst::ICMP_SGT:
1699 case ICmpInst::ICMP_SGE:
1700 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1701 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1702 default:
1703 break;
1704 }
1705 }
1706
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 default: // We cannot analyze this expression.
1708 break;
1709 }
1710 }
1711
Dan Gohman246b2562007-10-22 18:31:58 +00001712 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001713}
1714
1715
1716
1717//===----------------------------------------------------------------------===//
1718// Iteration Count Computation Code
1719//
1720
1721/// getIterationCount - If the specified loop has a predictable iteration
1722/// count, return it. Note that it is not valid to call this method on a
1723/// loop without a loop-invariant iteration count.
1724SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1725 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1726 if (I == IterationCounts.end()) {
1727 SCEVHandle ItCount = ComputeIterationCount(L);
1728 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1729 if (ItCount != UnknownValue) {
1730 assert(ItCount->isLoopInvariant(L) &&
1731 "Computed trip count isn't loop invariant for loop!");
1732 ++NumTripCountsComputed;
1733 } else if (isa<PHINode>(L->getHeader()->begin())) {
1734 // Only count loops that have phi nodes as not being computable.
1735 ++NumTripCountsNotComputed;
1736 }
1737 }
1738 return I->second;
1739}
1740
1741/// ComputeIterationCount - Compute the number of times the specified loop
1742/// will iterate.
1743SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1744 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001745 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001746 L->getExitBlocks(ExitBlocks);
1747 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001748
1749 // Okay, there is one exit block. Try to find the condition that causes the
1750 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001751 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001752
1753 BasicBlock *ExitingBlock = 0;
1754 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1755 PI != E; ++PI)
1756 if (L->contains(*PI)) {
1757 if (ExitingBlock == 0)
1758 ExitingBlock = *PI;
1759 else
1760 return UnknownValue; // More than one block exiting!
1761 }
1762 assert(ExitingBlock && "No exits from loop, something is broken!");
1763
1764 // Okay, we've computed the exiting block. See what condition causes us to
1765 // exit.
1766 //
1767 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001768 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1769 if (ExitBr == 0) return UnknownValue;
1770 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001771
1772 // At this point, we know we have a conditional branch that determines whether
1773 // the loop is exited. However, we don't know if the branch is executed each
1774 // time through the loop. If not, then the execution count of the branch will
1775 // not be equal to the trip count of the loop.
1776 //
1777 // Currently we check for this by checking to see if the Exit branch goes to
1778 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001779 // times as the loop. We also handle the case where the exit block *is* the
1780 // loop header. This is common for un-rotated loops. More extensive analysis
1781 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001782 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001783 ExitBr->getSuccessor(1) != L->getHeader() &&
1784 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001785 return UnknownValue;
1786
Reid Spencere4d87aa2006-12-23 06:05:41 +00001787 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1788
1789 // If its not an integer comparison then compute it the hard way.
1790 // Note that ICmpInst deals with pointer comparisons too so we must check
1791 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001792 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001793 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1794 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001795
Reid Spencere4d87aa2006-12-23 06:05:41 +00001796 // If the condition was exit on true, convert the condition to exit on false
1797 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001798 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001799 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001800 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001801 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001802
1803 // Handle common loops like: for (X = "string"; *X; ++X)
1804 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1805 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1806 SCEVHandle ItCnt =
1807 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1808 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1809 }
1810
Chris Lattner53e677a2004-04-02 20:23:17 +00001811 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1812 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1813
1814 // Try to evaluate any dependencies out of the loop.
1815 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1816 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1817 Tmp = getSCEVAtScope(RHS, L);
1818 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1819
Reid Spencere4d87aa2006-12-23 06:05:41 +00001820 // At this point, we would like to compute how many iterations of the
1821 // loop the predicate will return true for these inputs.
Wojciech Matyjewicza089b102008-02-11 18:37:34 +00001822 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
1823 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00001824 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001825 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001826 }
1827
1828 // FIXME: think about handling pointer comparisons! i.e.:
1829 // while (P != P+100) ++P;
1830
1831 // If we have a comparison of a chrec against a constant, try to use value
1832 // ranges to answer this query.
1833 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1834 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1835 if (AddRec->getLoop() == L) {
1836 // Form the comparison range using the constant of the correct type so
1837 // that the ConstantRange class knows to do a signed or unsigned
1838 // comparison.
1839 ConstantInt *CompVal = RHSC->getValue();
1840 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001841 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001842 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001843 if (CompVal) {
1844 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00001845 ConstantRange CompRange(
1846 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001847
Dan Gohman246b2562007-10-22 18:31:58 +00001848 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00001849 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1850 }
1851 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001852
Chris Lattner53e677a2004-04-02 20:23:17 +00001853 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001854 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001855 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00001856 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001857 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001858 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001859 }
1860 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001861 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00001862 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001863 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001864 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001865 }
1866 case ICmpInst::ICMP_SLT: {
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001867 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001868 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001869 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001870 }
1871 case ICmpInst::ICMP_SGT: {
Dan Gohman246b2562007-10-22 18:31:58 +00001872 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1873 SE.getNegativeSCEV(RHS), L, true);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001874 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1875 break;
1876 }
1877 case ICmpInst::ICMP_ULT: {
1878 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1879 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1880 break;
1881 }
1882 case ICmpInst::ICMP_UGT: {
Dan Gohman246b2562007-10-22 18:31:58 +00001883 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1884 SE.getNegativeSCEV(RHS), L, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001885 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001886 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001887 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001888 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001889#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001890 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001891 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001892 cerr << "[unsigned] ";
1893 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001894 << Instruction::getOpcodeName(Instruction::ICmp)
1895 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001896#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001897 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001898 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001899 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001900 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00001901}
1902
Chris Lattner673e02b2004-10-12 01:49:27 +00001903static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00001904EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
1905 ScalarEvolution &SE) {
1906 SCEVHandle InVal = SE.getConstant(C);
1907 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00001908 assert(isa<SCEVConstant>(Val) &&
1909 "Evaluation of SCEV at constant didn't fold correctly?");
1910 return cast<SCEVConstant>(Val)->getValue();
1911}
1912
1913/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1914/// and a GEP expression (missing the pointer index) indexing into it, return
1915/// the addressed element of the initializer or null if the index expression is
1916/// invalid.
1917static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001918GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001919 const std::vector<ConstantInt*> &Indices) {
1920 Constant *Init = GV->getInitializer();
1921 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001922 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001923 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1924 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1925 Init = cast<Constant>(CS->getOperand(Idx));
1926 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1927 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1928 Init = cast<Constant>(CA->getOperand(Idx));
1929 } else if (isa<ConstantAggregateZero>(Init)) {
1930 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1931 assert(Idx < STy->getNumElements() && "Bad struct index!");
1932 Init = Constant::getNullValue(STy->getElementType(Idx));
1933 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1934 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1935 Init = Constant::getNullValue(ATy->getElementType());
1936 } else {
1937 assert(0 && "Unknown constant aggregate type!");
1938 }
1939 return 0;
1940 } else {
1941 return 0; // Unknown initializer type
1942 }
1943 }
1944 return Init;
1945}
1946
1947/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001948/// 'icmp op load X, cst', try to se if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001949SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001950ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001951 const Loop *L,
1952 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001953 if (LI->isVolatile()) return UnknownValue;
1954
1955 // Check to see if the loaded pointer is a getelementptr of a global.
1956 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1957 if (!GEP) return UnknownValue;
1958
1959 // Make sure that it is really a constant global we are gepping, with an
1960 // initializer, and make sure the first IDX is really 0.
1961 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1962 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1963 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1964 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1965 return UnknownValue;
1966
1967 // Okay, we allow one non-constant index into the GEP instruction.
1968 Value *VarIdx = 0;
1969 std::vector<ConstantInt*> Indexes;
1970 unsigned VarIdxNum = 0;
1971 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1972 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1973 Indexes.push_back(CI);
1974 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1975 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1976 VarIdx = GEP->getOperand(i);
1977 VarIdxNum = i-2;
1978 Indexes.push_back(0);
1979 }
1980
1981 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1982 // Check to see if X is a loop variant variable value now.
1983 SCEVHandle Idx = getSCEV(VarIdx);
1984 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1985 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1986
1987 // We can only recognize very limited forms of loop index expressions, in
1988 // particular, only affine AddRec's like {C1,+,C2}.
1989 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1990 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1991 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1992 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1993 return UnknownValue;
1994
1995 unsigned MaxSteps = MaxBruteForceIterations;
1996 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001997 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00001998 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00001999 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002000
2001 // Form the GEP offset.
2002 Indexes[VarIdxNum] = Val;
2003
2004 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2005 if (Result == 0) break; // Cannot compute!
2006
2007 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002008 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002009 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002010 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002011#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002012 cerr << "\n***\n*** Computed loop count " << *ItCst
2013 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2014 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002015#endif
2016 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002017 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002018 }
2019 }
2020 return UnknownValue;
2021}
2022
2023
Chris Lattner3221ad02004-04-17 22:58:41 +00002024/// CanConstantFold - Return true if we can constant fold an instruction of the
2025/// specified type, assuming that all operands were constants.
2026static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002027 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002028 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2029 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002030
Chris Lattner3221ad02004-04-17 22:58:41 +00002031 if (const CallInst *CI = dyn_cast<CallInst>(I))
2032 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002033 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002034 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002035}
2036
Chris Lattner3221ad02004-04-17 22:58:41 +00002037/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2038/// in the loop that V is derived from. We allow arbitrary operations along the
2039/// way, but the operands of an operation must either be constants or a value
2040/// derived from a constant PHI. If this expression does not fit with these
2041/// constraints, return null.
2042static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2043 // If this is not an instruction, or if this is an instruction outside of the
2044 // loop, it can't be derived from a loop PHI.
2045 Instruction *I = dyn_cast<Instruction>(V);
2046 if (I == 0 || !L->contains(I->getParent())) return 0;
2047
2048 if (PHINode *PN = dyn_cast<PHINode>(I))
2049 if (L->getHeader() == I->getParent())
2050 return PN;
2051 else
2052 // We don't currently keep track of the control flow needed to evaluate
2053 // PHIs, so we cannot handle PHIs inside of loops.
2054 return 0;
2055
2056 // If we won't be able to constant fold this expression even if the operands
2057 // are constants, return early.
2058 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002059
Chris Lattner3221ad02004-04-17 22:58:41 +00002060 // Otherwise, we can evaluate this instruction if all of its operands are
2061 // constant or derived from a PHI node themselves.
2062 PHINode *PHI = 0;
2063 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2064 if (!(isa<Constant>(I->getOperand(Op)) ||
2065 isa<GlobalValue>(I->getOperand(Op)))) {
2066 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2067 if (P == 0) return 0; // Not evolving from PHI
2068 if (PHI == 0)
2069 PHI = P;
2070 else if (PHI != P)
2071 return 0; // Evolving from multiple different PHIs.
2072 }
2073
2074 // This is a expression evolving from a constant PHI!
2075 return PHI;
2076}
2077
2078/// EvaluateExpression - Given an expression that passes the
2079/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2080/// in the loop has the value PHIVal. If we can't fold this expression for some
2081/// reason, return null.
2082static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2083 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00002084 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00002085 return GV;
2086 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002087 Instruction *I = cast<Instruction>(V);
2088
2089 std::vector<Constant*> Operands;
2090 Operands.resize(I->getNumOperands());
2091
2092 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2093 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2094 if (Operands[i] == 0) return 0;
2095 }
2096
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002097 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2098 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2099 &Operands[0], Operands.size());
2100 else
2101 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2102 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002103}
2104
2105/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2106/// in the header of its containing loop, we know the loop executes a
2107/// constant number of times, and the PHI node is just a recurrence
2108/// involving constants, fold it.
2109Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002110getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002111 std::map<PHINode*, Constant*>::iterator I =
2112 ConstantEvolutionLoopExitValue.find(PN);
2113 if (I != ConstantEvolutionLoopExitValue.end())
2114 return I->second;
2115
Reid Spencere8019bb2007-03-01 07:25:48 +00002116 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002117 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2118
2119 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2120
2121 // Since the loop is canonicalized, the PHI node must have two entries. One
2122 // entry must be a constant (coming in from outside of the loop), and the
2123 // second must be derived from the same PHI.
2124 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2125 Constant *StartCST =
2126 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2127 if (StartCST == 0)
2128 return RetVal = 0; // Must be a constant.
2129
2130 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2131 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2132 if (PN2 != PN)
2133 return RetVal = 0; // Not derived from same PHI.
2134
2135 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002136 if (Its.getActiveBits() >= 32)
2137 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002138
Reid Spencere8019bb2007-03-01 07:25:48 +00002139 unsigned NumIterations = Its.getZExtValue(); // must be in range
2140 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002141 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2142 if (IterationNum == NumIterations)
2143 return RetVal = PHIVal; // Got exit value!
2144
2145 // Compute the value of the PHI node for the next iteration.
2146 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2147 if (NextPHI == PHIVal)
2148 return RetVal = NextPHI; // Stopped evolving!
2149 if (NextPHI == 0)
2150 return 0; // Couldn't evaluate!
2151 PHIVal = NextPHI;
2152 }
2153}
2154
Chris Lattner7980fb92004-04-17 18:36:24 +00002155/// ComputeIterationCountExhaustively - If the trip is known to execute a
2156/// constant number of times (the condition evolves only from constants),
2157/// try to evaluate a few iterations of the loop until we get the exit
2158/// condition gets a value of ExitWhen (true or false). If we cannot
2159/// evaluate the trip count of the loop, return UnknownValue.
2160SCEVHandle ScalarEvolutionsImpl::
2161ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2162 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2163 if (PN == 0) return UnknownValue;
2164
2165 // Since the loop is canonicalized, the PHI node must have two entries. One
2166 // entry must be a constant (coming in from outside of the loop), and the
2167 // second must be derived from the same PHI.
2168 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2169 Constant *StartCST =
2170 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2171 if (StartCST == 0) return UnknownValue; // Must be a constant.
2172
2173 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2174 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2175 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2176
2177 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2178 // the loop symbolically to determine when the condition gets a value of
2179 // "ExitWhen".
2180 unsigned IterationNum = 0;
2181 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2182 for (Constant *PHIVal = StartCST;
2183 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002184 ConstantInt *CondVal =
2185 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002186
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002187 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002188 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002189
Reid Spencere8019bb2007-03-01 07:25:48 +00002190 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002191 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002192 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002193 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002194 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002195
Chris Lattner3221ad02004-04-17 22:58:41 +00002196 // Compute the value of the PHI node for the next iteration.
2197 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2198 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002199 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002200 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002201 }
2202
2203 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002204 return UnknownValue;
2205}
2206
2207/// getSCEVAtScope - Compute the value of the specified expression within the
2208/// indicated loop (which may be null to indicate in no loop). If the
2209/// expression cannot be evaluated, return UnknownValue.
2210SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2211 // FIXME: this should be turned into a virtual method on SCEV!
2212
Chris Lattner3221ad02004-04-17 22:58:41 +00002213 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002214
Chris Lattner3221ad02004-04-17 22:58:41 +00002215 // If this instruction is evolves from a constant-evolving PHI, compute the
2216 // exit value from the loop without using SCEVs.
2217 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2218 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2219 const Loop *LI = this->LI[I->getParent()];
2220 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2221 if (PHINode *PN = dyn_cast<PHINode>(I))
2222 if (PN->getParent() == LI->getHeader()) {
2223 // Okay, there is no closed form solution for the PHI node. Check
2224 // to see if the loop that contains it has a known iteration count.
2225 // If so, we may be able to force computation of the exit value.
2226 SCEVHandle IterationCount = getIterationCount(LI);
2227 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2228 // Okay, we know how many times the containing loop executes. If
2229 // this is a constant evolving PHI node, get the final value at
2230 // the specified iteration number.
2231 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002232 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002233 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002234 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002235 }
2236 }
2237
Reid Spencer09906f32006-12-04 21:33:23 +00002238 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002239 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002240 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002241 // result. This is particularly useful for computing loop exit values.
2242 if (CanConstantFold(I)) {
2243 std::vector<Constant*> Operands;
2244 Operands.reserve(I->getNumOperands());
2245 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2246 Value *Op = I->getOperand(i);
2247 if (Constant *C = dyn_cast<Constant>(Op)) {
2248 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002249 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002250 // If any of the operands is non-constant and if they are
2251 // non-integer, don't even try to analyze them with scev techniques.
2252 if (!isa<IntegerType>(Op->getType()))
2253 return V;
2254
Chris Lattner3221ad02004-04-17 22:58:41 +00002255 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2256 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002257 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2258 Op->getType(),
2259 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002260 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2261 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002262 Operands.push_back(ConstantExpr::getIntegerCast(C,
2263 Op->getType(),
2264 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002265 else
2266 return V;
2267 } else {
2268 return V;
2269 }
2270 }
2271 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002272
2273 Constant *C;
2274 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2275 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2276 &Operands[0], Operands.size());
2277 else
2278 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2279 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002280 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002281 }
2282 }
2283
2284 // This is some other type of SCEVUnknown, just return it.
2285 return V;
2286 }
2287
Chris Lattner53e677a2004-04-02 20:23:17 +00002288 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2289 // Avoid performing the look-up in the common case where the specified
2290 // expression has no loop-variant portions.
2291 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2292 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2293 if (OpAtScope != Comm->getOperand(i)) {
2294 if (OpAtScope == UnknownValue) return UnknownValue;
2295 // Okay, at least one of these operands is loop variant but might be
2296 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002297 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002298 NewOps.push_back(OpAtScope);
2299
2300 for (++i; i != e; ++i) {
2301 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2302 if (OpAtScope == UnknownValue) return UnknownValue;
2303 NewOps.push_back(OpAtScope);
2304 }
2305 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002306 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002307 if (isa<SCEVMulExpr>(Comm))
2308 return SE.getMulExpr(NewOps);
2309 if (isa<SCEVSMaxExpr>(Comm))
2310 return SE.getSMaxExpr(NewOps);
2311 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002312 }
2313 }
2314 // If we got here, all operands are loop invariant.
2315 return Comm;
2316 }
2317
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002318 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Chris Lattner60a05cc2006-04-01 04:48:52 +00002319 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002320 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002321 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002322 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002323 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2324 return Div; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002325 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002326 }
2327
2328 // If this is a loop recurrence for a loop that does not contain L, then we
2329 // are dealing with the final value computed by the loop.
2330 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2331 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2332 // To evaluate this recurrence, we need to know how many times the AddRec
2333 // loop iterates. Compute this now.
2334 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2335 if (IterationCount == UnknownValue) return UnknownValue;
2336 IterationCount = getTruncateOrZeroExtend(IterationCount,
Dan Gohman246b2562007-10-22 18:31:58 +00002337 AddRec->getType(), SE);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002338
Chris Lattner53e677a2004-04-02 20:23:17 +00002339 // If the value is affine, simplify the expression evaluation to just
2340 // Start + Step*IterationCount.
2341 if (AddRec->isAffine())
Dan Gohman246b2562007-10-22 18:31:58 +00002342 return SE.getAddExpr(AddRec->getStart(),
2343 SE.getMulExpr(IterationCount,
2344 AddRec->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002345
2346 // Otherwise, evaluate it the hard way.
Dan Gohman246b2562007-10-22 18:31:58 +00002347 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002348 }
2349 return UnknownValue;
2350 }
2351
2352 //assert(0 && "Unknown SCEV type!");
2353 return UnknownValue;
2354}
2355
2356
2357/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2358/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2359/// might be the same) or two SCEVCouldNotCompute objects.
2360///
2361static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002362SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002363 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002364 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2365 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2366 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002367
Chris Lattner53e677a2004-04-02 20:23:17 +00002368 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002369 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002370 SCEV *CNC = new SCEVCouldNotCompute();
2371 return std::make_pair(CNC, CNC);
2372 }
2373
Reid Spencere8019bb2007-03-01 07:25:48 +00002374 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002375 const APInt &L = LC->getValue()->getValue();
2376 const APInt &M = MC->getValue()->getValue();
2377 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002378 APInt Two(BitWidth, 2);
2379 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002380
Reid Spencere8019bb2007-03-01 07:25:48 +00002381 {
2382 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002383 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002384 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2385 // The B coefficient is M-N/2
2386 APInt B(M);
2387 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002388
Reid Spencere8019bb2007-03-01 07:25:48 +00002389 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002390 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002391
Reid Spencere8019bb2007-03-01 07:25:48 +00002392 // Compute the B^2-4ac term.
2393 APInt SqrtTerm(B);
2394 SqrtTerm *= B;
2395 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002396
Reid Spencere8019bb2007-03-01 07:25:48 +00002397 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2398 // integer value or else APInt::sqrt() will assert.
2399 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002400
Reid Spencere8019bb2007-03-01 07:25:48 +00002401 // Compute the two solutions for the quadratic formula.
2402 // The divisions must be performed as signed divisions.
2403 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002404 APInt TwoA( A << 1 );
Reid Spencere8019bb2007-03-01 07:25:48 +00002405 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2406 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002407
Dan Gohman246b2562007-10-22 18:31:58 +00002408 return std::make_pair(SE.getConstant(Solution1),
2409 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002410 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002411}
2412
2413/// HowFarToZero - Return the number of times a backedge comparing the specified
2414/// value to zero will execute. If not computable, return UnknownValue
2415SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2416 // If the value is a constant
2417 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2418 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002419 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002420 return UnknownValue; // Otherwise it will loop infinitely.
2421 }
2422
2423 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2424 if (!AddRec || AddRec->getLoop() != L)
2425 return UnknownValue;
2426
2427 if (AddRec->isAffine()) {
2428 // If this is an affine expression the execution count of this branch is
2429 // equal to:
2430 //
2431 // (0 - Start/Step) iff Start % Step == 0
2432 //
2433 // Get the initial value for the loop.
2434 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002435 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002436 SCEVHandle Step = AddRec->getOperand(1);
2437
2438 Step = getSCEVAtScope(Step, L->getParentLoop());
2439
2440 // Figure out if Start % Step == 0.
2441 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2442 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2443 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Dan Gohman246b2562007-10-22 18:31:58 +00002444 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002445 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2446 return Start; // 0 - Start/-1 == Start
2447
2448 // Check to see if Start is divisible by SC with no remainder.
2449 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2450 ConstantInt *StartCC = StartC->getValue();
2451 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002452 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002453 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002454 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Dan Gohman246b2562007-10-22 18:31:58 +00002455 return SE.getUnknown(Result);
Chris Lattner53e677a2004-04-02 20:23:17 +00002456 }
2457 }
2458 }
Chris Lattner42a75512007-01-15 02:27:26 +00002459 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002460 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2461 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002462 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002463 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2464 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2465 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002466#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002467 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2468 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002469#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002470 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002471 if (ConstantInt *CB =
2472 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002473 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002474 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002475 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002476
Chris Lattner53e677a2004-04-02 20:23:17 +00002477 // We can only use this value if the chrec ends up with an exact zero
2478 // value at this index. When solving for "X*X != 5", for example, we
2479 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002480 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002481 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
Reid Spencercae57542007-03-02 00:28:52 +00002482 if (EvalVal->getValue()->isZero())
Chris Lattner53e677a2004-04-02 20:23:17 +00002483 return R1; // We found a quadratic root!
2484 }
2485 }
2486 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002487
Chris Lattner53e677a2004-04-02 20:23:17 +00002488 return UnknownValue;
2489}
2490
2491/// HowFarToNonZero - Return the number of times a backedge checking the
2492/// specified value for nonzero will execute. If not computable, return
2493/// UnknownValue
2494SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2495 // Loops that look like: while (X == 0) are very strange indeed. We don't
2496 // handle them yet except for the trivial case. This could be expanded in the
2497 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002498
Chris Lattner53e677a2004-04-02 20:23:17 +00002499 // If the value is a constant, check to see if it is known to be non-zero
2500 // already. If so, the backedge will execute zero times.
2501 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2502 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002503 Constant *NonZero =
2504 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002505 if (NonZero == ConstantInt::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002506 return getSCEV(Zero);
2507 return UnknownValue; // Otherwise it will loop infinitely.
2508 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002509
Chris Lattner53e677a2004-04-02 20:23:17 +00002510 // We could implement others, but I really doubt anyone writes loops like
2511 // this, and if they did, they would already be constant folded.
2512 return UnknownValue;
2513}
2514
Chris Lattnerdb25de42005-08-15 23:33:51 +00002515/// HowManyLessThans - Return the number of times a backedge containing the
2516/// specified less-than comparison will execute. If not computable, return
2517/// UnknownValue.
2518SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002519HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002520 // Only handle: "ADDREC < LoopInvariant".
2521 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2522
2523 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2524 if (!AddRec || AddRec->getLoop() != L)
2525 return UnknownValue;
2526
2527 if (AddRec->isAffine()) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002528 // The number of iterations for "{n,+,1} < m", is m-n. However, we don't
2529 // know that m is >= n on input to the loop. If it is, the condition
Wojciech Matyjewicz7b5b7682008-02-12 15:09:36 +00002530 // returns true zero times. To handle both cases, we return SMAX(m, n)-n.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002531
Chris Lattnerdb25de42005-08-15 23:33:51 +00002532 // FORNOW: We only support unit strides.
Dan Gohman246b2562007-10-22 18:31:58 +00002533 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Chris Lattnerdb25de42005-08-15 23:33:51 +00002534 if (AddRec->getOperand(1) != One)
2535 return UnknownValue;
2536
Wojciech Matyjewicz7b5b7682008-02-12 15:09:36 +00002537 SCEVHandle Start = AddRec->getOperand(0);
2538 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start) : (SCEVHandle)RHS;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002539
Wojciech Matyjewicz7b5b7682008-02-12 15:09:36 +00002540 return SE.getMinusSCEV(End, Start);
Chris Lattnerdb25de42005-08-15 23:33:51 +00002541 }
2542
2543 return UnknownValue;
2544}
2545
Chris Lattner53e677a2004-04-02 20:23:17 +00002546/// getNumIterationsInRange - Return the number of iterations of this loop that
2547/// produce values in the specified constant range. Another way of looking at
2548/// this is that it returns the first iteration number where the value is not in
2549/// the condition, thus computing the exit count. If the iteration count can't
2550/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002551SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2552 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002553 if (Range.isFullSet()) // Infinite loop.
2554 return new SCEVCouldNotCompute();
2555
2556 // If the start is a non-zero constant, shift the range to simplify things.
2557 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002558 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002559 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002560 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2561 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002562 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2563 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002564 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002565 // This is strange and shouldn't happen.
2566 return new SCEVCouldNotCompute();
2567 }
2568
2569 // The only time we can solve this is when we have all constant indices.
2570 // Otherwise, we cannot determine the overflow conditions.
2571 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2572 if (!isa<SCEVConstant>(getOperand(i)))
2573 return new SCEVCouldNotCompute();
2574
2575
2576 // Okay at this point we know that all elements of the chrec are constants and
2577 // that the start element is zero.
2578
2579 // First check to see if the range contains zero. If not, the first
2580 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002581 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002582 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002583
Chris Lattner53e677a2004-04-02 20:23:17 +00002584 if (isAffine()) {
2585 // If this is an affine expression then we have this situation:
2586 // Solve {0,+,A} in Range === Ax in Range
2587
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002588 // We know that zero is in the range. If A is positive then we know that
2589 // the upper value of the range must be the first possible exit value.
2590 // If A is negative then the lower of the range is the last possible loop
2591 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002592 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002593 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2594 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002595
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002596 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002597 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002598 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002599
2600 // Evaluate at the exit value. If we really did fall out of the valid
2601 // range, then we computed our trip count, otherwise wrap around or other
2602 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00002603 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002604 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002605 return new SCEVCouldNotCompute(); // Something strange happened
2606
2607 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002608 assert(Range.contains(
2609 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002610 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002611 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00002612 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00002613 } else if (isQuadratic()) {
2614 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2615 // quadratic equation to solve it. To do this, we must frame our problem in
2616 // terms of figuring out when zero is crossed, instead of when
2617 // Range.getUpper() is crossed.
2618 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002619 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2620 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002621
2622 // Next, solve the constructed addrec
2623 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00002624 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002625 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2626 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2627 if (R1) {
2628 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002629 if (ConstantInt *CB =
2630 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002631 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002632 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002633 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002634
Chris Lattner53e677a2004-04-02 20:23:17 +00002635 // Make sure the root is not off by one. The returned iteration should
2636 // not be in the range, but the previous one should be. When solving
2637 // for "X*X < 5", for example, we should not return a root of 2.
2638 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002639 R1->getValue(),
2640 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002641 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002642 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00002643 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002644
Dan Gohman246b2562007-10-22 18:31:58 +00002645 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002646 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002647 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002648 return new SCEVCouldNotCompute(); // Something strange happened
2649 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002650
Chris Lattner53e677a2004-04-02 20:23:17 +00002651 // If R1 was not in the range, then it is a good return value. Make
2652 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00002653 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00002654 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002655 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002656 return R1;
2657 return new SCEVCouldNotCompute(); // Something strange happened
2658 }
2659 }
2660 }
2661
2662 // Fallback, if this is a general polynomial, figure out the progression
2663 // through brute force: evaluate until we find an iteration that fails the
2664 // test. This is likely to be slow, but getting an accurate trip count is
2665 // incredibly important, we will be able to simplify the exit test a lot, and
2666 // we are almost guaranteed to get a trip count in this case.
2667 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00002668 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2669 do {
2670 ++NumBruteForceEvaluations;
Dan Gohman246b2562007-10-22 18:31:58 +00002671 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002672 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2673 return new SCEVCouldNotCompute();
2674
2675 // Check to see if we found the value!
Reid Spencera6e8a952007-03-01 07:54:15 +00002676 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002677 return SE.getConstant(TestVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002678
2679 // Increment to test the next index.
Zhou Shengfdc1e162007-04-07 17:40:57 +00002680 TestVal = ConstantInt::get(TestVal->getValue()+1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002681 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002682
Chris Lattner53e677a2004-04-02 20:23:17 +00002683 return new SCEVCouldNotCompute();
2684}
2685
2686
2687
2688//===----------------------------------------------------------------------===//
2689// ScalarEvolution Class Implementation
2690//===----------------------------------------------------------------------===//
2691
2692bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00002693 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00002694 return false;
2695}
2696
2697void ScalarEvolution::releaseMemory() {
2698 delete (ScalarEvolutionsImpl*)Impl;
2699 Impl = 0;
2700}
2701
2702void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2703 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002704 AU.addRequiredTransitive<LoopInfo>();
2705}
2706
2707SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2708 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2709}
2710
Chris Lattnera0740fb2005-08-09 23:36:33 +00002711/// hasSCEV - Return true if the SCEV for this value has already been
2712/// computed.
2713bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002714 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002715}
2716
2717
2718/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2719/// the specified value.
2720void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2721 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2722}
2723
2724
Chris Lattner53e677a2004-04-02 20:23:17 +00002725SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2726 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2727}
2728
2729bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2730 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2731}
2732
2733SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2734 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2735}
2736
Dan Gohman5cec4db2007-06-19 14:28:31 +00002737void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2738 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002739}
2740
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002741static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002742 const Loop *L) {
2743 // Print all inner loops first
2744 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2745 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002746
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002747 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002748
Devang Patelb7211a22007-08-21 00:31:24 +00002749 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002750 L->getExitBlocks(ExitBlocks);
2751 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002752 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002753
2754 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002755 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002756 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002757 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002758 }
2759
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002760 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002761}
2762
Reid Spencerce9653c2004-12-07 04:03:45 +00002763void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002764 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2765 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2766
2767 OS << "Classifying expressions for: " << F.getName() << "\n";
2768 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00002769 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002770 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002771 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002772 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002773 SV->print(OS);
2774 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002775
Chris Lattner42a75512007-01-15 02:27:26 +00002776 if ((*I).getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002777 ConstantRange Bounds = SV->getValueRange();
2778 if (!Bounds.isFullSet())
2779 OS << "Bounds: " << Bounds << " ";
2780 }
2781
Chris Lattner6ffe5512004-04-27 15:13:33 +00002782 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002783 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002784 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002785 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2786 OS << "<<Unknown>>";
2787 } else {
2788 OS << *ExitValue;
2789 }
2790 }
2791
2792
2793 OS << "\n";
2794 }
2795
2796 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2797 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2798 PrintLoopInfo(OS, this, *I);
2799}