blob: 8fb46dd883b9089c28eed9dd4185a4861c7695e0 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000083#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman844731a2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman844731a2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000103char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
Chris Lattner53e677a2004-04-02 20:23:17 +0000112SCEV::~SCEV() {}
113void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000114 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000115}
116
Reid Spencer581b0d42007-02-28 19:57:34 +0000117uint32_t SCEV::getBitWidth() const {
118 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
119 return ITy->getBitWidth();
120 return 0;
121}
122
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000123bool SCEV::isZero() const {
124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
125 return SC->getValue()->isZero();
126 return false;
127}
128
Chris Lattner53e677a2004-04-02 20:23:17 +0000129
130SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
131
132bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
133 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000134 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000135}
136
137const Type *SCEVCouldNotCompute::getType() const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return false;
145}
146
Chris Lattner4dc534c2005-02-13 04:37:18 +0000147SCEVHandle SCEVCouldNotCompute::
148replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000149 const SCEVHandle &Conc,
150 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000151 return this;
152}
153
Chris Lattner53e677a2004-04-02 20:23:17 +0000154void SCEVCouldNotCompute::print(std::ostream &OS) const {
155 OS << "***COULDNOTCOMPUTE***";
156}
157
158bool SCEVCouldNotCompute::classof(const SCEV *S) {
159 return S->getSCEVType() == scCouldNotCompute;
160}
161
162
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000163// SCEVConstants - Only allow the creation of one SCEVConstant for any
164// particular value. Don't use a SCEVHandle here, or else the object will
165// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000166static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000167
Chris Lattner53e677a2004-04-02 20:23:17 +0000168
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000169SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000170 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171}
Chris Lattner53e677a2004-04-02 20:23:17 +0000172
Dan Gohman246b2562007-10-22 18:31:58 +0000173SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000174 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175 if (R == 0) R = new SCEVConstant(V);
176 return R;
177}
Chris Lattner53e677a2004-04-02 20:23:17 +0000178
Dan Gohman246b2562007-10-22 18:31:58 +0000179SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
180 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000181}
182
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185void SCEVConstant::print(std::ostream &OS) const {
186 WriteAsOperand(OS, V, false);
187}
Chris Lattner53e677a2004-04-02 20:23:17 +0000188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
190// particular input. Don't use a SCEVHandle here, or else the object will
191// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000192static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
193 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
196 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000197 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000199 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
200 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201}
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000204 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205}
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207void SCEVTruncateExpr::print(std::ostream &OS) const {
208 OS << "(truncate " << *Op << " to " << *Ty << ")";
209}
210
211// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
212// particular input. Don't use a SCEVHandle here, or else the object will never
213// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000214static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
215 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216
217SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000218 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000219 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000221 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
222 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
225SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000226 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227}
228
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000229void SCEVZeroExtendExpr::print(std::ostream &OS) const {
230 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
231}
232
Dan Gohmand19534a2007-06-15 14:38:12 +0000233// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
234// particular input. Don't use a SCEVHandle here, or else the object will never
235// be deleted!
236static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
237 SCEVSignExtendExpr*> > SCEVSignExtends;
238
239SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
240 : SCEV(scSignExtend), Op(op), Ty(ty) {
241 assert(Op->getType()->isInteger() && Ty->isInteger() &&
242 "Cannot sign extend non-integer value!");
243 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
244 && "This is not an extending conversion!");
245}
246
247SCEVSignExtendExpr::~SCEVSignExtendExpr() {
248 SCEVSignExtends->erase(std::make_pair(Op, Ty));
249}
250
Dan Gohmand19534a2007-06-15 14:38:12 +0000251void SCEVSignExtendExpr::print(std::ostream &OS) const {
252 OS << "(signextend " << *Op << " to " << *Ty << ")";
253}
254
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000255// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
256// particular input. Don't use a SCEVHandle here, or else the object will never
257// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000258static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
259 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000260
261SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000262 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
263 std::vector<SCEV*>(Operands.begin(),
264 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000265}
266
267void SCEVCommutativeExpr::print(std::ostream &OS) const {
268 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
269 const char *OpStr = getOperationStr();
270 OS << "(" << *Operands[0];
271 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
272 OS << OpStr << *Operands[i];
273 OS << ")";
274}
275
Chris Lattner4dc534c2005-02-13 04:37:18 +0000276SCEVHandle SCEVCommutativeExpr::
277replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000278 const SCEVHandle &Conc,
279 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000280 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000281 SCEVHandle H =
282 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000283 if (H != getOperand(i)) {
284 std::vector<SCEVHandle> NewOps;
285 NewOps.reserve(getNumOperands());
286 for (unsigned j = 0; j != i; ++j)
287 NewOps.push_back(getOperand(j));
288 NewOps.push_back(H);
289 for (++i; i != e; ++i)
290 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000291 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000292
293 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000294 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000295 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000296 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000297 else if (isa<SCEVSMaxExpr>(this))
298 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000299 else if (isa<SCEVUMaxExpr>(this))
300 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000301 else
302 assert(0 && "Unknown commutative expr!");
303 }
304 }
305 return this;
306}
307
308
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000309// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000310// input. Don't use a SCEVHandle here, or else the object will never be
311// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000312static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000313 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000315SCEVUDivExpr::~SCEVUDivExpr() {
316 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000317}
318
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000319void SCEVUDivExpr::print(std::ostream &OS) const {
320 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000321}
322
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000323const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000324 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000325}
326
327// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
328// particular input. Don't use a SCEVHandle here, or else the object will never
329// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000330static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
331 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000332
333SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000334 SCEVAddRecExprs->erase(std::make_pair(L,
335 std::vector<SCEV*>(Operands.begin(),
336 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
338
Chris Lattner4dc534c2005-02-13 04:37:18 +0000339SCEVHandle SCEVAddRecExpr::
340replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000341 const SCEVHandle &Conc,
342 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000343 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000344 SCEVHandle H =
345 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000346 if (H != getOperand(i)) {
347 std::vector<SCEVHandle> NewOps;
348 NewOps.reserve(getNumOperands());
349 for (unsigned j = 0; j != i; ++j)
350 NewOps.push_back(getOperand(j));
351 NewOps.push_back(H);
352 for (++i; i != e; ++i)
353 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000354 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000355
Dan Gohman246b2562007-10-22 18:31:58 +0000356 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000357 }
358 }
359 return this;
360}
361
362
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
364 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000365 // contain L and if the start is invariant.
366 return !QueryLoop->contains(L->getHeader()) &&
367 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000368}
369
370
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000371void SCEVAddRecExpr::print(std::ostream &OS) const {
372 OS << "{" << *Operands[0];
373 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
374 OS << ",+," << *Operands[i];
375 OS << "}<" << L->getHeader()->getName() + ">";
376}
Chris Lattner53e677a2004-04-02 20:23:17 +0000377
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000378// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
379// value. Don't use a SCEVHandle here, or else the object will never be
380// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000381static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000382
Chris Lattnerb3364092006-10-04 21:49:37 +0000383SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000384
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
386 // All non-instruction values are loop invariant. All instructions are loop
387 // invariant if they are not contained in the specified loop.
388 if (Instruction *I = dyn_cast<Instruction>(V))
389 return !L->contains(I->getParent());
390 return true;
391}
Chris Lattner53e677a2004-04-02 20:23:17 +0000392
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000393const Type *SCEVUnknown::getType() const {
394 return V->getType();
395}
Chris Lattner53e677a2004-04-02 20:23:17 +0000396
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000397void SCEVUnknown::print(std::ostream &OS) const {
398 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000399}
400
Chris Lattner8d741b82004-06-20 06:23:15 +0000401//===----------------------------------------------------------------------===//
402// SCEV Utilities
403//===----------------------------------------------------------------------===//
404
405namespace {
406 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
407 /// than the complexity of the RHS. This comparator is used to canonicalize
408 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000409 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000410 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000411 return LHS->getSCEVType() < RHS->getSCEVType();
412 }
413 };
414}
415
416/// GroupByComplexity - Given a list of SCEV objects, order them by their
417/// complexity, and group objects of the same complexity together by value.
418/// When this routine is finished, we know that any duplicates in the vector are
419/// consecutive and that complexity is monotonically increasing.
420///
421/// Note that we go take special precautions to ensure that we get determinstic
422/// results from this routine. In other words, we don't want the results of
423/// this to depend on where the addresses of various SCEV objects happened to
424/// land in memory.
425///
426static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
427 if (Ops.size() < 2) return; // Noop
428 if (Ops.size() == 2) {
429 // This is the common case, which also happens to be trivially simple.
430 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000431 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000432 std::swap(Ops[0], Ops[1]);
433 return;
434 }
435
436 // Do the rough sort by complexity.
437 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
438
439 // Now that we are sorted by complexity, group elements of the same
440 // complexity. Note that this is, at worst, N^2, but the vector is likely to
441 // be extremely short in practice. Note that we take this approach because we
442 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000443 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000444 SCEV *S = Ops[i];
445 unsigned Complexity = S->getSCEVType();
446
447 // If there are any objects of the same complexity and same value as this
448 // one, group them.
449 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
450 if (Ops[j] == S) { // Found a duplicate.
451 // Move it to immediately after i'th element.
452 std::swap(Ops[i+1], Ops[j]);
453 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000454 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000455 }
456 }
457 }
458}
459
Chris Lattner53e677a2004-04-02 20:23:17 +0000460
Chris Lattner53e677a2004-04-02 20:23:17 +0000461
462//===----------------------------------------------------------------------===//
463// Simple SCEV method implementations
464//===----------------------------------------------------------------------===//
465
466/// getIntegerSCEV - Given an integer or FP type, create a constant for the
467/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000468SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000469 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000470 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000471 C = Constant::getNullValue(Ty);
472 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000473 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
474 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000475 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000476 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000477 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000478}
479
Chris Lattner53e677a2004-04-02 20:23:17 +0000480/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
481///
Dan Gohman246b2562007-10-22 18:31:58 +0000482SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000483 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000484 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000485
Nick Lewycky178f20a2008-02-20 06:58:55 +0000486 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000487}
488
489/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
490SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
491 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
492 return getUnknown(ConstantExpr::getNot(VC->getValue()));
493
Nick Lewycky178f20a2008-02-20 06:58:55 +0000494 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000495 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000496}
497
498/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
499///
Dan Gohman246b2562007-10-22 18:31:58 +0000500SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
501 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000502 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000503 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000504}
505
506
Eli Friedmanb42a6262008-08-04 23:49:06 +0000507/// BinomialCoefficient - Compute BC(It, K). The result has width W.
508// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000509static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000510 ScalarEvolution &SE,
511 const IntegerType* ResultTy) {
512 // Handle the simplest case efficiently.
513 if (K == 1)
514 return SE.getTruncateOrZeroExtend(It, ResultTy);
515
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000516 // We are using the following formula for BC(It, K):
517 //
518 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
519 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000520 // Suppose, W is the bitwidth of the return value. We must be prepared for
521 // overflow. Hence, we must assure that the result of our computation is
522 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
523 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000524 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000525 // However, this code doesn't use exactly that formula; the formula it uses
526 // is something like the following, where T is the number of factors of 2 in
527 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
528 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000529 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000530 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000531 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000532 // This formula is trivially equivalent to the previous formula. However,
533 // this formula can be implemented much more efficiently. The trick is that
534 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
535 // arithmetic. To do exact division in modular arithmetic, all we have
536 // to do is multiply by the inverse. Therefore, this step can be done at
537 // width W.
538 //
539 // The next issue is how to safely do the division by 2^T. The way this
540 // is done is by doing the multiplication step at a width of at least W + T
541 // bits. This way, the bottom W+T bits of the product are accurate. Then,
542 // when we perform the division by 2^T (which is equivalent to a right shift
543 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
544 // truncated out after the division by 2^T.
545 //
546 // In comparison to just directly using the first formula, this technique
547 // is much more efficient; using the first formula requires W * K bits,
548 // but this formula less than W + K bits. Also, the first formula requires
549 // a division step, whereas this formula only requires multiplies and shifts.
550 //
551 // It doesn't matter whether the subtraction step is done in the calculation
552 // width or the input iteration count's width; if the subtraction overflows,
553 // the result must be zero anyway. We prefer here to do it in the width of
554 // the induction variable because it helps a lot for certain cases; CodeGen
555 // isn't smart enough to ignore the overflow, which leads to much less
556 // efficient code if the width of the subtraction is wider than the native
557 // register width.
558 //
559 // (It's possible to not widen at all by pulling out factors of 2 before
560 // the multiplication; for example, K=2 can be calculated as
561 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
562 // extra arithmetic, so it's not an obvious win, and it gets
563 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000564
Eli Friedmanb42a6262008-08-04 23:49:06 +0000565 // Protection from insane SCEVs; this bound is conservative,
566 // but it probably doesn't matter.
567 if (K > 1000)
568 return new SCEVCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000569
Eli Friedmanb42a6262008-08-04 23:49:06 +0000570 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000571
Eli Friedmanb42a6262008-08-04 23:49:06 +0000572 // Calculate K! / 2^T and T; we divide out the factors of two before
573 // multiplying for calculating K! / 2^T to avoid overflow.
574 // Other overflow doesn't matter because we only care about the bottom
575 // W bits of the result.
576 APInt OddFactorial(W, 1);
577 unsigned T = 1;
578 for (unsigned i = 3; i <= K; ++i) {
579 APInt Mult(W, i);
580 unsigned TwoFactors = Mult.countTrailingZeros();
581 T += TwoFactors;
582 Mult = Mult.lshr(TwoFactors);
583 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000584 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000585
Eli Friedmanb42a6262008-08-04 23:49:06 +0000586 // We need at least W + T bits for the multiplication step
587 // FIXME: A temporary hack; we round up the bitwidths
588 // to the nearest power of 2 to be nice to the code generator.
589 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
590 // FIXME: Temporary hack to avoid generating integers that are too wide.
591 // Although, it's not completely clear how to determine how much
592 // widening is safe; for example, on X86, we can't really widen
593 // beyond 64 because we need to be able to do multiplication
594 // that's CalculationBits wide, but on X86-64, we can safely widen up to
595 // 128 bits.
596 if (CalculationBits > 64)
597 return new SCEVCouldNotCompute();
598
599 // Calcuate 2^T, at width T+W.
600 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
601
602 // Calculate the multiplicative inverse of K! / 2^T;
603 // this multiplication factor will perform the exact division by
604 // K! / 2^T.
605 APInt Mod = APInt::getSignedMinValue(W+1);
606 APInt MultiplyFactor = OddFactorial.zext(W+1);
607 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
608 MultiplyFactor = MultiplyFactor.trunc(W);
609
610 // Calculate the product, at width T+W
611 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
612 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
613 for (unsigned i = 1; i != K; ++i) {
614 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
615 Dividend = SE.getMulExpr(Dividend,
616 SE.getTruncateOrZeroExtend(S, CalculationTy));
617 }
618
619 // Divide by 2^T
620 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
621
622 // Truncate the result, and divide by K! / 2^T.
623
624 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
625 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000626}
627
Chris Lattner53e677a2004-04-02 20:23:17 +0000628/// evaluateAtIteration - Return the value of this chain of recurrences at
629/// the specified iteration number. We can evaluate this recurrence by
630/// multiplying each element in the chain by the binomial coefficient
631/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
632///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000633/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000634///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000635/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000636///
Dan Gohman246b2562007-10-22 18:31:58 +0000637SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
638 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000639 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000640 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000641 // The computation is correct in the face of overflow provided that the
642 // multiplication is performed _after_ the evaluation of the binomial
643 // coefficient.
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000644 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
645 cast<IntegerType>(getType()));
646 if (isa<SCEVCouldNotCompute>(Coeff))
647 return Coeff;
648
649 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000650 }
651 return Result;
652}
653
Chris Lattner53e677a2004-04-02 20:23:17 +0000654//===----------------------------------------------------------------------===//
655// SCEV Expression folder implementations
656//===----------------------------------------------------------------------===//
657
Dan Gohman246b2562007-10-22 18:31:58 +0000658SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000659 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000660 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000661 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000662
663 // If the input value is a chrec scev made out of constants, truncate
664 // all of the constants.
665 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
666 std::vector<SCEVHandle> Operands;
667 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
668 // FIXME: This should allow truncation of other expression types!
669 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000670 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000671 else
672 break;
673 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000674 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000675 }
676
Chris Lattnerb3364092006-10-04 21:49:37 +0000677 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000678 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
679 return Result;
680}
681
Dan Gohman246b2562007-10-22 18:31:58 +0000682SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000683 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000684 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000685 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000686
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 zero extend all of the
689 // operands (often constants). This would allow analysis of something like
690 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
691
Chris Lattnerb3364092006-10-04 21:49:37 +0000692 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000693 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
694 return Result;
695}
696
Dan Gohman246b2562007-10-22 18:31:58 +0000697SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000698 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000699 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000700 ConstantExpr::getSExt(SC->getValue(), Ty));
701
702 // FIXME: If the input value is a chrec scev, and we can prove that the value
703 // did not overflow the old, smaller, value, we can sign extend all of the
704 // operands (often constants). This would allow analysis of something like
705 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
706
707 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
708 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
709 return Result;
710}
711
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000712/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
713/// of the input value to the specified type. If the type must be
714/// extended, it is zero extended.
715SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
716 const Type *Ty) {
717 const Type *SrcTy = V->getType();
718 assert(SrcTy->isInteger() && Ty->isInteger() &&
719 "Cannot truncate or zero extend with non-integer arguments!");
720 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
721 return V; // No conversion
722 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
723 return getTruncateExpr(V, Ty);
724 return getZeroExtendExpr(V, Ty);
725}
726
Chris Lattner53e677a2004-04-02 20:23:17 +0000727// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000728SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000729 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000730 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000731
732 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000733 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000734
735 // If there are any constants, fold them together.
736 unsigned Idx = 0;
737 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
738 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000739 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000740 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
741 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000742 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
743 RHSC->getValue()->getValue());
744 Ops[0] = getConstant(Fold);
745 Ops.erase(Ops.begin()+1); // Erase the folded element
746 if (Ops.size() == 1) return Ops[0];
747 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000748 }
749
750 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000751 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000752 Ops.erase(Ops.begin());
753 --Idx;
754 }
755 }
756
Chris Lattner627018b2004-04-07 16:16:11 +0000757 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000758
Chris Lattner53e677a2004-04-02 20:23:17 +0000759 // Okay, check to see if the same value occurs in the operand list twice. If
760 // so, merge them together into an multiply expression. Since we sorted the
761 // list, these values are required to be adjacent.
762 const Type *Ty = Ops[0]->getType();
763 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
764 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
765 // Found a match, merge the two values into a multiply, and add any
766 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000767 SCEVHandle Two = getIntegerSCEV(2, Ty);
768 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000769 if (Ops.size() == 2)
770 return Mul;
771 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
772 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000773 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000774 }
775
Dan Gohmanf50cd742007-06-18 19:30:09 +0000776 // Now we know the first non-constant operand. Skip past any cast SCEVs.
777 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
778 ++Idx;
779
780 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000781 if (Idx < Ops.size()) {
782 bool DeletedAdd = false;
783 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
784 // If we have an add, expand the add operands onto the end of the operands
785 // list.
786 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
787 Ops.erase(Ops.begin()+Idx);
788 DeletedAdd = true;
789 }
790
791 // If we deleted at least one add, we added operands to the end of the list,
792 // and they are not necessarily sorted. Recurse to resort and resimplify
793 // any operands we just aquired.
794 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000795 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000796 }
797
798 // Skip over the add expression until we get to a multiply.
799 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
800 ++Idx;
801
802 // If we are adding something to a multiply expression, make sure the
803 // something is not already an operand of the multiply. If so, merge it into
804 // the multiply.
805 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
806 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
807 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
808 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
809 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000810 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000811 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
812 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
813 if (Mul->getNumOperands() != 2) {
814 // If the multiply has more than two operands, we must get the
815 // Y*Z term.
816 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
817 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000818 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000819 }
Dan Gohman246b2562007-10-22 18:31:58 +0000820 SCEVHandle One = getIntegerSCEV(1, Ty);
821 SCEVHandle AddOne = getAddExpr(InnerMul, One);
822 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000823 if (Ops.size() == 2) return OuterMul;
824 if (AddOp < Idx) {
825 Ops.erase(Ops.begin()+AddOp);
826 Ops.erase(Ops.begin()+Idx-1);
827 } else {
828 Ops.erase(Ops.begin()+Idx);
829 Ops.erase(Ops.begin()+AddOp-1);
830 }
831 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000832 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000833 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000834
Chris Lattner53e677a2004-04-02 20:23:17 +0000835 // Check this multiply against other multiplies being added together.
836 for (unsigned OtherMulIdx = Idx+1;
837 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
838 ++OtherMulIdx) {
839 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
840 // If MulOp occurs in OtherMul, we can fold the two multiplies
841 // together.
842 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
843 OMulOp != e; ++OMulOp)
844 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
845 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
846 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
847 if (Mul->getNumOperands() != 2) {
848 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
849 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000850 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000851 }
852 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
853 if (OtherMul->getNumOperands() != 2) {
854 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
855 OtherMul->op_end());
856 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000857 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000858 }
Dan Gohman246b2562007-10-22 18:31:58 +0000859 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
860 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000861 if (Ops.size() == 2) return OuterMul;
862 Ops.erase(Ops.begin()+Idx);
863 Ops.erase(Ops.begin()+OtherMulIdx-1);
864 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000865 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000866 }
867 }
868 }
869 }
870
871 // If there are any add recurrences in the operands list, see if any other
872 // added values are loop invariant. If so, we can fold them into the
873 // recurrence.
874 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
875 ++Idx;
876
877 // Scan over all recurrences, trying to fold loop invariants into them.
878 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
879 // Scan all of the other operands to this add and add them to the vector if
880 // they are loop invariant w.r.t. the recurrence.
881 std::vector<SCEVHandle> LIOps;
882 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
883 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
884 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
885 LIOps.push_back(Ops[i]);
886 Ops.erase(Ops.begin()+i);
887 --i; --e;
888 }
889
890 // If we found some loop invariants, fold them into the recurrence.
891 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +0000892 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +0000893 LIOps.push_back(AddRec->getStart());
894
895 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000896 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000897
Dan Gohman246b2562007-10-22 18:31:58 +0000898 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000899 // If all of the other operands were loop invariant, we are done.
900 if (Ops.size() == 1) return NewRec;
901
902 // Otherwise, add the folded AddRec by the non-liv parts.
903 for (unsigned i = 0;; ++i)
904 if (Ops[i] == AddRec) {
905 Ops[i] = NewRec;
906 break;
907 }
Dan Gohman246b2562007-10-22 18:31:58 +0000908 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000909 }
910
911 // Okay, if there weren't any loop invariants to be folded, check to see if
912 // there are multiple AddRec's with the same loop induction variable being
913 // added together. If so, we can fold them.
914 for (unsigned OtherIdx = Idx+1;
915 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
916 if (OtherIdx != Idx) {
917 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
918 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
919 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
920 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
921 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
922 if (i >= NewOps.size()) {
923 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
924 OtherAddRec->op_end());
925 break;
926 }
Dan Gohman246b2562007-10-22 18:31:58 +0000927 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000928 }
Dan Gohman246b2562007-10-22 18:31:58 +0000929 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000930
931 if (Ops.size() == 2) return NewAddRec;
932
933 Ops.erase(Ops.begin()+Idx);
934 Ops.erase(Ops.begin()+OtherIdx-1);
935 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000936 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000937 }
938 }
939
940 // Otherwise couldn't fold anything into this recurrence. Move onto the
941 // next one.
942 }
943
944 // Okay, it looks like we really DO need an add expr. Check to see if we
945 // already have one, otherwise create a new one.
946 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000947 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
948 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000949 if (Result == 0) Result = new SCEVAddExpr(Ops);
950 return Result;
951}
952
953
Dan Gohman246b2562007-10-22 18:31:58 +0000954SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000955 assert(!Ops.empty() && "Cannot get empty mul!");
956
957 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000958 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000959
960 // If there are any constants, fold them together.
961 unsigned Idx = 0;
962 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
963
964 // C1*(C2+V) -> C1*C2 + C1*V
965 if (Ops.size() == 2)
966 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
967 if (Add->getNumOperands() == 2 &&
968 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000969 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
970 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000971
972
973 ++Idx;
974 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
975 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000976 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
977 RHSC->getValue()->getValue());
978 Ops[0] = getConstant(Fold);
979 Ops.erase(Ops.begin()+1); // Erase the folded element
980 if (Ops.size() == 1) return Ops[0];
981 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000982 }
983
984 // If we are left with a constant one being multiplied, strip it off.
985 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
986 Ops.erase(Ops.begin());
987 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000988 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000989 // If we have a multiply of zero, it will always be zero.
990 return Ops[0];
991 }
992 }
993
994 // Skip over the add expression until we get to a multiply.
995 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
996 ++Idx;
997
998 if (Ops.size() == 1)
999 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001000
Chris Lattner53e677a2004-04-02 20:23:17 +00001001 // If there are mul operands inline them all into this expression.
1002 if (Idx < Ops.size()) {
1003 bool DeletedMul = false;
1004 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1005 // If we have an mul, expand the mul operands onto the end of the operands
1006 // list.
1007 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1008 Ops.erase(Ops.begin()+Idx);
1009 DeletedMul = true;
1010 }
1011
1012 // If we deleted at least one mul, we added operands to the end of the list,
1013 // and they are not necessarily sorted. Recurse to resort and resimplify
1014 // any operands we just aquired.
1015 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001016 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001017 }
1018
1019 // If there are any add recurrences in the operands list, see if any other
1020 // added values are loop invariant. If so, we can fold them into the
1021 // recurrence.
1022 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1023 ++Idx;
1024
1025 // Scan over all recurrences, trying to fold loop invariants into them.
1026 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1027 // Scan all of the other operands to this mul and add them to the vector if
1028 // they are loop invariant w.r.t. the recurrence.
1029 std::vector<SCEVHandle> LIOps;
1030 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1031 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1032 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1033 LIOps.push_back(Ops[i]);
1034 Ops.erase(Ops.begin()+i);
1035 --i; --e;
1036 }
1037
1038 // If we found some loop invariants, fold them into the recurrence.
1039 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001040 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001041 std::vector<SCEVHandle> NewOps;
1042 NewOps.reserve(AddRec->getNumOperands());
1043 if (LIOps.size() == 1) {
1044 SCEV *Scale = LIOps[0];
1045 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001046 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001047 } else {
1048 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1049 std::vector<SCEVHandle> MulOps(LIOps);
1050 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001051 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001052 }
1053 }
1054
Dan Gohman246b2562007-10-22 18:31:58 +00001055 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001056
1057 // If all of the other operands were loop invariant, we are done.
1058 if (Ops.size() == 1) return NewRec;
1059
1060 // Otherwise, multiply the folded AddRec by the non-liv parts.
1061 for (unsigned i = 0;; ++i)
1062 if (Ops[i] == AddRec) {
1063 Ops[i] = NewRec;
1064 break;
1065 }
Dan Gohman246b2562007-10-22 18:31:58 +00001066 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001067 }
1068
1069 // Okay, if there weren't any loop invariants to be folded, check to see if
1070 // there are multiple AddRec's with the same loop induction variable being
1071 // multiplied together. If so, we can fold them.
1072 for (unsigned OtherIdx = Idx+1;
1073 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1074 if (OtherIdx != Idx) {
1075 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1076 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1077 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1078 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001079 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001080 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001081 SCEVHandle B = F->getStepRecurrence(*this);
1082 SCEVHandle D = G->getStepRecurrence(*this);
1083 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1084 getMulExpr(G, B),
1085 getMulExpr(B, D));
1086 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1087 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001088 if (Ops.size() == 2) return NewAddRec;
1089
1090 Ops.erase(Ops.begin()+Idx);
1091 Ops.erase(Ops.begin()+OtherIdx-1);
1092 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001093 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001094 }
1095 }
1096
1097 // Otherwise couldn't fold anything into this recurrence. Move onto the
1098 // next one.
1099 }
1100
1101 // Okay, it looks like we really DO need an mul expr. Check to see if we
1102 // already have one, otherwise create a new one.
1103 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001104 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1105 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001106 if (Result == 0)
1107 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001108 return Result;
1109}
1110
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001111SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001112 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1113 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001114 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001115
1116 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1117 Constant *LHSCV = LHSC->getValue();
1118 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001119 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001120 }
1121 }
1122
1123 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1124
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001125 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1126 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001127 return Result;
1128}
1129
1130
1131/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1132/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001133SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001134 const SCEVHandle &Step, const Loop *L) {
1135 std::vector<SCEVHandle> Operands;
1136 Operands.push_back(Start);
1137 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1138 if (StepChrec->getLoop() == L) {
1139 Operands.insert(Operands.end(), StepChrec->op_begin(),
1140 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001141 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001142 }
1143
1144 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001145 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001146}
1147
1148/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1149/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001150SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001151 const Loop *L) {
1152 if (Operands.size() == 1) return Operands[0];
1153
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001154 if (Operands.back()->isZero()) {
1155 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001156 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001157 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001158
Dan Gohmand9cc7492008-08-08 18:33:12 +00001159 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1160 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1161 const Loop* NestedLoop = NestedAR->getLoop();
1162 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1163 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1164 NestedAR->op_end());
1165 SCEVHandle NestedARHandle(NestedAR);
1166 Operands[0] = NestedAR->getStart();
1167 NestedOperands[0] = getAddRecExpr(Operands, L);
1168 return getAddRecExpr(NestedOperands, NestedLoop);
1169 }
1170 }
1171
Chris Lattner53e677a2004-04-02 20:23:17 +00001172 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001173 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1174 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001175 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1176 return Result;
1177}
1178
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001179SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1180 const SCEVHandle &RHS) {
1181 std::vector<SCEVHandle> Ops;
1182 Ops.push_back(LHS);
1183 Ops.push_back(RHS);
1184 return getSMaxExpr(Ops);
1185}
1186
1187SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1188 assert(!Ops.empty() && "Cannot get empty smax!");
1189 if (Ops.size() == 1) return Ops[0];
1190
1191 // Sort by complexity, this groups all similar expression types together.
1192 GroupByComplexity(Ops);
1193
1194 // If there are any constants, fold them together.
1195 unsigned Idx = 0;
1196 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1197 ++Idx;
1198 assert(Idx < Ops.size());
1199 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1200 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001201 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001202 APIntOps::smax(LHSC->getValue()->getValue(),
1203 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001204 Ops[0] = getConstant(Fold);
1205 Ops.erase(Ops.begin()+1); // Erase the folded element
1206 if (Ops.size() == 1) return Ops[0];
1207 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001208 }
1209
1210 // If we are left with a constant -inf, strip it off.
1211 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1212 Ops.erase(Ops.begin());
1213 --Idx;
1214 }
1215 }
1216
1217 if (Ops.size() == 1) return Ops[0];
1218
1219 // Find the first SMax
1220 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1221 ++Idx;
1222
1223 // Check to see if one of the operands is an SMax. If so, expand its operands
1224 // onto our operand list, and recurse to simplify.
1225 if (Idx < Ops.size()) {
1226 bool DeletedSMax = false;
1227 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1228 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1229 Ops.erase(Ops.begin()+Idx);
1230 DeletedSMax = true;
1231 }
1232
1233 if (DeletedSMax)
1234 return getSMaxExpr(Ops);
1235 }
1236
1237 // Okay, check to see if the same value occurs in the operand list twice. If
1238 // so, delete one. Since we sorted the list, these values are required to
1239 // be adjacent.
1240 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1241 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1242 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1243 --i; --e;
1244 }
1245
1246 if (Ops.size() == 1) return Ops[0];
1247
1248 assert(!Ops.empty() && "Reduced smax down to nothing!");
1249
Nick Lewycky3e630762008-02-20 06:48:22 +00001250 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001251 // already have one, otherwise create a new one.
1252 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1253 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1254 SCEVOps)];
1255 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1256 return Result;
1257}
1258
Nick Lewycky3e630762008-02-20 06:48:22 +00001259SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1260 const SCEVHandle &RHS) {
1261 std::vector<SCEVHandle> Ops;
1262 Ops.push_back(LHS);
1263 Ops.push_back(RHS);
1264 return getUMaxExpr(Ops);
1265}
1266
1267SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1268 assert(!Ops.empty() && "Cannot get empty umax!");
1269 if (Ops.size() == 1) return Ops[0];
1270
1271 // Sort by complexity, this groups all similar expression types together.
1272 GroupByComplexity(Ops);
1273
1274 // If there are any constants, fold them together.
1275 unsigned Idx = 0;
1276 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1277 ++Idx;
1278 assert(Idx < Ops.size());
1279 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1280 // We found two constants, fold them together!
1281 ConstantInt *Fold = ConstantInt::get(
1282 APIntOps::umax(LHSC->getValue()->getValue(),
1283 RHSC->getValue()->getValue()));
1284 Ops[0] = getConstant(Fold);
1285 Ops.erase(Ops.begin()+1); // Erase the folded element
1286 if (Ops.size() == 1) return Ops[0];
1287 LHSC = cast<SCEVConstant>(Ops[0]);
1288 }
1289
1290 // If we are left with a constant zero, strip it off.
1291 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1292 Ops.erase(Ops.begin());
1293 --Idx;
1294 }
1295 }
1296
1297 if (Ops.size() == 1) return Ops[0];
1298
1299 // Find the first UMax
1300 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1301 ++Idx;
1302
1303 // Check to see if one of the operands is a UMax. If so, expand its operands
1304 // onto our operand list, and recurse to simplify.
1305 if (Idx < Ops.size()) {
1306 bool DeletedUMax = false;
1307 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1308 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1309 Ops.erase(Ops.begin()+Idx);
1310 DeletedUMax = true;
1311 }
1312
1313 if (DeletedUMax)
1314 return getUMaxExpr(Ops);
1315 }
1316
1317 // Okay, check to see if the same value occurs in the operand list twice. If
1318 // so, delete one. Since we sorted the list, these values are required to
1319 // be adjacent.
1320 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1321 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1322 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1323 --i; --e;
1324 }
1325
1326 if (Ops.size() == 1) return Ops[0];
1327
1328 assert(!Ops.empty() && "Reduced umax down to nothing!");
1329
1330 // Okay, it looks like we really DO need a umax expr. Check to see if we
1331 // already have one, otherwise create a new one.
1332 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1333 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1334 SCEVOps)];
1335 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1336 return Result;
1337}
1338
Dan Gohman246b2562007-10-22 18:31:58 +00001339SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001340 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001341 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001342 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001343 if (Result == 0) Result = new SCEVUnknown(V);
1344 return Result;
1345}
1346
Chris Lattner53e677a2004-04-02 20:23:17 +00001347
1348//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001349// ScalarEvolutionsImpl Definition and Implementation
1350//===----------------------------------------------------------------------===//
1351//
1352/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1353/// evolution code.
1354///
1355namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001356 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001357 /// SE - A reference to the public ScalarEvolution object.
1358 ScalarEvolution &SE;
1359
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 /// F - The function we are analyzing.
1361 ///
1362 Function &F;
1363
1364 /// LI - The loop information for the function we are currently analyzing.
1365 ///
1366 LoopInfo &LI;
1367
1368 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1369 /// things.
1370 SCEVHandle UnknownValue;
1371
1372 /// Scalars - This is a cache of the scalars we have analyzed so far.
1373 ///
1374 std::map<Value*, SCEVHandle> Scalars;
1375
1376 /// IterationCounts - Cache the iteration count of the loops for this
1377 /// function as they are computed.
1378 std::map<const Loop*, SCEVHandle> IterationCounts;
1379
Chris Lattner3221ad02004-04-17 22:58:41 +00001380 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1381 /// the PHI instructions that we attempt to compute constant evolutions for.
1382 /// This allows us to avoid potentially expensive recomputation of these
1383 /// properties. An instruction maps to null if we are unable to compute its
1384 /// exit value.
1385 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001386
Chris Lattner53e677a2004-04-02 20:23:17 +00001387 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001388 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1389 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001390
1391 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1392 /// expression and create a new one.
1393 SCEVHandle getSCEV(Value *V);
1394
Chris Lattnera0740fb2005-08-09 23:36:33 +00001395 /// hasSCEV - Return true if the SCEV for this value has already been
1396 /// computed.
1397 bool hasSCEV(Value *V) const {
1398 return Scalars.count(V);
1399 }
1400
1401 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1402 /// the specified value.
1403 void setSCEV(Value *V, const SCEVHandle &H) {
1404 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1405 assert(isNew && "This entry already existed!");
Devang Patel89d0a4d2008-11-11 19:17:41 +00001406 isNew = false;
Chris Lattnera0740fb2005-08-09 23:36:33 +00001407 }
1408
1409
Chris Lattner53e677a2004-04-02 20:23:17 +00001410 /// getSCEVAtScope - Compute the value of the specified expression within
1411 /// the indicated loop (which may be null to indicate in no loop). If the
1412 /// expression cannot be evaluated, return UnknownValue itself.
1413 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1414
1415
1416 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1417 /// an analyzable loop-invariant iteration count.
1418 bool hasLoopInvariantIterationCount(const Loop *L);
1419
1420 /// getIterationCount - If the specified loop has a predictable iteration
1421 /// count, return it. Note that it is not valid to call this method on a
1422 /// loop without a loop-invariant iteration count.
1423 SCEVHandle getIterationCount(const Loop *L);
1424
Dan Gohman5cec4db2007-06-19 14:28:31 +00001425 /// deleteValueFromRecords - This method should be called by the
1426 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001427 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001428 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001429
1430 private:
1431 /// createSCEV - We know that there is no SCEV for the specified value.
1432 /// Analyze the expression.
1433 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001434
1435 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1436 /// SCEVs.
1437 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001438
1439 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1440 /// for the specified instruction and replaces any references to the
1441 /// symbolic value SymName with the specified value. This is used during
1442 /// PHI resolution.
1443 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1444 const SCEVHandle &SymName,
1445 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001446
1447 /// ComputeIterationCount - Compute the number of times the specified loop
1448 /// will iterate.
1449 SCEVHandle ComputeIterationCount(const Loop *L);
1450
Chris Lattner673e02b2004-10-12 01:49:27 +00001451 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001452 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001453 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1454 Constant *RHS,
1455 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001456 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001457
Chris Lattner7980fb92004-04-17 18:36:24 +00001458 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1459 /// constant number of times (the condition evolves only from constants),
1460 /// try to evaluate a few iterations of the loop until we get the exit
1461 /// condition gets a value of ExitWhen (true or false). If we cannot
1462 /// evaluate the trip count of the loop, return UnknownValue.
1463 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1464 bool ExitWhen);
1465
Chris Lattner53e677a2004-04-02 20:23:17 +00001466 /// HowFarToZero - Return the number of times a backedge comparing the
1467 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001468 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001469 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1470
1471 /// HowFarToNonZero - Return the number of times a backedge checking the
1472 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001473 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001475
Chris Lattnerdb25de42005-08-15 23:33:51 +00001476 /// HowManyLessThans - Return the number of times a backedge containing the
1477 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001478 /// UnknownValue. isSigned specifies whether the less-than is signed.
1479 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewyckydd643f22008-11-18 15:10:54 +00001480 bool isSigned, bool trueWhenEqual);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001481
Dan Gohmanfd6edef2008-09-15 22:18:04 +00001482 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1483 /// (which may not be an immediate predecessor) which has exactly one
1484 /// successor from which BB is reachable, or null if no such block is
1485 /// found.
1486 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1487
Nick Lewycky59cff122008-07-12 07:41:32 +00001488 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1489 /// a conditional between LHS and RHS.
Nick Lewyckydd643f22008-11-18 15:10:54 +00001490 bool executesAtLeastOnce(const Loop *L, bool isSigned, bool trueWhenEqual,
1491 SCEV *LHS, SCEV *RHS);
1492
1493 /// potentialInfiniteLoop - Test whether the loop might jump over the exit value
1494 /// due to wrapping.
1495 bool potentialInfiniteLoop(SCEV *Stride, SCEV *RHS, bool isSigned,
1496 bool trueWhenEqual);
Nick Lewycky59cff122008-07-12 07:41:32 +00001497
Chris Lattner3221ad02004-04-17 22:58:41 +00001498 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1499 /// in the header of its containing loop, we know the loop executes a
1500 /// constant number of times, and the PHI node is just a recurrence
1501 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001502 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001503 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 };
1505}
1506
1507//===----------------------------------------------------------------------===//
1508// Basic SCEV Analysis and PHI Idiom Recognition Code
1509//
1510
Dan Gohman5cec4db2007-06-19 14:28:31 +00001511/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001512/// client before it removes an instruction from the program, to make sure
1513/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001514void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1515 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001516
Dan Gohman5cec4db2007-06-19 14:28:31 +00001517 if (Scalars.erase(V)) {
1518 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001519 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001520 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001521 }
1522
1523 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001524 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001525 Worklist.pop_back();
1526
Dan Gohman5cec4db2007-06-19 14:28:31 +00001527 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001528 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001529 Instruction *Inst = cast<Instruction>(*UI);
1530 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001531 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001532 ConstantEvolutionLoopExitValue.erase(PN);
1533 Worklist.push_back(Inst);
1534 }
1535 }
1536 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001537}
1538
1539
1540/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1541/// expression and create a new one.
1542SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1543 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1544
1545 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1546 if (I != Scalars.end()) return I->second;
1547 SCEVHandle S = createSCEV(V);
1548 Scalars.insert(std::make_pair(V, S));
1549 return S;
1550}
1551
Chris Lattner4dc534c2005-02-13 04:37:18 +00001552/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1553/// the specified instruction and replaces any references to the symbolic value
1554/// SymName with the specified value. This is used during PHI resolution.
1555void ScalarEvolutionsImpl::
1556ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1557 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001558 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001559 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001560
Chris Lattner4dc534c2005-02-13 04:37:18 +00001561 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001562 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001563 if (NV == SI->second) return; // No change.
1564
1565 SI->second = NV; // Update the scalars map!
1566
1567 // Any instruction values that use this instruction might also need to be
1568 // updated!
1569 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1570 UI != E; ++UI)
1571 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1572}
Chris Lattner53e677a2004-04-02 20:23:17 +00001573
1574/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1575/// a loop header, making it a potential recurrence, or it doesn't.
1576///
1577SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1578 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1579 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1580 if (L->getHeader() == PN->getParent()) {
1581 // If it lives in the loop header, it has two incoming values, one
1582 // from outside the loop, and one from inside.
1583 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1584 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001585
Chris Lattner53e677a2004-04-02 20:23:17 +00001586 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001587 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001588 assert(Scalars.find(PN) == Scalars.end() &&
1589 "PHI node already processed?");
1590 Scalars.insert(std::make_pair(PN, SymbolicName));
1591
1592 // Using this symbolic name for the PHI, analyze the value coming around
1593 // the back-edge.
1594 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1595
1596 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1597 // has a special value for the first iteration of the loop.
1598
1599 // If the value coming around the backedge is an add with the symbolic
1600 // value we just inserted, then we found a simple induction variable!
1601 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1602 // If there is a single occurrence of the symbolic value, replace it
1603 // with a recurrence.
1604 unsigned FoundIndex = Add->getNumOperands();
1605 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1606 if (Add->getOperand(i) == SymbolicName)
1607 if (FoundIndex == e) {
1608 FoundIndex = i;
1609 break;
1610 }
1611
1612 if (FoundIndex != Add->getNumOperands()) {
1613 // Create an add with everything but the specified operand.
1614 std::vector<SCEVHandle> Ops;
1615 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1616 if (i != FoundIndex)
1617 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001618 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001619
1620 // This is not a valid addrec if the step amount is varying each
1621 // loop iteration, but is not itself an addrec in this loop.
1622 if (Accum->isLoopInvariant(L) ||
1623 (isa<SCEVAddRecExpr>(Accum) &&
1624 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1625 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001626 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001627
1628 // Okay, for the entire analysis of this edge we assumed the PHI
1629 // to be symbolic. We now need to go back and update all of the
1630 // entries for the scalars that use the PHI (except for the PHI
1631 // itself) to use the new analyzed value instead of the "symbolic"
1632 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001633 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001634 return PHISCEV;
1635 }
1636 }
Chris Lattner97156e72006-04-26 18:34:07 +00001637 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1638 // Otherwise, this could be a loop like this:
1639 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1640 // In this case, j = {1,+,1} and BEValue is j.
1641 // Because the other in-value of i (0) fits the evolution of BEValue
1642 // i really is an addrec evolution.
1643 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1644 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1645
1646 // If StartVal = j.start - j.stride, we can use StartVal as the
1647 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001648 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1649 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001650 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001651 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001652
1653 // Okay, for the entire analysis of this edge we assumed the PHI
1654 // to be symbolic. We now need to go back and update all of the
1655 // entries for the scalars that use the PHI (except for the PHI
1656 // itself) to use the new analyzed value instead of the "symbolic"
1657 // value.
1658 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1659 return PHISCEV;
1660 }
1661 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001662 }
1663
1664 return SymbolicName;
1665 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001666
Chris Lattner53e677a2004-04-02 20:23:17 +00001667 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001668 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001669}
1670
Nick Lewycky83bb0052007-11-22 07:59:40 +00001671/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1672/// guaranteed to end in (at every loop iteration). It is, at the same time,
1673/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1674/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1675static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1676 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001677 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001678
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001679 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001680 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1681
1682 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1683 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1684 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1685 }
1686
1687 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1688 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1689 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1690 }
1691
Chris Lattnera17f0392006-12-12 02:26:09 +00001692 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001693 // The result is the min of all operands results.
1694 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1695 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1696 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1697 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001698 }
1699
1700 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001701 // The result is the sum of all operands results.
1702 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1703 uint32_t BitWidth = M->getBitWidth();
1704 for (unsigned i = 1, e = M->getNumOperands();
1705 SumOpRes != BitWidth && i != e; ++i)
1706 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1707 BitWidth);
1708 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001709 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001710
Chris Lattnera17f0392006-12-12 02:26:09 +00001711 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001712 // The result is the min of all operands results.
1713 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1714 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1715 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1716 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001717 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001718
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001719 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1720 // The result is the min of all operands results.
1721 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1722 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1723 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1724 return MinOpRes;
1725 }
1726
Nick Lewycky3e630762008-02-20 06:48:22 +00001727 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1728 // The result is the min of all operands results.
1729 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1730 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1731 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1732 return MinOpRes;
1733 }
1734
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001735 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001736 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001737}
Chris Lattner53e677a2004-04-02 20:23:17 +00001738
1739/// createSCEV - We know that there is no SCEV for the specified value.
1740/// Analyze the expression.
1741///
1742SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001743 if (!isa<IntegerType>(V->getType()))
1744 return SE.getUnknown(V);
1745
Dan Gohman6c459a22008-06-22 19:56:46 +00001746 unsigned Opcode = Instruction::UserOp1;
1747 if (Instruction *I = dyn_cast<Instruction>(V))
1748 Opcode = I->getOpcode();
1749 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1750 Opcode = CE->getOpcode();
1751 else
1752 return SE.getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001753
Dan Gohman6c459a22008-06-22 19:56:46 +00001754 User *U = cast<User>(V);
1755 switch (Opcode) {
1756 case Instruction::Add:
1757 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1758 getSCEV(U->getOperand(1)));
1759 case Instruction::Mul:
1760 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1761 getSCEV(U->getOperand(1)));
1762 case Instruction::UDiv:
1763 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1764 getSCEV(U->getOperand(1)));
1765 case Instruction::Sub:
1766 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1767 getSCEV(U->getOperand(1)));
1768 case Instruction::Or:
1769 // If the RHS of the Or is a constant, we may have something like:
1770 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1771 // optimizations will transparently handle this case.
1772 //
1773 // In order for this transformation to be safe, the LHS must be of the
1774 // form X*(2^n) and the Or constant must be less than 2^n.
1775 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1776 SCEVHandle LHS = getSCEV(U->getOperand(0));
1777 const APInt &CIVal = CI->getValue();
1778 if (GetMinTrailingZeros(LHS) >=
1779 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1780 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001781 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001782 break;
1783 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001784 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001785 // If the RHS of the xor is a signbit, then this is just an add.
1786 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001787 if (CI->getValue().isSignBit())
1788 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1789 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001790
1791 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001792 else if (CI->isAllOnesValue())
1793 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1794 }
1795 break;
1796
1797 case Instruction::Shl:
1798 // Turn shift left of a constant amount into a multiply.
1799 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1800 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1801 Constant *X = ConstantInt::get(
1802 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1803 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1804 }
1805 break;
1806
Nick Lewycky01eaf802008-07-07 06:15:49 +00001807 case Instruction::LShr:
1808 // Turn logical shift right of a constant into a unsigned divide.
1809 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1810 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1811 Constant *X = ConstantInt::get(
1812 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1813 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1814 }
1815 break;
1816
Dan Gohman6c459a22008-06-22 19:56:46 +00001817 case Instruction::Trunc:
1818 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1819
1820 case Instruction::ZExt:
1821 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1822
1823 case Instruction::SExt:
1824 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1825
1826 case Instruction::BitCast:
1827 // BitCasts are no-op casts so we just eliminate the cast.
1828 if (U->getType()->isInteger() &&
1829 U->getOperand(0)->getType()->isInteger())
1830 return getSCEV(U->getOperand(0));
1831 break;
1832
1833 case Instruction::PHI:
1834 return createNodeForPHI(cast<PHINode>(U));
1835
1836 case Instruction::Select:
1837 // This could be a smax or umax that was lowered earlier.
1838 // Try to recover it.
1839 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1840 Value *LHS = ICI->getOperand(0);
1841 Value *RHS = ICI->getOperand(1);
1842 switch (ICI->getPredicate()) {
1843 case ICmpInst::ICMP_SLT:
1844 case ICmpInst::ICMP_SLE:
1845 std::swap(LHS, RHS);
1846 // fall through
1847 case ICmpInst::ICMP_SGT:
1848 case ICmpInst::ICMP_SGE:
1849 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1850 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1851 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00001852 // ~smax(~x, ~y) == smin(x, y).
1853 return SE.getNotSCEV(SE.getSMaxExpr(
1854 SE.getNotSCEV(getSCEV(LHS)),
1855 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00001856 break;
1857 case ICmpInst::ICMP_ULT:
1858 case ICmpInst::ICMP_ULE:
1859 std::swap(LHS, RHS);
1860 // fall through
1861 case ICmpInst::ICMP_UGT:
1862 case ICmpInst::ICMP_UGE:
1863 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1864 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1865 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1866 // ~umax(~x, ~y) == umin(x, y)
1867 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1868 SE.getNotSCEV(getSCEV(RHS))));
1869 break;
1870 default:
1871 break;
1872 }
1873 }
1874
1875 default: // We cannot analyze this expression.
1876 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001877 }
1878
Dan Gohman246b2562007-10-22 18:31:58 +00001879 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001880}
1881
1882
1883
1884//===----------------------------------------------------------------------===//
1885// Iteration Count Computation Code
1886//
1887
1888/// getIterationCount - If the specified loop has a predictable iteration
1889/// count, return it. Note that it is not valid to call this method on a
1890/// loop without a loop-invariant iteration count.
1891SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1892 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1893 if (I == IterationCounts.end()) {
1894 SCEVHandle ItCount = ComputeIterationCount(L);
1895 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1896 if (ItCount != UnknownValue) {
1897 assert(ItCount->isLoopInvariant(L) &&
1898 "Computed trip count isn't loop invariant for loop!");
1899 ++NumTripCountsComputed;
1900 } else if (isa<PHINode>(L->getHeader()->begin())) {
1901 // Only count loops that have phi nodes as not being computable.
1902 ++NumTripCountsNotComputed;
1903 }
1904 }
1905 return I->second;
1906}
1907
1908/// ComputeIterationCount - Compute the number of times the specified loop
1909/// will iterate.
1910SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1911 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001912 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001913 L->getExitBlocks(ExitBlocks);
1914 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001915
1916 // Okay, there is one exit block. Try to find the condition that causes the
1917 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001918 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001919
1920 BasicBlock *ExitingBlock = 0;
1921 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1922 PI != E; ++PI)
1923 if (L->contains(*PI)) {
1924 if (ExitingBlock == 0)
1925 ExitingBlock = *PI;
1926 else
1927 return UnknownValue; // More than one block exiting!
1928 }
1929 assert(ExitingBlock && "No exits from loop, something is broken!");
1930
1931 // Okay, we've computed the exiting block. See what condition causes us to
1932 // exit.
1933 //
1934 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001935 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1936 if (ExitBr == 0) return UnknownValue;
1937 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001938
1939 // At this point, we know we have a conditional branch that determines whether
1940 // the loop is exited. However, we don't know if the branch is executed each
1941 // time through the loop. If not, then the execution count of the branch will
1942 // not be equal to the trip count of the loop.
1943 //
1944 // Currently we check for this by checking to see if the Exit branch goes to
1945 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001946 // times as the loop. We also handle the case where the exit block *is* the
1947 // loop header. This is common for un-rotated loops. More extensive analysis
1948 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001949 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001950 ExitBr->getSuccessor(1) != L->getHeader() &&
1951 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001952 return UnknownValue;
1953
Reid Spencere4d87aa2006-12-23 06:05:41 +00001954 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1955
Nick Lewycky3b711652008-02-21 08:34:02 +00001956 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001957 // Note that ICmpInst deals with pointer comparisons too so we must check
1958 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001959 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001960 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1961 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001962
Reid Spencere4d87aa2006-12-23 06:05:41 +00001963 // If the condition was exit on true, convert the condition to exit on false
1964 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001965 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001966 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001967 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001968 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001969
1970 // Handle common loops like: for (X = "string"; *X; ++X)
1971 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1972 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1973 SCEVHandle ItCnt =
1974 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1975 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1976 }
1977
Chris Lattner53e677a2004-04-02 20:23:17 +00001978 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1979 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1980
1981 // Try to evaluate any dependencies out of the loop.
1982 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1983 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1984 Tmp = getSCEVAtScope(RHS, L);
1985 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1986
Reid Spencere4d87aa2006-12-23 06:05:41 +00001987 // At this point, we would like to compute how many iterations of the
1988 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00001989 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
1990 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00001991 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001992 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001993 }
1994
1995 // FIXME: think about handling pointer comparisons! i.e.:
1996 // while (P != P+100) ++P;
1997
1998 // If we have a comparison of a chrec against a constant, try to use value
1999 // ranges to answer this query.
2000 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2001 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2002 if (AddRec->getLoop() == L) {
2003 // Form the comparison range using the constant of the correct type so
2004 // that the ConstantRange class knows to do a signed or unsigned
2005 // comparison.
2006 ConstantInt *CompVal = RHSC->getValue();
2007 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002008 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002009 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002010 if (CompVal) {
2011 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002012 ConstantRange CompRange(
2013 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002014
Dan Gohman246b2562007-10-22 18:31:58 +00002015 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002016 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2017 }
2018 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002019
Chris Lattner53e677a2004-04-02 20:23:17 +00002020 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002021 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002022 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00002023 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002024 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002025 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002026 }
2027 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002028 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00002029 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002030 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002031 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002032 }
2033 case ICmpInst::ICMP_SLT: {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002034 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002035 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002036 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002037 }
2038 case ICmpInst::ICMP_SGT: {
Eli Friedman068acc32008-07-30 00:04:08 +00002039 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewyckydd643f22008-11-18 15:10:54 +00002040 SE.getNotSCEV(RHS), L, true, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002041 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2042 break;
2043 }
2044 case ICmpInst::ICMP_ULT: {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002045 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002046 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2047 break;
2048 }
2049 case ICmpInst::ICMP_UGT: {
Dale Johannesena0c8fc62008-04-20 16:58:57 +00002050 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewyckydd643f22008-11-18 15:10:54 +00002051 SE.getNotSCEV(RHS), L, false, false);
2052 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2053 break;
2054 }
2055 case ICmpInst::ICMP_SLE: {
2056 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, true);
2057 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2058 break;
2059 }
2060 case ICmpInst::ICMP_SGE: {
2061 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2062 SE.getNotSCEV(RHS), L, true, true);
2063 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2064 break;
2065 }
2066 case ICmpInst::ICMP_ULE: {
2067 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, true);
2068 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2069 break;
2070 }
2071 case ICmpInst::ICMP_UGE: {
2072 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2073 SE.getNotSCEV(RHS), L, false, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002074 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002075 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002076 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002077 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002078#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002079 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002080 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00002081 cerr << "[unsigned] ";
2082 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002083 << Instruction::getOpcodeName(Instruction::ICmp)
2084 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002085#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002086 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002087 }
Chris Lattner7980fb92004-04-17 18:36:24 +00002088 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002089 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002090}
2091
Chris Lattner673e02b2004-10-12 01:49:27 +00002092static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002093EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2094 ScalarEvolution &SE) {
2095 SCEVHandle InVal = SE.getConstant(C);
2096 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002097 assert(isa<SCEVConstant>(Val) &&
2098 "Evaluation of SCEV at constant didn't fold correctly?");
2099 return cast<SCEVConstant>(Val)->getValue();
2100}
2101
2102/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2103/// and a GEP expression (missing the pointer index) indexing into it, return
2104/// the addressed element of the initializer or null if the index expression is
2105/// invalid.
2106static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002107GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002108 const std::vector<ConstantInt*> &Indices) {
2109 Constant *Init = GV->getInitializer();
2110 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002111 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002112 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2113 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2114 Init = cast<Constant>(CS->getOperand(Idx));
2115 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2116 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2117 Init = cast<Constant>(CA->getOperand(Idx));
2118 } else if (isa<ConstantAggregateZero>(Init)) {
2119 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2120 assert(Idx < STy->getNumElements() && "Bad struct index!");
2121 Init = Constant::getNullValue(STy->getElementType(Idx));
2122 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2123 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2124 Init = Constant::getNullValue(ATy->getElementType());
2125 } else {
2126 assert(0 && "Unknown constant aggregate type!");
2127 }
2128 return 0;
2129 } else {
2130 return 0; // Unknown initializer type
2131 }
2132 }
2133 return Init;
2134}
2135
2136/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky08de6132008-05-06 04:03:18 +00002137/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002138SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002139ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002140 const Loop *L,
2141 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002142 if (LI->isVolatile()) return UnknownValue;
2143
2144 // Check to see if the loaded pointer is a getelementptr of a global.
2145 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2146 if (!GEP) return UnknownValue;
2147
2148 // Make sure that it is really a constant global we are gepping, with an
2149 // initializer, and make sure the first IDX is really 0.
2150 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2151 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2152 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2153 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2154 return UnknownValue;
2155
2156 // Okay, we allow one non-constant index into the GEP instruction.
2157 Value *VarIdx = 0;
2158 std::vector<ConstantInt*> Indexes;
2159 unsigned VarIdxNum = 0;
2160 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2161 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2162 Indexes.push_back(CI);
2163 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2164 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2165 VarIdx = GEP->getOperand(i);
2166 VarIdxNum = i-2;
2167 Indexes.push_back(0);
2168 }
2169
2170 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2171 // Check to see if X is a loop variant variable value now.
2172 SCEVHandle Idx = getSCEV(VarIdx);
2173 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2174 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2175
2176 // We can only recognize very limited forms of loop index expressions, in
2177 // particular, only affine AddRec's like {C1,+,C2}.
2178 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2179 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2180 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2181 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2182 return UnknownValue;
2183
2184 unsigned MaxSteps = MaxBruteForceIterations;
2185 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002186 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002187 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002188 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002189
2190 // Form the GEP offset.
2191 Indexes[VarIdxNum] = Val;
2192
2193 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2194 if (Result == 0) break; // Cannot compute!
2195
2196 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002197 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002198 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002199 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002200#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002201 cerr << "\n***\n*** Computed loop count " << *ItCst
2202 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2203 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002204#endif
2205 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002206 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002207 }
2208 }
2209 return UnknownValue;
2210}
2211
2212
Chris Lattner3221ad02004-04-17 22:58:41 +00002213/// CanConstantFold - Return true if we can constant fold an instruction of the
2214/// specified type, assuming that all operands were constants.
2215static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002216 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002217 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2218 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002219
Chris Lattner3221ad02004-04-17 22:58:41 +00002220 if (const CallInst *CI = dyn_cast<CallInst>(I))
2221 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002222 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002223 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002224}
2225
Chris Lattner3221ad02004-04-17 22:58:41 +00002226/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2227/// in the loop that V is derived from. We allow arbitrary operations along the
2228/// way, but the operands of an operation must either be constants or a value
2229/// derived from a constant PHI. If this expression does not fit with these
2230/// constraints, return null.
2231static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2232 // If this is not an instruction, or if this is an instruction outside of the
2233 // loop, it can't be derived from a loop PHI.
2234 Instruction *I = dyn_cast<Instruction>(V);
2235 if (I == 0 || !L->contains(I->getParent())) return 0;
2236
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002237 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002238 if (L->getHeader() == I->getParent())
2239 return PN;
2240 else
2241 // We don't currently keep track of the control flow needed to evaluate
2242 // PHIs, so we cannot handle PHIs inside of loops.
2243 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002244 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002245
2246 // If we won't be able to constant fold this expression even if the operands
2247 // are constants, return early.
2248 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002249
Chris Lattner3221ad02004-04-17 22:58:41 +00002250 // Otherwise, we can evaluate this instruction if all of its operands are
2251 // constant or derived from a PHI node themselves.
2252 PHINode *PHI = 0;
2253 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2254 if (!(isa<Constant>(I->getOperand(Op)) ||
2255 isa<GlobalValue>(I->getOperand(Op)))) {
2256 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2257 if (P == 0) return 0; // Not evolving from PHI
2258 if (PHI == 0)
2259 PHI = P;
2260 else if (PHI != P)
2261 return 0; // Evolving from multiple different PHIs.
2262 }
2263
2264 // This is a expression evolving from a constant PHI!
2265 return PHI;
2266}
2267
2268/// EvaluateExpression - Given an expression that passes the
2269/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2270/// in the loop has the value PHIVal. If we can't fold this expression for some
2271/// reason, return null.
2272static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2273 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002274 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002275 Instruction *I = cast<Instruction>(V);
2276
2277 std::vector<Constant*> Operands;
2278 Operands.resize(I->getNumOperands());
2279
2280 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2281 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2282 if (Operands[i] == 0) return 0;
2283 }
2284
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002285 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2286 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2287 &Operands[0], Operands.size());
2288 else
2289 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2290 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002291}
2292
2293/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2294/// in the header of its containing loop, we know the loop executes a
2295/// constant number of times, and the PHI node is just a recurrence
2296/// involving constants, fold it.
2297Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002298getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002299 std::map<PHINode*, Constant*>::iterator I =
2300 ConstantEvolutionLoopExitValue.find(PN);
2301 if (I != ConstantEvolutionLoopExitValue.end())
2302 return I->second;
2303
Reid Spencere8019bb2007-03-01 07:25:48 +00002304 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002305 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2306
2307 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2308
2309 // Since the loop is canonicalized, the PHI node must have two entries. One
2310 // entry must be a constant (coming in from outside of the loop), and the
2311 // second must be derived from the same PHI.
2312 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2313 Constant *StartCST =
2314 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2315 if (StartCST == 0)
2316 return RetVal = 0; // Must be a constant.
2317
2318 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2319 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2320 if (PN2 != PN)
2321 return RetVal = 0; // Not derived from same PHI.
2322
2323 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002324 if (Its.getActiveBits() >= 32)
2325 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002326
Reid Spencere8019bb2007-03-01 07:25:48 +00002327 unsigned NumIterations = Its.getZExtValue(); // must be in range
2328 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002329 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2330 if (IterationNum == NumIterations)
2331 return RetVal = PHIVal; // Got exit value!
2332
2333 // Compute the value of the PHI node for the next iteration.
2334 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2335 if (NextPHI == PHIVal)
2336 return RetVal = NextPHI; // Stopped evolving!
2337 if (NextPHI == 0)
2338 return 0; // Couldn't evaluate!
2339 PHIVal = NextPHI;
2340 }
2341}
2342
Chris Lattner7980fb92004-04-17 18:36:24 +00002343/// ComputeIterationCountExhaustively - If the trip is known to execute a
2344/// constant number of times (the condition evolves only from constants),
2345/// try to evaluate a few iterations of the loop until we get the exit
2346/// condition gets a value of ExitWhen (true or false). If we cannot
2347/// evaluate the trip count of the loop, return UnknownValue.
2348SCEVHandle ScalarEvolutionsImpl::
2349ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2350 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2351 if (PN == 0) return UnknownValue;
2352
2353 // Since the loop is canonicalized, the PHI node must have two entries. One
2354 // entry must be a constant (coming in from outside of the loop), and the
2355 // second must be derived from the same PHI.
2356 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2357 Constant *StartCST =
2358 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2359 if (StartCST == 0) return UnknownValue; // Must be a constant.
2360
2361 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2362 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2363 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2364
2365 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2366 // the loop symbolically to determine when the condition gets a value of
2367 // "ExitWhen".
2368 unsigned IterationNum = 0;
2369 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2370 for (Constant *PHIVal = StartCST;
2371 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002372 ConstantInt *CondVal =
2373 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002374
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002375 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002376 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002377
Reid Spencere8019bb2007-03-01 07:25:48 +00002378 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002379 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002380 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002381 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002382 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002383
Chris Lattner3221ad02004-04-17 22:58:41 +00002384 // Compute the value of the PHI node for the next iteration.
2385 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2386 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002387 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002388 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002389 }
2390
2391 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002392 return UnknownValue;
2393}
2394
2395/// getSCEVAtScope - Compute the value of the specified expression within the
2396/// indicated loop (which may be null to indicate in no loop). If the
2397/// expression cannot be evaluated, return UnknownValue.
2398SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2399 // FIXME: this should be turned into a virtual method on SCEV!
2400
Chris Lattner3221ad02004-04-17 22:58:41 +00002401 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002402
Nick Lewycky3e630762008-02-20 06:48:22 +00002403 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002404 // exit value from the loop without using SCEVs.
2405 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2406 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2407 const Loop *LI = this->LI[I->getParent()];
2408 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2409 if (PHINode *PN = dyn_cast<PHINode>(I))
2410 if (PN->getParent() == LI->getHeader()) {
2411 // Okay, there is no closed form solution for the PHI node. Check
2412 // to see if the loop that contains it has a known iteration count.
2413 // If so, we may be able to force computation of the exit value.
2414 SCEVHandle IterationCount = getIterationCount(LI);
2415 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2416 // Okay, we know how many times the containing loop executes. If
2417 // this is a constant evolving PHI node, get the final value at
2418 // the specified iteration number.
2419 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002420 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002421 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002422 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002423 }
2424 }
2425
Reid Spencer09906f32006-12-04 21:33:23 +00002426 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002427 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002428 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002429 // result. This is particularly useful for computing loop exit values.
2430 if (CanConstantFold(I)) {
2431 std::vector<Constant*> Operands;
2432 Operands.reserve(I->getNumOperands());
2433 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2434 Value *Op = I->getOperand(i);
2435 if (Constant *C = dyn_cast<Constant>(Op)) {
2436 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002437 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002438 // If any of the operands is non-constant and if they are
2439 // non-integer, don't even try to analyze them with scev techniques.
2440 if (!isa<IntegerType>(Op->getType()))
2441 return V;
2442
Chris Lattner3221ad02004-04-17 22:58:41 +00002443 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2444 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002445 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2446 Op->getType(),
2447 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002448 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2449 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002450 Operands.push_back(ConstantExpr::getIntegerCast(C,
2451 Op->getType(),
2452 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002453 else
2454 return V;
2455 } else {
2456 return V;
2457 }
2458 }
2459 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002460
2461 Constant *C;
2462 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2463 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2464 &Operands[0], Operands.size());
2465 else
2466 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2467 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002468 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002469 }
2470 }
2471
2472 // This is some other type of SCEVUnknown, just return it.
2473 return V;
2474 }
2475
Chris Lattner53e677a2004-04-02 20:23:17 +00002476 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2477 // Avoid performing the look-up in the common case where the specified
2478 // expression has no loop-variant portions.
2479 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2480 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2481 if (OpAtScope != Comm->getOperand(i)) {
2482 if (OpAtScope == UnknownValue) return UnknownValue;
2483 // Okay, at least one of these operands is loop variant but might be
2484 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002485 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002486 NewOps.push_back(OpAtScope);
2487
2488 for (++i; i != e; ++i) {
2489 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2490 if (OpAtScope == UnknownValue) return UnknownValue;
2491 NewOps.push_back(OpAtScope);
2492 }
2493 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002494 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002495 if (isa<SCEVMulExpr>(Comm))
2496 return SE.getMulExpr(NewOps);
2497 if (isa<SCEVSMaxExpr>(Comm))
2498 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002499 if (isa<SCEVUMaxExpr>(Comm))
2500 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002501 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002502 }
2503 }
2504 // If we got here, all operands are loop invariant.
2505 return Comm;
2506 }
2507
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002508 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Chris Lattner60a05cc2006-04-01 04:48:52 +00002509 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002510 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002511 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002512 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002513 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2514 return Div; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002515 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002516 }
2517
2518 // If this is a loop recurrence for a loop that does not contain L, then we
2519 // are dealing with the final value computed by the loop.
2520 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2521 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2522 // To evaluate this recurrence, we need to know how many times the AddRec
2523 // loop iterates. Compute this now.
2524 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2525 if (IterationCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002526
Eli Friedmanb42a6262008-08-04 23:49:06 +00002527 // Then, evaluate the AddRec.
Dan Gohman246b2562007-10-22 18:31:58 +00002528 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002529 }
2530 return UnknownValue;
2531 }
2532
2533 //assert(0 && "Unknown SCEV type!");
2534 return UnknownValue;
2535}
2536
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002537/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2538/// following equation:
2539///
2540/// A * X = B (mod N)
2541///
2542/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2543/// A and B isn't important.
2544///
2545/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2546static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2547 ScalarEvolution &SE) {
2548 uint32_t BW = A.getBitWidth();
2549 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2550 assert(A != 0 && "A must be non-zero.");
2551
2552 // 1. D = gcd(A, N)
2553 //
2554 // The gcd of A and N may have only one prime factor: 2. The number of
2555 // trailing zeros in A is its multiplicity
2556 uint32_t Mult2 = A.countTrailingZeros();
2557 // D = 2^Mult2
2558
2559 // 2. Check if B is divisible by D.
2560 //
2561 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2562 // is not less than multiplicity of this prime factor for D.
2563 if (B.countTrailingZeros() < Mult2)
2564 return new SCEVCouldNotCompute();
2565
2566 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2567 // modulo (N / D).
2568 //
2569 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2570 // bit width during computations.
2571 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2572 APInt Mod(BW + 1, 0);
2573 Mod.set(BW - Mult2); // Mod = N / D
2574 APInt I = AD.multiplicativeInverse(Mod);
2575
2576 // 4. Compute the minimum unsigned root of the equation:
2577 // I * (B / D) mod (N / D)
2578 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2579
2580 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2581 // bits.
2582 return SE.getConstant(Result.trunc(BW));
2583}
Chris Lattner53e677a2004-04-02 20:23:17 +00002584
2585/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2586/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2587/// might be the same) or two SCEVCouldNotCompute objects.
2588///
2589static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002590SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002591 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002592 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2593 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2594 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002595
Chris Lattner53e677a2004-04-02 20:23:17 +00002596 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002597 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002598 SCEV *CNC = new SCEVCouldNotCompute();
2599 return std::make_pair(CNC, CNC);
2600 }
2601
Reid Spencere8019bb2007-03-01 07:25:48 +00002602 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002603 const APInt &L = LC->getValue()->getValue();
2604 const APInt &M = MC->getValue()->getValue();
2605 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002606 APInt Two(BitWidth, 2);
2607 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002608
Reid Spencere8019bb2007-03-01 07:25:48 +00002609 {
2610 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002611 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002612 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2613 // The B coefficient is M-N/2
2614 APInt B(M);
2615 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002616
Reid Spencere8019bb2007-03-01 07:25:48 +00002617 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002618 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002619
Reid Spencere8019bb2007-03-01 07:25:48 +00002620 // Compute the B^2-4ac term.
2621 APInt SqrtTerm(B);
2622 SqrtTerm *= B;
2623 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002624
Reid Spencere8019bb2007-03-01 07:25:48 +00002625 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2626 // integer value or else APInt::sqrt() will assert.
2627 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002628
Reid Spencere8019bb2007-03-01 07:25:48 +00002629 // Compute the two solutions for the quadratic formula.
2630 // The divisions must be performed as signed divisions.
2631 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002632 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002633 if (TwoA.isMinValue()) {
2634 SCEV *CNC = new SCEVCouldNotCompute();
2635 return std::make_pair(CNC, CNC);
2636 }
2637
Reid Spencere8019bb2007-03-01 07:25:48 +00002638 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2639 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002640
Dan Gohman246b2562007-10-22 18:31:58 +00002641 return std::make_pair(SE.getConstant(Solution1),
2642 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002643 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002644}
2645
2646/// HowFarToZero - Return the number of times a backedge comparing the specified
2647/// value to zero will execute. If not computable, return UnknownValue
2648SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2649 // If the value is a constant
2650 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2651 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002652 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002653 return UnknownValue; // Otherwise it will loop infinitely.
2654 }
2655
2656 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2657 if (!AddRec || AddRec->getLoop() != L)
2658 return UnknownValue;
2659
2660 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002661 // If this is an affine expression, the execution count of this branch is
2662 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002663 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002664 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002665 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002666 // equivalent to:
2667 //
2668 // Step*N = -Start (mod 2^BW)
2669 //
2670 // where BW is the common bit width of Start and Step.
2671
Chris Lattner53e677a2004-04-02 20:23:17 +00002672 // Get the initial value for the loop.
2673 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002674 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002675
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002676 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002677
Chris Lattner53e677a2004-04-02 20:23:17 +00002678 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002679 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002680
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002681 // First, handle unitary steps.
2682 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2683 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2684 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2685 return Start; // N = Start (as unsigned)
2686
2687 // Then, try to solve the above equation provided that Start is constant.
2688 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2689 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2690 -StartC->getValue()->getValue(),SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002691 }
Chris Lattner42a75512007-01-15 02:27:26 +00002692 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002693 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2694 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002695 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002696 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2697 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2698 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002699#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002700 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2701 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002702#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002703 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002704 if (ConstantInt *CB =
2705 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002706 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002707 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002708 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002709
Chris Lattner53e677a2004-04-02 20:23:17 +00002710 // We can only use this value if the chrec ends up with an exact zero
2711 // value at this index. When solving for "X*X != 5", for example, we
2712 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002713 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002714 if (Val->isZero())
2715 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002716 }
2717 }
2718 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002719
Chris Lattner53e677a2004-04-02 20:23:17 +00002720 return UnknownValue;
2721}
2722
2723/// HowFarToNonZero - Return the number of times a backedge checking the
2724/// specified value for nonzero will execute. If not computable, return
2725/// UnknownValue
2726SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2727 // Loops that look like: while (X == 0) are very strange indeed. We don't
2728 // handle them yet except for the trivial case. This could be expanded in the
2729 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002730
Chris Lattner53e677a2004-04-02 20:23:17 +00002731 // If the value is a constant, check to see if it is known to be non-zero
2732 // already. If so, the backedge will execute zero times.
2733 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002734 if (!C->getValue()->isNullValue())
2735 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002736 return UnknownValue; // Otherwise it will loop infinitely.
2737 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002738
Chris Lattner53e677a2004-04-02 20:23:17 +00002739 // We could implement others, but I really doubt anyone writes loops like
2740 // this, and if they did, they would already be constant folded.
2741 return UnknownValue;
2742}
2743
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002744/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2745/// (which may not be an immediate predecessor) which has exactly one
2746/// successor from which BB is reachable, or null if no such block is
2747/// found.
2748///
2749BasicBlock *
2750ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2751 // If the block has a unique predecessor, the predecessor must have
2752 // no other successors from which BB is reachable.
2753 if (BasicBlock *Pred = BB->getSinglePredecessor())
2754 return Pred;
2755
2756 // A loop's header is defined to be a block that dominates the loop.
2757 // If the loop has a preheader, it must be a block that has exactly
2758 // one successor that can reach BB. This is slightly more strict
2759 // than necessary, but works if critical edges are split.
2760 if (Loop *L = LI.getLoopFor(BB))
2761 return L->getLoopPreheader();
2762
2763 return 0;
2764}
2765
Nick Lewycky59cff122008-07-12 07:41:32 +00002766/// executesAtLeastOnce - Test whether entry to the loop is protected by
2767/// a conditional between LHS and RHS.
2768bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
Nick Lewyckydd643f22008-11-18 15:10:54 +00002769 bool trueWhenEqual,
Nick Lewycky59cff122008-07-12 07:41:32 +00002770 SCEV *LHS, SCEV *RHS) {
2771 BasicBlock *Preheader = L->getLoopPreheader();
2772 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00002773
Dan Gohman38372182008-08-12 20:17:31 +00002774 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002775 // there are predecessors that can be found that have unique successors
2776 // leading to the original header.
2777 for (; Preheader;
2778 PreheaderDest = Preheader,
2779 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00002780
2781 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00002782 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00002783 if (!LoopEntryPredicate ||
2784 LoopEntryPredicate->isUnconditional())
2785 continue;
2786
2787 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2788 if (!ICI) continue;
2789
2790 // Now that we found a conditional branch that dominates the loop, check to
2791 // see if it is the comparison we are looking for.
2792 Value *PreCondLHS = ICI->getOperand(0);
2793 Value *PreCondRHS = ICI->getOperand(1);
2794 ICmpInst::Predicate Cond;
2795 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2796 Cond = ICI->getPredicate();
2797 else
2798 Cond = ICI->getInversePredicate();
2799
2800 switch (Cond) {
2801 case ICmpInst::ICMP_UGT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002802 if (isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002803 std::swap(PreCondLHS, PreCondRHS);
2804 Cond = ICmpInst::ICMP_ULT;
2805 break;
2806 case ICmpInst::ICMP_SGT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002807 if (!isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002808 std::swap(PreCondLHS, PreCondRHS);
2809 Cond = ICmpInst::ICMP_SLT;
2810 break;
2811 case ICmpInst::ICMP_ULT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002812 if (isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002813 break;
2814 case ICmpInst::ICMP_SLT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002815 if (!isSigned || trueWhenEqual) continue;
2816 break;
2817 case ICmpInst::ICMP_UGE:
2818 if (isSigned || !trueWhenEqual) continue;
2819 std::swap(PreCondLHS, PreCondRHS);
2820 Cond = ICmpInst::ICMP_ULE;
2821 break;
2822 case ICmpInst::ICMP_SGE:
2823 if (!isSigned || !trueWhenEqual) continue;
2824 std::swap(PreCondLHS, PreCondRHS);
2825 Cond = ICmpInst::ICMP_SLE;
2826 break;
2827 case ICmpInst::ICMP_ULE:
2828 if (isSigned || !trueWhenEqual) continue;
2829 break;
2830 case ICmpInst::ICMP_SLE:
2831 if (!isSigned || !trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002832 break;
2833 default:
2834 continue;
2835 }
2836
2837 if (!PreCondLHS->getType()->isInteger()) continue;
2838
2839 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2840 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2841 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2842 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2843 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2844 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00002845 }
2846
Dan Gohman38372182008-08-12 20:17:31 +00002847 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00002848}
2849
Nick Lewyckydd643f22008-11-18 15:10:54 +00002850/// potentialInfiniteLoop - Test whether the loop might jump over the exit value
2851/// due to wrapping around 2^n.
2852bool ScalarEvolutionsImpl::potentialInfiniteLoop(SCEV *Stride, SCEV *RHS,
2853 bool isSigned, bool trueWhenEqual) {
2854 // Return true when the distance from RHS to maxint > Stride.
2855
2856 if (!isa<SCEVConstant>(Stride))
2857 return true;
2858 SCEVConstant *SC = cast<SCEVConstant>(Stride);
2859
2860 if (SC->getValue()->isZero())
2861 return true;
2862 if (!trueWhenEqual && SC->getValue()->isOne())
2863 return false;
2864
2865 if (!isa<SCEVConstant>(RHS))
2866 return true;
2867 SCEVConstant *R = cast<SCEVConstant>(RHS);
2868
2869 if (isSigned)
2870 return true; // XXX: because we don't have an sdiv scev.
2871
2872 // If negative, it wraps around every iteration, but we don't care about that.
2873 APInt S = SC->getValue()->getValue().abs();
2874
2875 APInt Dist = APInt::getMaxValue(R->getValue()->getBitWidth()) -
2876 R->getValue()->getValue();
2877
2878 if (trueWhenEqual)
2879 return !S.ult(Dist);
2880 else
2881 return !S.ule(Dist);
2882}
2883
Chris Lattnerdb25de42005-08-15 23:33:51 +00002884/// HowManyLessThans - Return the number of times a backedge containing the
2885/// specified less-than comparison will execute. If not computable, return
2886/// UnknownValue.
2887SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckydd643f22008-11-18 15:10:54 +00002888HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
2889 bool isSigned, bool trueWhenEqual) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002890 // Only handle: "ADDREC < LoopInvariant".
2891 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2892
2893 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2894 if (!AddRec || AddRec->getLoop() != L)
2895 return UnknownValue;
2896
2897 if (AddRec->isAffine()) {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002898 SCEVHandle Stride = AddRec->getOperand(1);
2899 if (potentialInfiniteLoop(Stride, RHS, isSigned, trueWhenEqual))
Chris Lattnerdb25de42005-08-15 23:33:51 +00002900 return UnknownValue;
2901
Nick Lewyckydd643f22008-11-18 15:10:54 +00002902 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
2903 // m. So, we count the number of iterations in which {n,+,s} < m is true.
2904 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002905 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002906
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002907 // First, we get the value of the LHS in the first iteration: n
2908 SCEVHandle Start = AddRec->getOperand(0);
2909
Nick Lewyckydd643f22008-11-18 15:10:54 +00002910 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002911
Nick Lewyckydd643f22008-11-18 15:10:54 +00002912 // Assuming that the loop will run at least once, we know that it will
2913 // run (m-n)/s times.
2914 SCEVHandle End = RHS;
2915
2916 if (!executesAtLeastOnce(L, isSigned, trueWhenEqual,
2917 SE.getMinusSCEV(Start, One), RHS)) {
2918 // If not, we get the value of the LHS in the first iteration in which
2919 // the above condition doesn't hold. This equals to max(m,n).
2920 End = isSigned ? SE.getSMaxExpr(RHS, Start)
2921 : SE.getUMaxExpr(RHS, Start);
Nick Lewycky59cff122008-07-12 07:41:32 +00002922 }
Nick Lewyckydd643f22008-11-18 15:10:54 +00002923
2924 // If the expression is less-than-or-equal to, we need to extend the
2925 // loop by one iteration.
2926 //
2927 // The loop won't actually run (m-n)/s times because the loop iterations
2928 // won't divide evenly. For example, if you have {2,+,5} u< 10 the
2929 // division would equal one, but the loop runs twice putting the
2930 // induction variable at 12.
2931
2932 if (!trueWhenEqual)
2933 // (Stride - 1) is correct only because we know it's unsigned.
2934 // What we really want is to decrease the magnitude of Stride by one.
2935 Start = SE.getMinusSCEV(Start, SE.getMinusSCEV(Stride, One));
2936 else
2937 Start = SE.getMinusSCEV(Start, Stride);
2938
2939 // Finally, we subtract these two values to get the number of times the
2940 // backedge is executed: max(m,n)-n.
2941 return SE.getUDivExpr(SE.getMinusSCEV(End, Start), Stride);
Chris Lattnerdb25de42005-08-15 23:33:51 +00002942 }
2943
2944 return UnknownValue;
2945}
2946
Chris Lattner53e677a2004-04-02 20:23:17 +00002947/// getNumIterationsInRange - Return the number of iterations of this loop that
2948/// produce values in the specified constant range. Another way of looking at
2949/// this is that it returns the first iteration number where the value is not in
2950/// the condition, thus computing the exit count. If the iteration count can't
2951/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002952SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2953 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002954 if (Range.isFullSet()) // Infinite loop.
2955 return new SCEVCouldNotCompute();
2956
2957 // If the start is a non-zero constant, shift the range to simplify things.
2958 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002959 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002960 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002961 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2962 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002963 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2964 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002965 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002966 // This is strange and shouldn't happen.
2967 return new SCEVCouldNotCompute();
2968 }
2969
2970 // The only time we can solve this is when we have all constant indices.
2971 // Otherwise, we cannot determine the overflow conditions.
2972 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2973 if (!isa<SCEVConstant>(getOperand(i)))
2974 return new SCEVCouldNotCompute();
2975
2976
2977 // Okay at this point we know that all elements of the chrec are constants and
2978 // that the start element is zero.
2979
2980 // First check to see if the range contains zero. If not, the first
2981 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002982 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002983 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002984
Chris Lattner53e677a2004-04-02 20:23:17 +00002985 if (isAffine()) {
2986 // If this is an affine expression then we have this situation:
2987 // Solve {0,+,A} in Range === Ax in Range
2988
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002989 // We know that zero is in the range. If A is positive then we know that
2990 // the upper value of the range must be the first possible exit value.
2991 // If A is negative then the lower of the range is the last possible loop
2992 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002993 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002994 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2995 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002996
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002997 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002998 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002999 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003000
3001 // Evaluate at the exit value. If we really did fall out of the valid
3002 // range, then we computed our trip count, otherwise wrap around or other
3003 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003004 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003005 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003006 return new SCEVCouldNotCompute(); // Something strange happened
3007
3008 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003009 assert(Range.contains(
3010 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003011 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003012 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003013 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003014 } else if (isQuadratic()) {
3015 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3016 // quadratic equation to solve it. To do this, we must frame our problem in
3017 // terms of figuring out when zero is crossed, instead of when
3018 // Range.getUpper() is crossed.
3019 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003020 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3021 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003022
3023 // Next, solve the constructed addrec
3024 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003025 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003026 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3027 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3028 if (R1) {
3029 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003030 if (ConstantInt *CB =
3031 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003032 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003033 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003034 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003035
Chris Lattner53e677a2004-04-02 20:23:17 +00003036 // Make sure the root is not off by one. The returned iteration should
3037 // not be in the range, but the previous one should be. When solving
3038 // for "X*X < 5", for example, we should not return a root of 2.
3039 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003040 R1->getValue(),
3041 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003042 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003043 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003044 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003045
Dan Gohman246b2562007-10-22 18:31:58 +00003046 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003047 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003048 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003049 return new SCEVCouldNotCompute(); // Something strange happened
3050 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003051
Chris Lattner53e677a2004-04-02 20:23:17 +00003052 // If R1 was not in the range, then it is a good return value. Make
3053 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003054 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003055 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003056 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003057 return R1;
3058 return new SCEVCouldNotCompute(); // Something strange happened
3059 }
3060 }
3061 }
3062
Chris Lattner53e677a2004-04-02 20:23:17 +00003063 return new SCEVCouldNotCompute();
3064}
3065
3066
3067
3068//===----------------------------------------------------------------------===//
3069// ScalarEvolution Class Implementation
3070//===----------------------------------------------------------------------===//
3071
3072bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00003073 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00003074 return false;
3075}
3076
3077void ScalarEvolution::releaseMemory() {
3078 delete (ScalarEvolutionsImpl*)Impl;
3079 Impl = 0;
3080}
3081
3082void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3083 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003084 AU.addRequiredTransitive<LoopInfo>();
3085}
3086
3087SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3088 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3089}
3090
Chris Lattnera0740fb2005-08-09 23:36:33 +00003091/// hasSCEV - Return true if the SCEV for this value has already been
3092/// computed.
3093bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00003094 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00003095}
3096
3097
3098/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3099/// the specified value.
3100void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3101 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3102}
3103
3104
Chris Lattner53e677a2004-04-02 20:23:17 +00003105SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3106 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3107}
3108
3109bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3110 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3111}
3112
3113SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3114 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3115}
3116
Dan Gohman5cec4db2007-06-19 14:28:31 +00003117void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3118 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003119}
3120
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003121static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003122 const Loop *L) {
3123 // Print all inner loops first
3124 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3125 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003126
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003127 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003128
Devang Patelb7211a22007-08-21 00:31:24 +00003129 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003130 L->getExitBlocks(ExitBlocks);
3131 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003132 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003133
3134 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003135 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003136 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003137 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003138 }
3139
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003140 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003141}
3142
Reid Spencerce9653c2004-12-07 04:03:45 +00003143void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003144 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3145 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3146
3147 OS << "Classifying expressions for: " << F.getName() << "\n";
3148 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00003149 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003150 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003151 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003152 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003153 SV->print(OS);
3154 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003155
Chris Lattner6ffe5512004-04-27 15:13:33 +00003156 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003157 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003158 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003159 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3160 OS << "<<Unknown>>";
3161 } else {
3162 OS << *ExitValue;
3163 }
3164 }
3165
3166
3167 OS << "\n";
3168 }
3169
3170 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3171 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3172 PrintLoopInfo(OS, this, *I);
3173}