blob: 84e02e47a0c4fbb7879e51a126924aabe8a3782d [file] [log] [blame]
Chris Lattnerd934c702004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
Chris Lattnerd934c702004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman01808ca2005-04-21 21:13:18 +00007//
Chris Lattnerd934c702004-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 Brukman01808ca2005-04-21 21:13:18 +000031//
Chris Lattnerd934c702004-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 Lattnerd934c702004-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 Lattner57ef9422006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattnerb4f681b2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattnerec901cc2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerd934c702004-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 Lattner996795b2006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattner538c6eb2006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattner538c6eb2006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling597d4512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling597d4512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohencc08c832006-12-02 02:22:01 +000083#include <cmath>
Chris Lattnerd934c702004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner57ef9422006-12-19 22:30:33 +000086STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohmand78c4002008-05-13 00:00:25 +000098static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Dan Gohmand78c4002008-05-13 00:00:25 +0000104static RegisterPass<ScalarEvolution>
105R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel8c78a0b2007-05-03 01:11:54 +0000106char ScalarEvolution::ID = 0;
Chris Lattnerd934c702004-04-02 20:23:17 +0000107
108//===----------------------------------------------------------------------===//
109// SCEV class definitions
110//===----------------------------------------------------------------------===//
111
112//===----------------------------------------------------------------------===//
113// Implementation of the SCEV class.
114//
Chris Lattnerd934c702004-04-02 20:23:17 +0000115SCEV::~SCEV() {}
116void SCEV::dump() const {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000117 print(cerr);
Chris Lattnerd934c702004-04-02 20:23:17 +0000118}
119
Reid Spencer3a7e9d82007-02-28 19:57:34 +0000120uint32_t SCEV::getBitWidth() const {
121 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
122 return ITy->getBitWidth();
123 return 0;
124}
125
Dan Gohmanbe928e32008-06-18 16:23:07 +0000126bool SCEV::isZero() const {
127 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
128 return SC->getValue()->isZero();
129 return false;
130}
131
Chris Lattnerd934c702004-04-02 20:23:17 +0000132
133SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
134
135bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
136 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukman5ebc25c2004-04-05 19:00:46 +0000137 return false;
Chris Lattnerd934c702004-04-02 20:23:17 +0000138}
139
140const Type *SCEVCouldNotCompute::getType() const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukman5ebc25c2004-04-05 19:00:46 +0000142 return 0;
Chris Lattnerd934c702004-04-02 20:23:17 +0000143}
144
145bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 return false;
148}
149
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000150SCEVHandle SCEVCouldNotCompute::
151replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohmana37eaf22007-10-22 18:31:58 +0000152 const SCEVHandle &Conc,
153 ScalarEvolution &SE) const {
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000154 return this;
155}
156
Chris Lattnerd934c702004-04-02 20:23:17 +0000157void SCEVCouldNotCompute::print(std::ostream &OS) const {
158 OS << "***COULDNOTCOMPUTE***";
159}
160
161bool SCEVCouldNotCompute::classof(const SCEV *S) {
162 return S->getSCEVType() == scCouldNotCompute;
163}
164
165
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000166// SCEVConstants - Only allow the creation of one SCEVConstant for any
167// particular value. Don't use a SCEVHandle here, or else the object will
168// never be deleted!
Chris Lattner538c6eb2006-10-04 21:49:37 +0000169static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman01808ca2005-04-21 21:13:18 +0000170
Chris Lattnerd934c702004-04-02 20:23:17 +0000171
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000172SCEVConstant::~SCEVConstant() {
Chris Lattner538c6eb2006-10-04 21:49:37 +0000173 SCEVConstants->erase(V);
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000174}
Chris Lattnerd934c702004-04-02 20:23:17 +0000175
Dan Gohmana37eaf22007-10-22 18:31:58 +0000176SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattner538c6eb2006-10-04 21:49:37 +0000177 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000178 if (R == 0) R = new SCEVConstant(V);
179 return R;
180}
Chris Lattnerd934c702004-04-02 20:23:17 +0000181
Dan Gohmana37eaf22007-10-22 18:31:58 +0000182SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
183 return getConstant(ConstantInt::get(Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000184}
185
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000186const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattnerd934c702004-04-02 20:23:17 +0000187
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000188void SCEVConstant::print(std::ostream &OS) const {
189 WriteAsOperand(OS, V, false);
190}
Chris Lattnerd934c702004-04-02 20:23:17 +0000191
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000192// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
193// particular input. Don't use a SCEVHandle here, or else the object will
194// never be deleted!
Chris Lattner538c6eb2006-10-04 21:49:37 +0000195static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
196 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattnerd934c702004-04-02 20:23:17 +0000197
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000198SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
199 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner03c49532007-01-15 02:27:26 +0000200 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000201 "Cannot truncate non-integer value!");
Reid Spencer7928c2f2007-01-08 01:26:33 +0000202 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
203 && "This is not a truncating conversion!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000204}
Chris Lattnerd934c702004-04-02 20:23:17 +0000205
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000206SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattner538c6eb2006-10-04 21:49:37 +0000207 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000208}
Chris Lattnerd934c702004-04-02 20:23:17 +0000209
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000210void SCEVTruncateExpr::print(std::ostream &OS) const {
211 OS << "(truncate " << *Op << " to " << *Ty << ")";
212}
213
214// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
215// particular input. Don't use a SCEVHandle here, or else the object will never
216// be deleted!
Chris Lattner538c6eb2006-10-04 21:49:37 +0000217static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
218 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000219
220SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer20ffdbe2006-11-01 21:53:12 +0000221 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner03c49532007-01-15 02:27:26 +0000222 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000223 "Cannot zero extend non-integer value!");
Reid Spencer7928c2f2007-01-08 01:26:33 +0000224 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
225 && "This is not an extending conversion!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000226}
227
228SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattner538c6eb2006-10-04 21:49:37 +0000229 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000230}
231
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000232void SCEVZeroExtendExpr::print(std::ostream &OS) const {
233 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
234}
235
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000236// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
237// particular input. Don't use a SCEVHandle here, or else the object will never
238// be deleted!
239static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
240 SCEVSignExtendExpr*> > SCEVSignExtends;
241
242SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
243 : SCEV(scSignExtend), Op(op), Ty(ty) {
244 assert(Op->getType()->isInteger() && Ty->isInteger() &&
245 "Cannot sign extend non-integer value!");
246 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
247 && "This is not an extending conversion!");
248}
249
250SCEVSignExtendExpr::~SCEVSignExtendExpr() {
251 SCEVSignExtends->erase(std::make_pair(Op, Ty));
252}
253
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000254void SCEVSignExtendExpr::print(std::ostream &OS) const {
255 OS << "(signextend " << *Op << " to " << *Ty << ")";
256}
257
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000258// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
259// particular input. Don't use a SCEVHandle here, or else the object will never
260// be deleted!
Chris Lattner538c6eb2006-10-04 21:49:37 +0000261static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
262 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000263
264SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattner538c6eb2006-10-04 21:49:37 +0000265 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
266 std::vector<SCEV*>(Operands.begin(),
267 Operands.end())));
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000268}
269
270void SCEVCommutativeExpr::print(std::ostream &OS) const {
271 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
272 const char *OpStr = getOperationStr();
273 OS << "(" << *Operands[0];
274 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
275 OS << OpStr << *Operands[i];
276 OS << ")";
277}
278
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000279SCEVHandle SCEVCommutativeExpr::
280replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohmana37eaf22007-10-22 18:31:58 +0000281 const SCEVHandle &Conc,
282 ScalarEvolution &SE) const {
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000283 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohmana37eaf22007-10-22 18:31:58 +0000284 SCEVHandle H =
285 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000286 if (H != getOperand(i)) {
287 std::vector<SCEVHandle> NewOps;
288 NewOps.reserve(getNumOperands());
289 for (unsigned j = 0; j != i; ++j)
290 NewOps.push_back(getOperand(j));
291 NewOps.push_back(H);
292 for (++i; i != e; ++i)
293 NewOps.push_back(getOperand(i)->
Dan Gohmana37eaf22007-10-22 18:31:58 +0000294 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000295
296 if (isa<SCEVAddExpr>(this))
Dan Gohmana37eaf22007-10-22 18:31:58 +0000297 return SE.getAddExpr(NewOps);
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000298 else if (isa<SCEVMulExpr>(this))
Dan Gohmana37eaf22007-10-22 18:31:58 +0000299 return SE.getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +0000300 else if (isa<SCEVSMaxExpr>(this))
301 return SE.getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +0000302 else if (isa<SCEVUMaxExpr>(this))
303 return SE.getUMaxExpr(NewOps);
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000304 else
305 assert(0 && "Unknown commutative expr!");
306 }
307 }
308 return this;
309}
310
311
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000312// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000313// input. Don't use a SCEVHandle here, or else the object will never be
314// deleted!
Chris Lattner538c6eb2006-10-04 21:49:37 +0000315static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000316 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000317
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000318SCEVUDivExpr::~SCEVUDivExpr() {
319 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000320}
321
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000322void SCEVUDivExpr::print(std::ostream &OS) const {
323 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000324}
325
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000326const Type *SCEVUDivExpr::getType() const {
Reid Spencerc635f472006-12-31 05:48:39 +0000327 return LHS->getType();
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000328}
329
330// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
331// particular input. Don't use a SCEVHandle here, or else the object will never
332// be deleted!
Chris Lattner538c6eb2006-10-04 21:49:37 +0000333static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
334 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000335
336SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattner538c6eb2006-10-04 21:49:37 +0000337 SCEVAddRecExprs->erase(std::make_pair(L,
338 std::vector<SCEV*>(Operands.begin(),
339 Operands.end())));
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000340}
341
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000342SCEVHandle SCEVAddRecExpr::
343replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohmana37eaf22007-10-22 18:31:58 +0000344 const SCEVHandle &Conc,
345 ScalarEvolution &SE) const {
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000346 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohmana37eaf22007-10-22 18:31:58 +0000347 SCEVHandle H =
348 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000349 if (H != getOperand(i)) {
350 std::vector<SCEVHandle> NewOps;
351 NewOps.reserve(getNumOperands());
352 for (unsigned j = 0; j != i; ++j)
353 NewOps.push_back(getOperand(j));
354 NewOps.push_back(H);
355 for (++i; i != e; ++i)
356 NewOps.push_back(getOperand(i)->
Dan Gohmana37eaf22007-10-22 18:31:58 +0000357 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman01808ca2005-04-21 21:13:18 +0000358
Dan Gohmana37eaf22007-10-22 18:31:58 +0000359 return SE.getAddRecExpr(NewOps, L);
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000360 }
361 }
362 return this;
363}
364
365
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000366bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
367 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnere5154162005-08-16 00:37:01 +0000368 // contain L and if the start is invariant.
369 return !QueryLoop->contains(L->getHeader()) &&
370 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattnerd934c702004-04-02 20:23:17 +0000371}
372
373
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000374void SCEVAddRecExpr::print(std::ostream &OS) const {
375 OS << "{" << *Operands[0];
376 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
377 OS << ",+," << *Operands[i];
378 OS << "}<" << L->getHeader()->getName() + ">";
379}
Chris Lattnerd934c702004-04-02 20:23:17 +0000380
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000381// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
382// value. Don't use a SCEVHandle here, or else the object will never be
383// deleted!
Chris Lattner538c6eb2006-10-04 21:49:37 +0000384static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattnerd934c702004-04-02 20:23:17 +0000385
Chris Lattner538c6eb2006-10-04 21:49:37 +0000386SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattnerd934c702004-04-02 20:23:17 +0000387
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000388bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
389 // All non-instruction values are loop invariant. All instructions are loop
390 // invariant if they are not contained in the specified loop.
391 if (Instruction *I = dyn_cast<Instruction>(V))
392 return !L->contains(I->getParent());
393 return true;
394}
Chris Lattnerd934c702004-04-02 20:23:17 +0000395
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000396const Type *SCEVUnknown::getType() const {
397 return V->getType();
398}
Chris Lattnerd934c702004-04-02 20:23:17 +0000399
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000400void SCEVUnknown::print(std::ostream &OS) const {
401 WriteAsOperand(OS, V, false);
Chris Lattnerd934c702004-04-02 20:23:17 +0000402}
403
Chris Lattnereb3e8402004-06-20 06:23:15 +0000404//===----------------------------------------------------------------------===//
405// SCEV Utilities
406//===----------------------------------------------------------------------===//
407
408namespace {
409 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
410 /// than the complexity of the RHS. This comparator is used to canonicalize
411 /// expressions.
Chris Lattner996795b2006-06-28 23:17:24 +0000412 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohman5e6ce7b2008-04-14 18:23:56 +0000413 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000414 return LHS->getSCEVType() < RHS->getSCEVType();
415 }
416 };
417}
418
419/// GroupByComplexity - Given a list of SCEV objects, order them by their
420/// complexity, and group objects of the same complexity together by value.
421/// When this routine is finished, we know that any duplicates in the vector are
422/// consecutive and that complexity is monotonically increasing.
423///
424/// Note that we go take special precautions to ensure that we get determinstic
425/// results from this routine. In other words, we don't want the results of
426/// this to depend on where the addresses of various SCEV objects happened to
427/// land in memory.
428///
429static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
430 if (Ops.size() < 2) return; // Noop
431 if (Ops.size() == 2) {
432 // This is the common case, which also happens to be trivially simple.
433 // Special case it.
Dan Gohman5e6ce7b2008-04-14 18:23:56 +0000434 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattnereb3e8402004-06-20 06:23:15 +0000435 std::swap(Ops[0], Ops[1]);
436 return;
437 }
438
439 // Do the rough sort by complexity.
440 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
441
442 // Now that we are sorted by complexity, group elements of the same
443 // complexity. Note that this is, at worst, N^2, but the vector is likely to
444 // be extremely short in practice. Note that we take this approach because we
445 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner6bfca8f2004-06-20 17:01:44 +0000446 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000447 SCEV *S = Ops[i];
448 unsigned Complexity = S->getSCEVType();
449
450 // If there are any objects of the same complexity and same value as this
451 // one, group them.
452 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
453 if (Ops[j] == S) { // Found a duplicate.
454 // Move it to immediately after i'th element.
455 std::swap(Ops[i+1], Ops[j]);
456 ++i; // no need to rescan it.
Chris Lattnerbaaed7e2004-06-20 20:32:16 +0000457 if (i == e-2) return; // Done!
Chris Lattnereb3e8402004-06-20 06:23:15 +0000458 }
459 }
460 }
461}
462
Chris Lattnerd934c702004-04-02 20:23:17 +0000463
Chris Lattnerd934c702004-04-02 20:23:17 +0000464
465//===----------------------------------------------------------------------===//
466// Simple SCEV method implementations
467//===----------------------------------------------------------------------===//
468
469/// getIntegerSCEV - Given an integer or FP type, create a constant for the
470/// specified signed integer value and return a SCEV for the constant.
Dan Gohmana37eaf22007-10-22 18:31:58 +0000471SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000472 Constant *C;
Misha Brukman01808ca2005-04-21 21:13:18 +0000473 if (Val == 0)
Chris Lattnerd934c702004-04-02 20:23:17 +0000474 C = Constant::getNullValue(Ty);
475 else if (Ty->isFloatingPoint())
Chris Lattner3b187622008-04-20 00:41:09 +0000476 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
477 APFloat::IEEEdouble, Val));
Reid Spencer266e42b2006-12-23 06:05:41 +0000478 else
Reid Spencere0fc4df2006-10-20 07:07:24 +0000479 C = ConstantInt::get(Ty, Val);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000480 return getUnknown(C);
Chris Lattnerd934c702004-04-02 20:23:17 +0000481}
482
Chris Lattnerd934c702004-04-02 20:23:17 +0000483/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
484///
Dan Gohmana37eaf22007-10-22 18:31:58 +0000485SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000486 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmana37eaf22007-10-22 18:31:58 +0000487 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman01808ca2005-04-21 21:13:18 +0000488
Nick Lewyckyb0a2f952008-02-20 06:58:55 +0000489 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +0000490}
491
492/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
493SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
494 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
495 return getUnknown(ConstantExpr::getNot(VC->getValue()));
496
Nick Lewyckyb0a2f952008-02-20 06:58:55 +0000497 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +0000498 return getMinusSCEV(AllOnes, V);
Chris Lattnerd934c702004-04-02 20:23:17 +0000499}
500
501/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
502///
Dan Gohmana37eaf22007-10-22 18:31:58 +0000503SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
504 const SCEVHandle &RHS) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000505 // X - Y --> X + -Y
Dan Gohmana37eaf22007-10-22 18:31:58 +0000506 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattnerd934c702004-04-02 20:23:17 +0000507}
508
509
Eli Friedman61f67622008-08-04 23:49:06 +0000510/// BinomialCoefficient - Compute BC(It, K). The result has width W.
511// Assume, K > 0.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000512static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman61f67622008-08-04 23:49:06 +0000513 ScalarEvolution &SE,
514 const IntegerType* ResultTy) {
515 // Handle the simplest case efficiently.
516 if (K == 1)
517 return SE.getTruncateOrZeroExtend(It, ResultTy);
518
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000519 // We are using the following formula for BC(It, K):
520 //
521 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
522 //
Eli Friedman61f67622008-08-04 23:49:06 +0000523 // Suppose, W is the bitwidth of the return value. We must be prepared for
524 // overflow. Hence, we must assure that the result of our computation is
525 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
526 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000527 //
Eli Friedman61f67622008-08-04 23:49:06 +0000528 // However, this code doesn't use exactly that formula; the formula it uses
529 // is something like the following, where T is the number of factors of 2 in
530 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
531 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000532 //
Eli Friedman61f67622008-08-04 23:49:06 +0000533 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000534 //
Eli Friedman61f67622008-08-04 23:49:06 +0000535 // This formula is trivially equivalent to the previous formula. However,
536 // this formula can be implemented much more efficiently. The trick is that
537 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
538 // arithmetic. To do exact division in modular arithmetic, all we have
539 // to do is multiply by the inverse. Therefore, this step can be done at
540 // width W.
541 //
542 // The next issue is how to safely do the division by 2^T. The way this
543 // is done is by doing the multiplication step at a width of at least W + T
544 // bits. This way, the bottom W+T bits of the product are accurate. Then,
545 // when we perform the division by 2^T (which is equivalent to a right shift
546 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
547 // truncated out after the division by 2^T.
548 //
549 // In comparison to just directly using the first formula, this technique
550 // is much more efficient; using the first formula requires W * K bits,
551 // but this formula less than W + K bits. Also, the first formula requires
552 // a division step, whereas this formula only requires multiplies and shifts.
553 //
554 // It doesn't matter whether the subtraction step is done in the calculation
555 // width or the input iteration count's width; if the subtraction overflows,
556 // the result must be zero anyway. We prefer here to do it in the width of
557 // the induction variable because it helps a lot for certain cases; CodeGen
558 // isn't smart enough to ignore the overflow, which leads to much less
559 // efficient code if the width of the subtraction is wider than the native
560 // register width.
561 //
562 // (It's possible to not widen at all by pulling out factors of 2 before
563 // the multiplication; for example, K=2 can be calculated as
564 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
565 // extra arithmetic, so it's not an obvious win, and it gets
566 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000567
Eli Friedman61f67622008-08-04 23:49:06 +0000568 // Protection from insane SCEVs; this bound is conservative,
569 // but it probably doesn't matter.
570 if (K > 1000)
571 return new SCEVCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000572
Eli Friedman61f67622008-08-04 23:49:06 +0000573 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000574
Eli Friedman61f67622008-08-04 23:49:06 +0000575 // Calculate K! / 2^T and T; we divide out the factors of two before
576 // multiplying for calculating K! / 2^T to avoid overflow.
577 // Other overflow doesn't matter because we only care about the bottom
578 // W bits of the result.
579 APInt OddFactorial(W, 1);
580 unsigned T = 1;
581 for (unsigned i = 3; i <= K; ++i) {
582 APInt Mult(W, i);
583 unsigned TwoFactors = Mult.countTrailingZeros();
584 T += TwoFactors;
585 Mult = Mult.lshr(TwoFactors);
586 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +0000587 }
Nick Lewyckyed169d52008-06-13 04:38:55 +0000588
Eli Friedman61f67622008-08-04 23:49:06 +0000589 // We need at least W + T bits for the multiplication step
590 // FIXME: A temporary hack; we round up the bitwidths
591 // to the nearest power of 2 to be nice to the code generator.
592 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
593 // FIXME: Temporary hack to avoid generating integers that are too wide.
594 // Although, it's not completely clear how to determine how much
595 // widening is safe; for example, on X86, we can't really widen
596 // beyond 64 because we need to be able to do multiplication
597 // that's CalculationBits wide, but on X86-64, we can safely widen up to
598 // 128 bits.
599 if (CalculationBits > 64)
600 return new SCEVCouldNotCompute();
601
602 // Calcuate 2^T, at width T+W.
603 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
604
605 // Calculate the multiplicative inverse of K! / 2^T;
606 // this multiplication factor will perform the exact division by
607 // K! / 2^T.
608 APInt Mod = APInt::getSignedMinValue(W+1);
609 APInt MultiplyFactor = OddFactorial.zext(W+1);
610 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
611 MultiplyFactor = MultiplyFactor.trunc(W);
612
613 // Calculate the product, at width T+W
614 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
615 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
616 for (unsigned i = 1; i != K; ++i) {
617 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
618 Dividend = SE.getMulExpr(Dividend,
619 SE.getTruncateOrZeroExtend(S, CalculationTy));
620 }
621
622 // Divide by 2^T
623 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
624
625 // Truncate the result, and divide by K! / 2^T.
626
627 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
628 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +0000629}
630
Chris Lattnerd934c702004-04-02 20:23:17 +0000631/// evaluateAtIteration - Return the value of this chain of recurrences at
632/// the specified iteration number. We can evaluate this recurrence by
633/// multiplying each element in the chain by the binomial coefficient
634/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
635///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000636/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +0000637///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000638/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +0000639///
Dan Gohmana37eaf22007-10-22 18:31:58 +0000640SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
641 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +0000642 SCEVHandle Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +0000643 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000644 // The computation is correct in the face of overflow provided that the
645 // multiplication is performed _after_ the evaluation of the binomial
646 // coefficient.
Eli Friedman61f67622008-08-04 23:49:06 +0000647 SCEVHandle Val =
648 SE.getMulExpr(getOperand(i),
649 BinomialCoefficient(It, i, SE,
650 cast<IntegerType>(getType())));
Dan Gohmana37eaf22007-10-22 18:31:58 +0000651 Result = SE.getAddExpr(Result, Val);
Chris Lattnerd934c702004-04-02 20:23:17 +0000652 }
653 return Result;
654}
655
Chris Lattnerd934c702004-04-02 20:23:17 +0000656//===----------------------------------------------------------------------===//
657// SCEV Expression folder implementations
658//===----------------------------------------------------------------------===//
659
Dan Gohmana37eaf22007-10-22 18:31:58 +0000660SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000661 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmana37eaf22007-10-22 18:31:58 +0000662 return getUnknown(
Reid Spencer0646eb42006-12-05 22:39:58 +0000663 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattnerd934c702004-04-02 20:23:17 +0000664
665 // If the input value is a chrec scev made out of constants, truncate
666 // all of the constants.
667 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
668 std::vector<SCEVHandle> Operands;
669 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
670 // FIXME: This should allow truncation of other expression types!
671 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohmana37eaf22007-10-22 18:31:58 +0000672 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattnerd934c702004-04-02 20:23:17 +0000673 else
674 break;
675 if (Operands.size() == AddRec->getNumOperands())
Dan Gohmana37eaf22007-10-22 18:31:58 +0000676 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +0000677 }
678
Chris Lattner538c6eb2006-10-04 21:49:37 +0000679 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattnerd934c702004-04-02 20:23:17 +0000680 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
681 return Result;
682}
683
Dan Gohmana37eaf22007-10-22 18:31:58 +0000684SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000685 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmana37eaf22007-10-22 18:31:58 +0000686 return getUnknown(
Reid Spencerbb65ebf2006-12-12 23:36:14 +0000687 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattnerd934c702004-04-02 20:23:17 +0000688
689 // FIXME: If the input value is a chrec scev, and we can prove that the value
690 // did not overflow the old, smaller, value, we can zero extend all of the
691 // operands (often constants). This would allow analysis of something like
692 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
693
Chris Lattner538c6eb2006-10-04 21:49:37 +0000694 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattnerd934c702004-04-02 20:23:17 +0000695 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
696 return Result;
697}
698
Dan Gohmana37eaf22007-10-22 18:31:58 +0000699SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000700 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmana37eaf22007-10-22 18:31:58 +0000701 return getUnknown(
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000702 ConstantExpr::getSExt(SC->getValue(), Ty));
703
704 // FIXME: If the input value is a chrec scev, and we can prove that the value
705 // did not overflow the old, smaller, value, we can sign extend all of the
706 // operands (often constants). This would allow analysis of something like
707 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
708
709 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
710 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
711 return Result;
712}
713
Nick Lewyckyed169d52008-06-13 04:38:55 +0000714/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
715/// of the input value to the specified type. If the type must be
716/// extended, it is zero extended.
717SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
718 const Type *Ty) {
719 const Type *SrcTy = V->getType();
720 assert(SrcTy->isInteger() && Ty->isInteger() &&
721 "Cannot truncate or zero extend with non-integer arguments!");
722 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
723 return V; // No conversion
724 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
725 return getTruncateExpr(V, Ty);
726 return getZeroExtendExpr(V, Ty);
727}
728
Chris Lattnerd934c702004-04-02 20:23:17 +0000729// get - Get a canonical add expression, or something simpler if possible.
Dan Gohmana37eaf22007-10-22 18:31:58 +0000730SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000731 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +0000732 if (Ops.size() == 1) return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +0000733
734 // Sort by complexity, this groups all similar expression types together.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000735 GroupByComplexity(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000736
737 // If there are any constants, fold them together.
738 unsigned Idx = 0;
739 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
740 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +0000741 assert(Idx < Ops.size());
Chris Lattnerd934c702004-04-02 20:23:17 +0000742 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
743 // We found two constants, fold them together!
Nick Lewycky1c44ebc2008-02-20 06:48:22 +0000744 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
745 RHSC->getValue()->getValue());
746 Ops[0] = getConstant(Fold);
747 Ops.erase(Ops.begin()+1); // Erase the folded element
748 if (Ops.size() == 1) return Ops[0];
749 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +0000750 }
751
752 // If we are left with a constant zero being added, strip it off.
Reid Spencer2e54a152007-03-02 00:28:52 +0000753 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000754 Ops.erase(Ops.begin());
755 --Idx;
756 }
757 }
758
Chris Lattner74498e12004-04-07 16:16:11 +0000759 if (Ops.size() == 1) return Ops[0];
Misha Brukman01808ca2005-04-21 21:13:18 +0000760
Chris Lattnerd934c702004-04-02 20:23:17 +0000761 // Okay, check to see if the same value occurs in the operand list twice. If
762 // so, merge them together into an multiply expression. Since we sorted the
763 // list, these values are required to be adjacent.
764 const Type *Ty = Ops[0]->getType();
765 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
766 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
767 // Found a match, merge the two values into a multiply, and add any
768 // remaining values to the result.
Dan Gohmana37eaf22007-10-22 18:31:58 +0000769 SCEVHandle Two = getIntegerSCEV(2, Ty);
770 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattnerd934c702004-04-02 20:23:17 +0000771 if (Ops.size() == 2)
772 return Mul;
773 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
774 Ops.push_back(Mul);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000775 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000776 }
777
Dan Gohmaneed125f2007-06-18 19:30:09 +0000778 // Now we know the first non-constant operand. Skip past any cast SCEVs.
779 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
780 ++Idx;
781
782 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +0000783 if (Idx < Ops.size()) {
784 bool DeletedAdd = false;
785 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
786 // If we have an add, expand the add operands onto the end of the operands
787 // list.
788 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
789 Ops.erase(Ops.begin()+Idx);
790 DeletedAdd = true;
791 }
792
793 // If we deleted at least one add, we added operands to the end of the list,
794 // and they are not necessarily sorted. Recurse to resort and resimplify
795 // any operands we just aquired.
796 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +0000797 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000798 }
799
800 // Skip over the add expression until we get to a multiply.
801 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
802 ++Idx;
803
804 // If we are adding something to a multiply expression, make sure the
805 // something is not already an operand of the multiply. If so, merge it into
806 // the multiply.
807 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
808 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
809 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
810 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
811 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattnera27dd472004-12-04 20:54:32 +0000812 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000813 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
814 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
815 if (Mul->getNumOperands() != 2) {
816 // If the multiply has more than two operands, we must get the
817 // Y*Z term.
818 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
819 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000820 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +0000821 }
Dan Gohmana37eaf22007-10-22 18:31:58 +0000822 SCEVHandle One = getIntegerSCEV(1, Ty);
823 SCEVHandle AddOne = getAddExpr(InnerMul, One);
824 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattnerd934c702004-04-02 20:23:17 +0000825 if (Ops.size() == 2) return OuterMul;
826 if (AddOp < Idx) {
827 Ops.erase(Ops.begin()+AddOp);
828 Ops.erase(Ops.begin()+Idx-1);
829 } else {
830 Ops.erase(Ops.begin()+Idx);
831 Ops.erase(Ops.begin()+AddOp-1);
832 }
833 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000834 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000835 }
Misha Brukman01808ca2005-04-21 21:13:18 +0000836
Chris Lattnerd934c702004-04-02 20:23:17 +0000837 // Check this multiply against other multiplies being added together.
838 for (unsigned OtherMulIdx = Idx+1;
839 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
840 ++OtherMulIdx) {
841 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
842 // If MulOp occurs in OtherMul, we can fold the two multiplies
843 // together.
844 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
845 OMulOp != e; ++OMulOp)
846 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
847 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
848 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
849 if (Mul->getNumOperands() != 2) {
850 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
851 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000852 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +0000853 }
854 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
855 if (OtherMul->getNumOperands() != 2) {
856 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
857 OtherMul->op_end());
858 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000859 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +0000860 }
Dan Gohmana37eaf22007-10-22 18:31:58 +0000861 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
862 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +0000863 if (Ops.size() == 2) return OuterMul;
864 Ops.erase(Ops.begin()+Idx);
865 Ops.erase(Ops.begin()+OtherMulIdx-1);
866 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000867 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000868 }
869 }
870 }
871 }
872
873 // If there are any add recurrences in the operands list, see if any other
874 // added values are loop invariant. If so, we can fold them into the
875 // recurrence.
876 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
877 ++Idx;
878
879 // Scan over all recurrences, trying to fold loop invariants into them.
880 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
881 // Scan all of the other operands to this add and add them to the vector if
882 // they are loop invariant w.r.t. the recurrence.
883 std::vector<SCEVHandle> LIOps;
884 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
885 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
886 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
887 LIOps.push_back(Ops[i]);
888 Ops.erase(Ops.begin()+i);
889 --i; --e;
890 }
891
892 // If we found some loop invariants, fold them into the recurrence.
893 if (!LIOps.empty()) {
894 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
895 LIOps.push_back(AddRec->getStart());
896
897 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +0000898 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattnerd934c702004-04-02 20:23:17 +0000899
Dan Gohmana37eaf22007-10-22 18:31:58 +0000900 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +0000901 // If all of the other operands were loop invariant, we are done.
902 if (Ops.size() == 1) return NewRec;
903
904 // Otherwise, add the folded AddRec by the non-liv parts.
905 for (unsigned i = 0;; ++i)
906 if (Ops[i] == AddRec) {
907 Ops[i] = NewRec;
908 break;
909 }
Dan Gohmana37eaf22007-10-22 18:31:58 +0000910 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000911 }
912
913 // Okay, if there weren't any loop invariants to be folded, check to see if
914 // there are multiple AddRec's with the same loop induction variable being
915 // added together. If so, we can fold them.
916 for (unsigned OtherIdx = Idx+1;
917 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
918 if (OtherIdx != Idx) {
919 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
920 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
921 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
922 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
923 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
924 if (i >= NewOps.size()) {
925 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
926 OtherAddRec->op_end());
927 break;
928 }
Dan Gohmana37eaf22007-10-22 18:31:58 +0000929 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattnerd934c702004-04-02 20:23:17 +0000930 }
Dan Gohmana37eaf22007-10-22 18:31:58 +0000931 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +0000932
933 if (Ops.size() == 2) return NewAddRec;
934
935 Ops.erase(Ops.begin()+Idx);
936 Ops.erase(Ops.begin()+OtherIdx-1);
937 Ops.push_back(NewAddRec);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000938 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000939 }
940 }
941
942 // Otherwise couldn't fold anything into this recurrence. Move onto the
943 // next one.
944 }
945
946 // Okay, it looks like we really DO need an add expr. Check to see if we
947 // already have one, otherwise create a new one.
948 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattner538c6eb2006-10-04 21:49:37 +0000949 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
950 SCEVOps)];
Chris Lattnerd934c702004-04-02 20:23:17 +0000951 if (Result == 0) Result = new SCEVAddExpr(Ops);
952 return Result;
953}
954
955
Dan Gohmana37eaf22007-10-22 18:31:58 +0000956SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000957 assert(!Ops.empty() && "Cannot get empty mul!");
958
959 // Sort by complexity, this groups all similar expression types together.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000960 GroupByComplexity(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000961
962 // If there are any constants, fold them together.
963 unsigned Idx = 0;
964 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
965
966 // C1*(C2+V) -> C1*C2 + C1*V
967 if (Ops.size() == 2)
968 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
969 if (Add->getNumOperands() == 2 &&
970 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohmana37eaf22007-10-22 18:31:58 +0000971 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
972 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +0000973
974
975 ++Idx;
976 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
977 // We found two constants, fold them together!
Nick Lewycky1c44ebc2008-02-20 06:48:22 +0000978 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
979 RHSC->getValue()->getValue());
980 Ops[0] = getConstant(Fold);
981 Ops.erase(Ops.begin()+1); // Erase the folded element
982 if (Ops.size() == 1) return Ops[0];
983 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +0000984 }
985
986 // If we are left with a constant one being multiplied, strip it off.
987 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
988 Ops.erase(Ops.begin());
989 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +0000990 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000991 // If we have a multiply of zero, it will always be zero.
992 return Ops[0];
993 }
994 }
995
996 // Skip over the add expression until we get to a multiply.
997 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
998 ++Idx;
999
1000 if (Ops.size() == 1)
1001 return Ops[0];
Misha Brukman01808ca2005-04-21 21:13:18 +00001002
Chris Lattnerd934c702004-04-02 20:23:17 +00001003 // If there are mul operands inline them all into this expression.
1004 if (Idx < Ops.size()) {
1005 bool DeletedMul = false;
1006 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1007 // If we have an mul, expand the mul operands onto the end of the operands
1008 // list.
1009 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1010 Ops.erase(Ops.begin()+Idx);
1011 DeletedMul = true;
1012 }
1013
1014 // If we deleted at least one mul, we added operands to the end of the list,
1015 // and they are not necessarily sorted. Recurse to resort and resimplify
1016 // any operands we just aquired.
1017 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00001018 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001019 }
1020
1021 // If there are any add recurrences in the operands list, see if any other
1022 // added values are loop invariant. If so, we can fold them into the
1023 // recurrence.
1024 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1025 ++Idx;
1026
1027 // Scan over all recurrences, trying to fold loop invariants into them.
1028 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1029 // Scan all of the other operands to this mul and add them to the vector if
1030 // they are loop invariant w.r.t. the recurrence.
1031 std::vector<SCEVHandle> LIOps;
1032 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1033 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1034 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1035 LIOps.push_back(Ops[i]);
1036 Ops.erase(Ops.begin()+i);
1037 --i; --e;
1038 }
1039
1040 // If we found some loop invariants, fold them into the recurrence.
1041 if (!LIOps.empty()) {
1042 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
1043 std::vector<SCEVHandle> NewOps;
1044 NewOps.reserve(AddRec->getNumOperands());
1045 if (LIOps.size() == 1) {
1046 SCEV *Scale = LIOps[0];
1047 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohmana37eaf22007-10-22 18:31:58 +00001048 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001049 } else {
1050 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1051 std::vector<SCEVHandle> MulOps(LIOps);
1052 MulOps.push_back(AddRec->getOperand(i));
Dan Gohmana37eaf22007-10-22 18:31:58 +00001053 NewOps.push_back(getMulExpr(MulOps));
Chris Lattnerd934c702004-04-02 20:23:17 +00001054 }
1055 }
1056
Dan Gohmana37eaf22007-10-22 18:31:58 +00001057 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +00001058
1059 // If all of the other operands were loop invariant, we are done.
1060 if (Ops.size() == 1) return NewRec;
1061
1062 // Otherwise, multiply the folded AddRec by the non-liv parts.
1063 for (unsigned i = 0;; ++i)
1064 if (Ops[i] == AddRec) {
1065 Ops[i] = NewRec;
1066 break;
1067 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00001068 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001069 }
1070
1071 // Okay, if there weren't any loop invariants to be folded, check to see if
1072 // there are multiple AddRec's with the same loop induction variable being
1073 // multiplied together. If so, we can fold them.
1074 for (unsigned OtherIdx = Idx+1;
1075 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1076 if (OtherIdx != Idx) {
1077 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1078 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1079 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1080 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohmana37eaf22007-10-22 18:31:58 +00001081 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattnerd934c702004-04-02 20:23:17 +00001082 G->getStart());
Dan Gohmana37eaf22007-10-22 18:31:58 +00001083 SCEVHandle B = F->getStepRecurrence(*this);
1084 SCEVHandle D = G->getStepRecurrence(*this);
1085 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1086 getMulExpr(G, B),
1087 getMulExpr(B, D));
1088 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1089 F->getLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +00001090 if (Ops.size() == 2) return NewAddRec;
1091
1092 Ops.erase(Ops.begin()+Idx);
1093 Ops.erase(Ops.begin()+OtherIdx-1);
1094 Ops.push_back(NewAddRec);
Dan Gohmana37eaf22007-10-22 18:31:58 +00001095 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001096 }
1097 }
1098
1099 // Otherwise couldn't fold anything into this recurrence. Move onto the
1100 // next one.
1101 }
1102
1103 // Okay, it looks like we really DO need an mul expr. Check to see if we
1104 // already have one, otherwise create a new one.
1105 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattner538c6eb2006-10-04 21:49:37 +00001106 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1107 SCEVOps)];
Chris Lattnera27dd472004-12-04 20:54:32 +00001108 if (Result == 0)
1109 Result = new SCEVMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001110 return Result;
1111}
1112
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001113SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001114 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1115 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001116 return LHS; // X udiv 1 --> x
Chris Lattnerd934c702004-04-02 20:23:17 +00001117
1118 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1119 Constant *LHSCV = LHSC->getValue();
1120 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001121 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattnerd934c702004-04-02 20:23:17 +00001122 }
1123 }
1124
1125 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1126
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001127 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1128 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00001129 return Result;
1130}
1131
1132
1133/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1134/// specified loop. Simplify the expression as much as possible.
Dan Gohmana37eaf22007-10-22 18:31:58 +00001135SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattnerd934c702004-04-02 20:23:17 +00001136 const SCEVHandle &Step, const Loop *L) {
1137 std::vector<SCEVHandle> Operands;
1138 Operands.push_back(Start);
1139 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1140 if (StepChrec->getLoop() == L) {
1141 Operands.insert(Operands.end(), StepChrec->op_begin(),
1142 StepChrec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00001143 return getAddRecExpr(Operands, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00001144 }
1145
1146 Operands.push_back(Step);
Dan Gohmana37eaf22007-10-22 18:31:58 +00001147 return getAddRecExpr(Operands, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00001148}
1149
1150/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1151/// specified loop. Simplify the expression as much as possible.
Dan Gohmana37eaf22007-10-22 18:31:58 +00001152SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattnerd934c702004-04-02 20:23:17 +00001153 const Loop *L) {
1154 if (Operands.size() == 1) return Operands[0];
1155
Dan Gohmanbe928e32008-06-18 16:23:07 +00001156 if (Operands.back()->isZero()) {
1157 Operands.pop_back();
1158 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
1159 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001160
1161 SCEVAddRecExpr *&Result =
Chris Lattner538c6eb2006-10-04 21:49:37 +00001162 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1163 Operands.end()))];
Chris Lattnerd934c702004-04-02 20:23:17 +00001164 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1165 return Result;
1166}
1167
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001168SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1169 const SCEVHandle &RHS) {
1170 std::vector<SCEVHandle> Ops;
1171 Ops.push_back(LHS);
1172 Ops.push_back(RHS);
1173 return getSMaxExpr(Ops);
1174}
1175
1176SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1177 assert(!Ops.empty() && "Cannot get empty smax!");
1178 if (Ops.size() == 1) return Ops[0];
1179
1180 // Sort by complexity, this groups all similar expression types together.
1181 GroupByComplexity(Ops);
1182
1183 // If there are any constants, fold them together.
1184 unsigned Idx = 0;
1185 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1186 ++Idx;
1187 assert(Idx < Ops.size());
1188 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1189 // We found two constants, fold them together!
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001190 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001191 APIntOps::smax(LHSC->getValue()->getValue(),
1192 RHSC->getValue()->getValue()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001193 Ops[0] = getConstant(Fold);
1194 Ops.erase(Ops.begin()+1); // Erase the folded element
1195 if (Ops.size() == 1) return Ops[0];
1196 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001197 }
1198
1199 // If we are left with a constant -inf, strip it off.
1200 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1201 Ops.erase(Ops.begin());
1202 --Idx;
1203 }
1204 }
1205
1206 if (Ops.size() == 1) return Ops[0];
1207
1208 // Find the first SMax
1209 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1210 ++Idx;
1211
1212 // Check to see if one of the operands is an SMax. If so, expand its operands
1213 // onto our operand list, and recurse to simplify.
1214 if (Idx < Ops.size()) {
1215 bool DeletedSMax = false;
1216 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1217 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1218 Ops.erase(Ops.begin()+Idx);
1219 DeletedSMax = true;
1220 }
1221
1222 if (DeletedSMax)
1223 return getSMaxExpr(Ops);
1224 }
1225
1226 // Okay, check to see if the same value occurs in the operand list twice. If
1227 // so, delete one. Since we sorted the list, these values are required to
1228 // be adjacent.
1229 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1230 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1231 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1232 --i; --e;
1233 }
1234
1235 if (Ops.size() == 1) return Ops[0];
1236
1237 assert(!Ops.empty() && "Reduced smax down to nothing!");
1238
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001239 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001240 // already have one, otherwise create a new one.
1241 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1242 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1243 SCEVOps)];
1244 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1245 return Result;
1246}
1247
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001248SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1249 const SCEVHandle &RHS) {
1250 std::vector<SCEVHandle> Ops;
1251 Ops.push_back(LHS);
1252 Ops.push_back(RHS);
1253 return getUMaxExpr(Ops);
1254}
1255
1256SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1257 assert(!Ops.empty() && "Cannot get empty umax!");
1258 if (Ops.size() == 1) return Ops[0];
1259
1260 // Sort by complexity, this groups all similar expression types together.
1261 GroupByComplexity(Ops);
1262
1263 // If there are any constants, fold them together.
1264 unsigned Idx = 0;
1265 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1266 ++Idx;
1267 assert(Idx < Ops.size());
1268 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1269 // We found two constants, fold them together!
1270 ConstantInt *Fold = ConstantInt::get(
1271 APIntOps::umax(LHSC->getValue()->getValue(),
1272 RHSC->getValue()->getValue()));
1273 Ops[0] = getConstant(Fold);
1274 Ops.erase(Ops.begin()+1); // Erase the folded element
1275 if (Ops.size() == 1) return Ops[0];
1276 LHSC = cast<SCEVConstant>(Ops[0]);
1277 }
1278
1279 // If we are left with a constant zero, strip it off.
1280 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1281 Ops.erase(Ops.begin());
1282 --Idx;
1283 }
1284 }
1285
1286 if (Ops.size() == 1) return Ops[0];
1287
1288 // Find the first UMax
1289 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1290 ++Idx;
1291
1292 // Check to see if one of the operands is a UMax. If so, expand its operands
1293 // onto our operand list, and recurse to simplify.
1294 if (Idx < Ops.size()) {
1295 bool DeletedUMax = false;
1296 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1297 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1298 Ops.erase(Ops.begin()+Idx);
1299 DeletedUMax = true;
1300 }
1301
1302 if (DeletedUMax)
1303 return getUMaxExpr(Ops);
1304 }
1305
1306 // Okay, check to see if the same value occurs in the operand list twice. If
1307 // so, delete one. Since we sorted the list, these values are required to
1308 // be adjacent.
1309 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1310 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1311 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1312 --i; --e;
1313 }
1314
1315 if (Ops.size() == 1) return Ops[0];
1316
1317 assert(!Ops.empty() && "Reduced umax down to nothing!");
1318
1319 // Okay, it looks like we really DO need a umax expr. Check to see if we
1320 // already have one, otherwise create a new one.
1321 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1322 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1323 SCEVOps)];
1324 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1325 return Result;
1326}
1327
Dan Gohmana37eaf22007-10-22 18:31:58 +00001328SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattnerb4f681b2004-04-15 15:07:24 +00001329 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmana37eaf22007-10-22 18:31:58 +00001330 return getConstant(CI);
Chris Lattner538c6eb2006-10-04 21:49:37 +00001331 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattnerb4f681b2004-04-15 15:07:24 +00001332 if (Result == 0) Result = new SCEVUnknown(V);
1333 return Result;
1334}
1335
Chris Lattnerd934c702004-04-02 20:23:17 +00001336
1337//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00001338// ScalarEvolutionsImpl Definition and Implementation
1339//===----------------------------------------------------------------------===//
1340//
1341/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1342/// evolution code.
1343///
1344namespace {
Chris Lattner996795b2006-06-28 23:17:24 +00001345 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohmana37eaf22007-10-22 18:31:58 +00001346 /// SE - A reference to the public ScalarEvolution object.
1347 ScalarEvolution &SE;
1348
Chris Lattnerd934c702004-04-02 20:23:17 +00001349 /// F - The function we are analyzing.
1350 ///
1351 Function &F;
1352
1353 /// LI - The loop information for the function we are currently analyzing.
1354 ///
1355 LoopInfo &LI;
1356
1357 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1358 /// things.
1359 SCEVHandle UnknownValue;
1360
1361 /// Scalars - This is a cache of the scalars we have analyzed so far.
1362 ///
1363 std::map<Value*, SCEVHandle> Scalars;
1364
1365 /// IterationCounts - Cache the iteration count of the loops for this
1366 /// function as they are computed.
1367 std::map<const Loop*, SCEVHandle> IterationCounts;
1368
Chris Lattnerdd730472004-04-17 22:58:41 +00001369 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1370 /// the PHI instructions that we attempt to compute constant evolutions for.
1371 /// This allows us to avoid potentially expensive recomputation of these
1372 /// properties. An instruction maps to null if we are unable to compute its
1373 /// exit value.
1374 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman01808ca2005-04-21 21:13:18 +00001375
Chris Lattnerd934c702004-04-02 20:23:17 +00001376 public:
Dan Gohmana37eaf22007-10-22 18:31:58 +00001377 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1378 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattnerd934c702004-04-02 20:23:17 +00001379
1380 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1381 /// expression and create a new one.
1382 SCEVHandle getSCEV(Value *V);
1383
Chris Lattnerb310ac4a2005-08-09 23:36:33 +00001384 /// hasSCEV - Return true if the SCEV for this value has already been
1385 /// computed.
1386 bool hasSCEV(Value *V) const {
1387 return Scalars.count(V);
1388 }
1389
1390 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1391 /// the specified value.
1392 void setSCEV(Value *V, const SCEVHandle &H) {
1393 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1394 assert(isNew && "This entry already existed!");
1395 }
1396
1397
Chris Lattnerd934c702004-04-02 20:23:17 +00001398 /// getSCEVAtScope - Compute the value of the specified expression within
1399 /// the indicated loop (which may be null to indicate in no loop). If the
1400 /// expression cannot be evaluated, return UnknownValue itself.
1401 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1402
1403
1404 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1405 /// an analyzable loop-invariant iteration count.
1406 bool hasLoopInvariantIterationCount(const Loop *L);
1407
1408 /// getIterationCount - If the specified loop has a predictable iteration
1409 /// count, return it. Note that it is not valid to call this method on a
1410 /// loop without a loop-invariant iteration count.
1411 SCEVHandle getIterationCount(const Loop *L);
1412
Dan Gohman32f53bb2007-06-19 14:28:31 +00001413 /// deleteValueFromRecords - This method should be called by the
1414 /// client before it removes a value from the program, to make sure
Chris Lattnerd934c702004-04-02 20:23:17 +00001415 /// that no dangling references are left around.
Dan Gohman32f53bb2007-06-19 14:28:31 +00001416 void deleteValueFromRecords(Value *V);
Chris Lattnerd934c702004-04-02 20:23:17 +00001417
1418 private:
1419 /// createSCEV - We know that there is no SCEV for the specified value.
1420 /// Analyze the expression.
1421 SCEVHandle createSCEV(Value *V);
Chris Lattnerd934c702004-04-02 20:23:17 +00001422
1423 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1424 /// SCEVs.
1425 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001426
1427 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1428 /// for the specified instruction and replaces any references to the
1429 /// symbolic value SymName with the specified value. This is used during
1430 /// PHI resolution.
1431 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1432 const SCEVHandle &SymName,
1433 const SCEVHandle &NewVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00001434
1435 /// ComputeIterationCount - Compute the number of times the specified loop
1436 /// will iterate.
1437 SCEVHandle ComputeIterationCount(const Loop *L);
1438
Chris Lattnerec901cc2004-10-12 01:49:27 +00001439 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky74a26e32007-11-20 08:44:50 +00001440 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattnerec901cc2004-10-12 01:49:27 +00001441 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1442 Constant *RHS,
1443 const Loop *L,
Reid Spencer266e42b2006-12-23 06:05:41 +00001444 ICmpInst::Predicate p);
Chris Lattnerec901cc2004-10-12 01:49:27 +00001445
Chris Lattner4021d1a2004-04-17 18:36:24 +00001446 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1447 /// constant number of times (the condition evolves only from constants),
1448 /// try to evaluate a few iterations of the loop until we get the exit
1449 /// condition gets a value of ExitWhen (true or false). If we cannot
1450 /// evaluate the trip count of the loop, return UnknownValue.
1451 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1452 bool ExitWhen);
1453
Chris Lattnerd934c702004-04-02 20:23:17 +00001454 /// HowFarToZero - Return the number of times a backedge comparing the
1455 /// specified value to zero will execute. If not computable, return
Chris Lattner587a75b2005-08-15 23:33:51 +00001456 /// UnknownValue.
Chris Lattnerd934c702004-04-02 20:23:17 +00001457 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1458
1459 /// HowFarToNonZero - Return the number of times a backedge checking the
1460 /// specified value for nonzero will execute. If not computable, return
Chris Lattner587a75b2005-08-15 23:33:51 +00001461 /// UnknownValue.
Chris Lattnerd934c702004-04-02 20:23:17 +00001462 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattnerdd730472004-04-17 22:58:41 +00001463
Chris Lattner587a75b2005-08-15 23:33:51 +00001464 /// HowManyLessThans - Return the number of times a backedge containing the
1465 /// specified less-than comparison will execute. If not computable, return
Nick Lewycky96606ce2007-08-06 19:21:00 +00001466 /// UnknownValue. isSigned specifies whether the less-than is signed.
1467 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1468 bool isSigned);
Chris Lattner587a75b2005-08-15 23:33:51 +00001469
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00001470 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1471 /// a conditional between LHS and RHS.
1472 bool executesAtLeastOnce(const Loop *L, bool isSigned, SCEV *LHS, SCEV *RHS);
1473
Chris Lattnerdd730472004-04-17 22:58:41 +00001474 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1475 /// in the header of its containing loop, we know the loop executes a
1476 /// constant number of times, and the PHI node is just a recurrence
1477 /// involving constants, fold it.
Reid Spencer983e3b32007-03-01 07:25:48 +00001478 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattnerdd730472004-04-17 22:58:41 +00001479 const Loop *L);
Chris Lattnerd934c702004-04-02 20:23:17 +00001480 };
1481}
1482
1483//===----------------------------------------------------------------------===//
1484// Basic SCEV Analysis and PHI Idiom Recognition Code
1485//
1486
Dan Gohman32f53bb2007-06-19 14:28:31 +00001487/// deleteValueFromRecords - This method should be called by the
Chris Lattnerd934c702004-04-02 20:23:17 +00001488/// client before it removes an instruction from the program, to make sure
1489/// that no dangling references are left around.
Dan Gohman32f53bb2007-06-19 14:28:31 +00001490void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1491 SmallVector<Value *, 16> Worklist;
Nick Lewycky3e842122007-06-06 04:12:20 +00001492
Dan Gohman32f53bb2007-06-19 14:28:31 +00001493 if (Scalars.erase(V)) {
1494 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky3e842122007-06-06 04:12:20 +00001495 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman32f53bb2007-06-19 14:28:31 +00001496 Worklist.push_back(V);
Nick Lewycky3e842122007-06-06 04:12:20 +00001497 }
1498
1499 while (!Worklist.empty()) {
Dan Gohman32f53bb2007-06-19 14:28:31 +00001500 Value *VV = Worklist.back();
Nick Lewycky3e842122007-06-06 04:12:20 +00001501 Worklist.pop_back();
1502
Dan Gohman32f53bb2007-06-19 14:28:31 +00001503 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky3e842122007-06-06 04:12:20 +00001504 UI != UE; ++UI) {
Nick Lewyckydf543f42007-06-06 11:26:20 +00001505 Instruction *Inst = cast<Instruction>(*UI);
1506 if (Scalars.erase(Inst)) {
Dan Gohman32f53bb2007-06-19 14:28:31 +00001507 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky3e842122007-06-06 04:12:20 +00001508 ConstantEvolutionLoopExitValue.erase(PN);
1509 Worklist.push_back(Inst);
1510 }
1511 }
1512 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001513}
1514
1515
1516/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1517/// expression and create a new one.
1518SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1519 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1520
1521 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1522 if (I != Scalars.end()) return I->second;
1523 SCEVHandle S = createSCEV(V);
1524 Scalars.insert(std::make_pair(V, S));
1525 return S;
1526}
1527
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001528/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1529/// the specified instruction and replaces any references to the symbolic value
1530/// SymName with the specified value. This is used during PHI resolution.
1531void ScalarEvolutionsImpl::
1532ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1533 const SCEVHandle &NewVal) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001534 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001535 if (SI == Scalars.end()) return;
Chris Lattnerd934c702004-04-02 20:23:17 +00001536
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001537 SCEVHandle NV =
Dan Gohmana37eaf22007-10-22 18:31:58 +00001538 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001539 if (NV == SI->second) return; // No change.
1540
1541 SI->second = NV; // Update the scalars map!
1542
1543 // Any instruction values that use this instruction might also need to be
1544 // updated!
1545 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1546 UI != E; ++UI)
1547 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1548}
Chris Lattnerd934c702004-04-02 20:23:17 +00001549
1550/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1551/// a loop header, making it a potential recurrence, or it doesn't.
1552///
1553SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1554 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1555 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1556 if (L->getHeader() == PN->getParent()) {
1557 // If it lives in the loop header, it has two incoming values, one
1558 // from outside the loop, and one from inside.
1559 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1560 unsigned BackEdge = IncomingEdge^1;
Misha Brukman01808ca2005-04-21 21:13:18 +00001561
Chris Lattnerd934c702004-04-02 20:23:17 +00001562 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmana37eaf22007-10-22 18:31:58 +00001563 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00001564 assert(Scalars.find(PN) == Scalars.end() &&
1565 "PHI node already processed?");
1566 Scalars.insert(std::make_pair(PN, SymbolicName));
1567
1568 // Using this symbolic name for the PHI, analyze the value coming around
1569 // the back-edge.
1570 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1571
1572 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1573 // has a special value for the first iteration of the loop.
1574
1575 // If the value coming around the backedge is an add with the symbolic
1576 // value we just inserted, then we found a simple induction variable!
1577 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1578 // If there is a single occurrence of the symbolic value, replace it
1579 // with a recurrence.
1580 unsigned FoundIndex = Add->getNumOperands();
1581 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1582 if (Add->getOperand(i) == SymbolicName)
1583 if (FoundIndex == e) {
1584 FoundIndex = i;
1585 break;
1586 }
1587
1588 if (FoundIndex != Add->getNumOperands()) {
1589 // Create an add with everything but the specified operand.
1590 std::vector<SCEVHandle> Ops;
1591 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1592 if (i != FoundIndex)
1593 Ops.push_back(Add->getOperand(i));
Dan Gohmana37eaf22007-10-22 18:31:58 +00001594 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001595
1596 // This is not a valid addrec if the step amount is varying each
1597 // loop iteration, but is not itself an addrec in this loop.
1598 if (Accum->isLoopInvariant(L) ||
1599 (isa<SCEVAddRecExpr>(Accum) &&
1600 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1601 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmana37eaf22007-10-22 18:31:58 +00001602 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00001603
1604 // Okay, for the entire analysis of this edge we assumed the PHI
1605 // to be symbolic. We now need to go back and update all of the
1606 // entries for the scalars that use the PHI (except for the PHI
1607 // itself) to use the new analyzed value instead of the "symbolic"
1608 // value.
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001609 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00001610 return PHISCEV;
1611 }
1612 }
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00001613 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1614 // Otherwise, this could be a loop like this:
1615 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1616 // In this case, j = {1,+,1} and BEValue is j.
1617 // Because the other in-value of i (0) fits the evolution of BEValue
1618 // i really is an addrec evolution.
1619 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1620 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1621
1622 // If StartVal = j.start - j.stride, we can use StartVal as the
1623 // initial step of the addrec evolution.
Dan Gohmana37eaf22007-10-22 18:31:58 +00001624 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1625 AddRec->getOperand(1))) {
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00001626 SCEVHandle PHISCEV =
Dan Gohmana37eaf22007-10-22 18:31:58 +00001627 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00001628
1629 // Okay, for the entire analysis of this edge we assumed the PHI
1630 // to be symbolic. We now need to go back and update all of the
1631 // entries for the scalars that use the PHI (except for the PHI
1632 // itself) to use the new analyzed value instead of the "symbolic"
1633 // value.
1634 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1635 return PHISCEV;
1636 }
1637 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001638 }
1639
1640 return SymbolicName;
1641 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001642
Chris Lattnerd934c702004-04-02 20:23:17 +00001643 // If it's not a loop phi, we can't handle it yet.
Dan Gohmana37eaf22007-10-22 18:31:58 +00001644 return SE.getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00001645}
1646
Nick Lewycky3783b462007-11-22 07:59:40 +00001647/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1648/// guaranteed to end in (at every loop iteration). It is, at the same time,
1649/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1650/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1651static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1652 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner69ec1ec2007-11-23 22:36:49 +00001653 return C->getValue()->getValue().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00001654
Nick Lewycky74a26e32007-11-20 08:44:50 +00001655 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky3783b462007-11-22 07:59:40 +00001656 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1657
1658 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1659 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1660 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1661 }
1662
1663 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1664 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1665 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1666 }
1667
Chris Lattner49b090e2006-12-12 02:26:09 +00001668 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00001669 // The result is the min of all operands results.
1670 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1671 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1672 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1673 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00001674 }
1675
1676 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00001677 // The result is the sum of all operands results.
1678 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1679 uint32_t BitWidth = M->getBitWidth();
1680 for (unsigned i = 1, e = M->getNumOperands();
1681 SumOpRes != BitWidth && i != e; ++i)
1682 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1683 BitWidth);
1684 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00001685 }
Nick Lewycky3783b462007-11-22 07:59:40 +00001686
Chris Lattner49b090e2006-12-12 02:26:09 +00001687 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00001688 // The result is the min of all operands results.
1689 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1690 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1691 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1692 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00001693 }
Nick Lewycky3783b462007-11-22 07:59:40 +00001694
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001695 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1696 // The result is the min of all operands results.
1697 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1698 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1699 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1700 return MinOpRes;
1701 }
1702
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001703 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1704 // The result is the min of all operands results.
1705 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1706 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1707 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1708 return MinOpRes;
1709 }
1710
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001711 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky3783b462007-11-22 07:59:40 +00001712 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00001713}
Chris Lattnerd934c702004-04-02 20:23:17 +00001714
1715/// createSCEV - We know that there is no SCEV for the specified value.
1716/// Analyze the expression.
1717///
1718SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattnera8fbde32007-11-23 08:46:22 +00001719 if (!isa<IntegerType>(V->getType()))
1720 return SE.getUnknown(V);
1721
Dan Gohman05e89732008-06-22 19:56:46 +00001722 unsigned Opcode = Instruction::UserOp1;
1723 if (Instruction *I = dyn_cast<Instruction>(V))
1724 Opcode = I->getOpcode();
1725 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1726 Opcode = CE->getOpcode();
1727 else
1728 return SE.getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00001729
Dan Gohman05e89732008-06-22 19:56:46 +00001730 User *U = cast<User>(V);
1731 switch (Opcode) {
1732 case Instruction::Add:
1733 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1734 getSCEV(U->getOperand(1)));
1735 case Instruction::Mul:
1736 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1737 getSCEV(U->getOperand(1)));
1738 case Instruction::UDiv:
1739 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1740 getSCEV(U->getOperand(1)));
1741 case Instruction::Sub:
1742 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1743 getSCEV(U->getOperand(1)));
1744 case Instruction::Or:
1745 // If the RHS of the Or is a constant, we may have something like:
1746 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1747 // optimizations will transparently handle this case.
1748 //
1749 // In order for this transformation to be safe, the LHS must be of the
1750 // form X*(2^n) and the Or constant must be less than 2^n.
1751 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1752 SCEVHandle LHS = getSCEV(U->getOperand(0));
1753 const APInt &CIVal = CI->getValue();
1754 if (GetMinTrailingZeros(LHS) >=
1755 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1756 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001757 }
Dan Gohman05e89732008-06-22 19:56:46 +00001758 break;
1759 case Instruction::Xor:
Dan Gohman05e89732008-06-22 19:56:46 +00001760 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00001761 // If the RHS of the xor is a signbit, then this is just an add.
1762 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman05e89732008-06-22 19:56:46 +00001763 if (CI->getValue().isSignBit())
1764 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1765 getSCEV(U->getOperand(1)));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00001766
1767 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman05e89732008-06-22 19:56:46 +00001768 else if (CI->isAllOnesValue())
1769 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1770 }
1771 break;
1772
1773 case Instruction::Shl:
1774 // Turn shift left of a constant amount into a multiply.
1775 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1776 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1777 Constant *X = ConstantInt::get(
1778 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1779 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1780 }
1781 break;
1782
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00001783 case Instruction::LShr:
1784 // Turn logical shift right of a constant into a unsigned divide.
1785 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1786 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1787 Constant *X = ConstantInt::get(
1788 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1789 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1790 }
1791 break;
1792
Dan Gohman05e89732008-06-22 19:56:46 +00001793 case Instruction::Trunc:
1794 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1795
1796 case Instruction::ZExt:
1797 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1798
1799 case Instruction::SExt:
1800 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1801
1802 case Instruction::BitCast:
1803 // BitCasts are no-op casts so we just eliminate the cast.
1804 if (U->getType()->isInteger() &&
1805 U->getOperand(0)->getType()->isInteger())
1806 return getSCEV(U->getOperand(0));
1807 break;
1808
1809 case Instruction::PHI:
1810 return createNodeForPHI(cast<PHINode>(U));
1811
1812 case Instruction::Select:
1813 // This could be a smax or umax that was lowered earlier.
1814 // Try to recover it.
1815 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1816 Value *LHS = ICI->getOperand(0);
1817 Value *RHS = ICI->getOperand(1);
1818 switch (ICI->getPredicate()) {
1819 case ICmpInst::ICMP_SLT:
1820 case ICmpInst::ICMP_SLE:
1821 std::swap(LHS, RHS);
1822 // fall through
1823 case ICmpInst::ICMP_SGT:
1824 case ICmpInst::ICMP_SGE:
1825 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1826 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1827 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman47369162008-07-30 04:36:32 +00001828 // ~smax(~x, ~y) == smin(x, y).
1829 return SE.getNotSCEV(SE.getSMaxExpr(
1830 SE.getNotSCEV(getSCEV(LHS)),
1831 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman05e89732008-06-22 19:56:46 +00001832 break;
1833 case ICmpInst::ICMP_ULT:
1834 case ICmpInst::ICMP_ULE:
1835 std::swap(LHS, RHS);
1836 // fall through
1837 case ICmpInst::ICMP_UGT:
1838 case ICmpInst::ICMP_UGE:
1839 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1840 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1841 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1842 // ~umax(~x, ~y) == umin(x, y)
1843 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1844 SE.getNotSCEV(getSCEV(RHS))));
1845 break;
1846 default:
1847 break;
1848 }
1849 }
1850
1851 default: // We cannot analyze this expression.
1852 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00001853 }
1854
Dan Gohmana37eaf22007-10-22 18:31:58 +00001855 return SE.getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00001856}
1857
1858
1859
1860//===----------------------------------------------------------------------===//
1861// Iteration Count Computation Code
1862//
1863
1864/// getIterationCount - If the specified loop has a predictable iteration
1865/// count, return it. Note that it is not valid to call this method on a
1866/// loop without a loop-invariant iteration count.
1867SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1868 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1869 if (I == IterationCounts.end()) {
1870 SCEVHandle ItCount = ComputeIterationCount(L);
1871 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1872 if (ItCount != UnknownValue) {
1873 assert(ItCount->isLoopInvariant(L) &&
1874 "Computed trip count isn't loop invariant for loop!");
1875 ++NumTripCountsComputed;
1876 } else if (isa<PHINode>(L->getHeader()->begin())) {
1877 // Only count loops that have phi nodes as not being computable.
1878 ++NumTripCountsNotComputed;
1879 }
1880 }
1881 return I->second;
1882}
1883
1884/// ComputeIterationCount - Compute the number of times the specified loop
1885/// will iterate.
1886SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1887 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb5933bb2007-08-21 00:31:24 +00001888 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00001889 L->getExitBlocks(ExitBlocks);
1890 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattnerd934c702004-04-02 20:23:17 +00001891
1892 // Okay, there is one exit block. Try to find the condition that causes the
1893 // loop to be exited.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00001894 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00001895
1896 BasicBlock *ExitingBlock = 0;
1897 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1898 PI != E; ++PI)
1899 if (L->contains(*PI)) {
1900 if (ExitingBlock == 0)
1901 ExitingBlock = *PI;
1902 else
1903 return UnknownValue; // More than one block exiting!
1904 }
1905 assert(ExitingBlock && "No exits from loop, something is broken!");
1906
1907 // Okay, we've computed the exiting block. See what condition causes us to
1908 // exit.
1909 //
1910 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattnerd934c702004-04-02 20:23:17 +00001911 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1912 if (ExitBr == 0) return UnknownValue;
1913 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner18954852007-01-07 02:24:26 +00001914
1915 // At this point, we know we have a conditional branch that determines whether
1916 // the loop is exited. However, we don't know if the branch is executed each
1917 // time through the loop. If not, then the execution count of the branch will
1918 // not be equal to the trip count of the loop.
1919 //
1920 // Currently we check for this by checking to see if the Exit branch goes to
1921 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00001922 // times as the loop. We also handle the case where the exit block *is* the
1923 // loop header. This is common for un-rotated loops. More extensive analysis
1924 // could be done to handle more cases here.
Chris Lattner18954852007-01-07 02:24:26 +00001925 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner5a554762007-01-14 01:24:47 +00001926 ExitBr->getSuccessor(1) != L->getHeader() &&
1927 ExitBr->getParent() != L->getHeader())
Chris Lattner18954852007-01-07 02:24:26 +00001928 return UnknownValue;
1929
Reid Spencer266e42b2006-12-23 06:05:41 +00001930 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1931
Nick Lewycky839adb82008-02-21 08:34:02 +00001932 // If it's not an integer comparison then compute it the hard way.
Reid Spencer266e42b2006-12-23 06:05:41 +00001933 // Note that ICmpInst deals with pointer comparisons too so we must check
1934 // the type of the operand.
Chris Lattner18954852007-01-07 02:24:26 +00001935 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner4021d1a2004-04-17 18:36:24 +00001936 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1937 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattnerd934c702004-04-02 20:23:17 +00001938
Reid Spencer266e42b2006-12-23 06:05:41 +00001939 // If the condition was exit on true, convert the condition to exit on false
1940 ICmpInst::Predicate Cond;
Chris Lattnerec901cc2004-10-12 01:49:27 +00001941 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencer266e42b2006-12-23 06:05:41 +00001942 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00001943 else
Reid Spencer266e42b2006-12-23 06:05:41 +00001944 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00001945
1946 // Handle common loops like: for (X = "string"; *X; ++X)
1947 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1948 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1949 SCEVHandle ItCnt =
1950 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1951 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1952 }
1953
Chris Lattnerd934c702004-04-02 20:23:17 +00001954 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1955 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1956
1957 // Try to evaluate any dependencies out of the loop.
1958 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1959 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1960 Tmp = getSCEVAtScope(RHS, L);
1961 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1962
Reid Spencer266e42b2006-12-23 06:05:41 +00001963 // At this point, we would like to compute how many iterations of the
1964 // loop the predicate will return true for these inputs.
Evan Cheng01d62572008-02-25 03:57:32 +00001965 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1966 // If there is a constant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00001967 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00001968 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00001969 }
1970
1971 // FIXME: think about handling pointer comparisons! i.e.:
1972 // while (P != P+100) ++P;
1973
1974 // If we have a comparison of a chrec against a constant, try to use value
1975 // ranges to answer this query.
1976 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1977 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1978 if (AddRec->getLoop() == L) {
1979 // Form the comparison range using the constant of the correct type so
1980 // that the ConstantRange class knows to do a signed or unsigned
1981 // comparison.
1982 ConstantInt *CompVal = RHSC->getValue();
1983 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencerb341b082006-12-12 05:05:00 +00001984 CompVal = dyn_cast<ConstantInt>(
Reid Spencer1ac0ab082006-12-12 09:17:50 +00001985 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001986 if (CompVal) {
1987 // Form the constant range.
Reid Spencerd373b9d2007-02-28 22:03:51 +00001988 ConstantRange CompRange(
1989 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman01808ca2005-04-21 21:13:18 +00001990
Dan Gohmana37eaf22007-10-22 18:31:58 +00001991 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00001992 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1993 }
1994 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001995
Chris Lattnerd934c702004-04-02 20:23:17 +00001996 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001997 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00001998 // Convert to: while (X-Y != 0)
Dan Gohmana37eaf22007-10-22 18:31:58 +00001999 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencer266e42b2006-12-23 06:05:41 +00002000 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerd934c702004-04-02 20:23:17 +00002001 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00002002 }
2003 case ICmpInst::ICMP_EQ: {
Chris Lattnerd934c702004-04-02 20:23:17 +00002004 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002005 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencer266e42b2006-12-23 06:05:41 +00002006 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerd934c702004-04-02 20:23:17 +00002007 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00002008 }
2009 case ICmpInst::ICMP_SLT: {
Nick Lewycky96606ce2007-08-06 19:21:00 +00002010 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencer266e42b2006-12-23 06:05:41 +00002011 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner587a75b2005-08-15 23:33:51 +00002012 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00002013 }
2014 case ICmpInst::ICMP_SGT: {
Eli Friedman5ae90442008-07-30 00:04:08 +00002015 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2016 SE.getNotSCEV(RHS), L, true);
Nick Lewycky96606ce2007-08-06 19:21:00 +00002017 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2018 break;
2019 }
2020 case ICmpInst::ICMP_ULT: {
2021 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2022 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2023 break;
2024 }
2025 case ICmpInst::ICMP_UGT: {
Dale Johannesen61457272008-04-20 16:58:57 +00002026 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewyckyf0bdd222008-05-06 04:03:18 +00002027 SE.getNotSCEV(RHS), L, false);
Reid Spencer266e42b2006-12-23 06:05:41 +00002028 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner587a75b2005-08-15 23:33:51 +00002029 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00002030 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002031 default:
Chris Lattner09169212004-04-02 20:26:46 +00002032#if 0
Bill Wendlingf3baad32006-12-07 01:30:32 +00002033 cerr << "ComputeIterationCount ";
Chris Lattnerd934c702004-04-02 20:23:17 +00002034 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlingf3baad32006-12-07 01:30:32 +00002035 cerr << "[unsigned] ";
2036 cerr << *LHS << " "
Reid Spencer266e42b2006-12-23 06:05:41 +00002037 << Instruction::getOpcodeName(Instruction::ICmp)
2038 << " " << *RHS << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00002039#endif
Chris Lattner0defaa12004-04-03 00:43:03 +00002040 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00002041 }
Chris Lattner4021d1a2004-04-17 18:36:24 +00002042 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencer266e42b2006-12-23 06:05:41 +00002043 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner4021d1a2004-04-17 18:36:24 +00002044}
2045
Chris Lattnerec901cc2004-10-12 01:49:27 +00002046static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00002047EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2048 ScalarEvolution &SE) {
2049 SCEVHandle InVal = SE.getConstant(C);
2050 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00002051 assert(isa<SCEVConstant>(Val) &&
2052 "Evaluation of SCEV at constant didn't fold correctly?");
2053 return cast<SCEVConstant>(Val)->getValue();
2054}
2055
2056/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2057/// and a GEP expression (missing the pointer index) indexing into it, return
2058/// the addressed element of the initializer or null if the index expression is
2059/// invalid.
2060static Constant *
Misha Brukman01808ca2005-04-21 21:13:18 +00002061GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattnerec901cc2004-10-12 01:49:27 +00002062 const std::vector<ConstantInt*> &Indices) {
2063 Constant *Init = GV->getInitializer();
2064 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002065 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattnerec901cc2004-10-12 01:49:27 +00002066 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2067 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2068 Init = cast<Constant>(CS->getOperand(Idx));
2069 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2070 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2071 Init = cast<Constant>(CA->getOperand(Idx));
2072 } else if (isa<ConstantAggregateZero>(Init)) {
2073 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2074 assert(Idx < STy->getNumElements() && "Bad struct index!");
2075 Init = Constant::getNullValue(STy->getElementType(Idx));
2076 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2077 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2078 Init = Constant::getNullValue(ATy->getElementType());
2079 } else {
2080 assert(0 && "Unknown constant aggregate type!");
2081 }
2082 return 0;
2083 } else {
2084 return 0; // Unknown initializer type
2085 }
2086 }
2087 return Init;
2088}
2089
2090/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewyckyf0bdd222008-05-06 04:03:18 +00002091/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattnerec901cc2004-10-12 01:49:27 +00002092SCEVHandle ScalarEvolutionsImpl::
Misha Brukman01808ca2005-04-21 21:13:18 +00002093ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencer266e42b2006-12-23 06:05:41 +00002094 const Loop *L,
2095 ICmpInst::Predicate predicate) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00002096 if (LI->isVolatile()) return UnknownValue;
2097
2098 // Check to see if the loaded pointer is a getelementptr of a global.
2099 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2100 if (!GEP) return UnknownValue;
2101
2102 // Make sure that it is really a constant global we are gepping, with an
2103 // initializer, and make sure the first IDX is really 0.
2104 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2105 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2106 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2107 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2108 return UnknownValue;
2109
2110 // Okay, we allow one non-constant index into the GEP instruction.
2111 Value *VarIdx = 0;
2112 std::vector<ConstantInt*> Indexes;
2113 unsigned VarIdxNum = 0;
2114 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2115 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2116 Indexes.push_back(CI);
2117 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2118 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2119 VarIdx = GEP->getOperand(i);
2120 VarIdxNum = i-2;
2121 Indexes.push_back(0);
2122 }
2123
2124 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2125 // Check to see if X is a loop variant variable value now.
2126 SCEVHandle Idx = getSCEV(VarIdx);
2127 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2128 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2129
2130 // We can only recognize very limited forms of loop index expressions, in
2131 // particular, only affine AddRec's like {C1,+,C2}.
2132 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2133 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2134 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2135 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2136 return UnknownValue;
2137
2138 unsigned MaxSteps = MaxBruteForceIterations;
2139 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002140 ConstantInt *ItCst =
Reid Spencerc635f472006-12-31 05:48:39 +00002141 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002142 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00002143
2144 // Form the GEP offset.
2145 Indexes[VarIdxNum] = Val;
2146
2147 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2148 if (Result == 0) break; // Cannot compute!
2149
2150 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00002151 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002152 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00002153 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00002154#if 0
Bill Wendlingf3baad32006-12-07 01:30:32 +00002155 cerr << "\n***\n*** Computed loop count " << *ItCst
2156 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2157 << "***\n";
Chris Lattnerec901cc2004-10-12 01:49:27 +00002158#endif
2159 ++NumArrayLenItCounts;
Dan Gohmana37eaf22007-10-22 18:31:58 +00002160 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00002161 }
2162 }
2163 return UnknownValue;
2164}
2165
2166
Chris Lattnerdd730472004-04-17 22:58:41 +00002167/// CanConstantFold - Return true if we can constant fold an instruction of the
2168/// specified type, assuming that all operands were constants.
2169static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00002170 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattnerdd730472004-04-17 22:58:41 +00002171 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2172 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00002173
Chris Lattnerdd730472004-04-17 22:58:41 +00002174 if (const CallInst *CI = dyn_cast<CallInst>(I))
2175 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00002176 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00002177 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00002178}
2179
Chris Lattnerdd730472004-04-17 22:58:41 +00002180/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2181/// in the loop that V is derived from. We allow arbitrary operations along the
2182/// way, but the operands of an operation must either be constants or a value
2183/// derived from a constant PHI. If this expression does not fit with these
2184/// constraints, return null.
2185static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2186 // If this is not an instruction, or if this is an instruction outside of the
2187 // loop, it can't be derived from a loop PHI.
2188 Instruction *I = dyn_cast<Instruction>(V);
2189 if (I == 0 || !L->contains(I->getParent())) return 0;
2190
Anton Korobeynikov579f0712008-02-20 11:08:44 +00002191 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00002192 if (L->getHeader() == I->getParent())
2193 return PN;
2194 else
2195 // We don't currently keep track of the control flow needed to evaluate
2196 // PHIs, so we cannot handle PHIs inside of loops.
2197 return 0;
Anton Korobeynikov579f0712008-02-20 11:08:44 +00002198 }
Chris Lattnerdd730472004-04-17 22:58:41 +00002199
2200 // If we won't be able to constant fold this expression even if the operands
2201 // are constants, return early.
2202 if (!CanConstantFold(I)) return 0;
Misha Brukman01808ca2005-04-21 21:13:18 +00002203
Chris Lattnerdd730472004-04-17 22:58:41 +00002204 // Otherwise, we can evaluate this instruction if all of its operands are
2205 // constant or derived from a PHI node themselves.
2206 PHINode *PHI = 0;
2207 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2208 if (!(isa<Constant>(I->getOperand(Op)) ||
2209 isa<GlobalValue>(I->getOperand(Op)))) {
2210 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2211 if (P == 0) return 0; // Not evolving from PHI
2212 if (PHI == 0)
2213 PHI = P;
2214 else if (PHI != P)
2215 return 0; // Evolving from multiple different PHIs.
2216 }
2217
2218 // This is a expression evolving from a constant PHI!
2219 return PHI;
2220}
2221
2222/// EvaluateExpression - Given an expression that passes the
2223/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2224/// in the loop has the value PHIVal. If we can't fold this expression for some
2225/// reason, return null.
2226static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2227 if (isa<PHINode>(V)) return PHIVal;
Reid Spencer30d69a52004-07-18 00:18:30 +00002228 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattnerdd730472004-04-17 22:58:41 +00002229 Instruction *I = cast<Instruction>(V);
2230
2231 std::vector<Constant*> Operands;
2232 Operands.resize(I->getNumOperands());
2233
2234 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2235 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2236 if (Operands[i] == 0) return 0;
2237 }
2238
Chris Lattnerd2265b42007-12-10 22:53:04 +00002239 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2240 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2241 &Operands[0], Operands.size());
2242 else
2243 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2244 &Operands[0], Operands.size());
Chris Lattnerdd730472004-04-17 22:58:41 +00002245}
2246
2247/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2248/// in the header of its containing loop, we know the loop executes a
2249/// constant number of times, and the PHI node is just a recurrence
2250/// involving constants, fold it.
2251Constant *ScalarEvolutionsImpl::
Reid Spencer983e3b32007-03-01 07:25:48 +00002252getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattnerdd730472004-04-17 22:58:41 +00002253 std::map<PHINode*, Constant*>::iterator I =
2254 ConstantEvolutionLoopExitValue.find(PN);
2255 if (I != ConstantEvolutionLoopExitValue.end())
2256 return I->second;
2257
Reid Spencer983e3b32007-03-01 07:25:48 +00002258 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattnerdd730472004-04-17 22:58:41 +00002259 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2260
2261 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2262
2263 // Since the loop is canonicalized, the PHI node must have two entries. One
2264 // entry must be a constant (coming in from outside of the loop), and the
2265 // second must be derived from the same PHI.
2266 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2267 Constant *StartCST =
2268 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2269 if (StartCST == 0)
2270 return RetVal = 0; // Must be a constant.
2271
2272 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2273 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2274 if (PN2 != PN)
2275 return RetVal = 0; // Not derived from same PHI.
2276
2277 // Execute the loop symbolically to determine the exit value.
Reid Spencer983e3b32007-03-01 07:25:48 +00002278 if (Its.getActiveBits() >= 32)
2279 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00002280
Reid Spencer983e3b32007-03-01 07:25:48 +00002281 unsigned NumIterations = Its.getZExtValue(); // must be in range
2282 unsigned IterationNum = 0;
Chris Lattnerdd730472004-04-17 22:58:41 +00002283 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2284 if (IterationNum == NumIterations)
2285 return RetVal = PHIVal; // Got exit value!
2286
2287 // Compute the value of the PHI node for the next iteration.
2288 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2289 if (NextPHI == PHIVal)
2290 return RetVal = NextPHI; // Stopped evolving!
2291 if (NextPHI == 0)
2292 return 0; // Couldn't evaluate!
2293 PHIVal = NextPHI;
2294 }
2295}
2296
Chris Lattner4021d1a2004-04-17 18:36:24 +00002297/// ComputeIterationCountExhaustively - If the trip is known to execute a
2298/// constant number of times (the condition evolves only from constants),
2299/// try to evaluate a few iterations of the loop until we get the exit
2300/// condition gets a value of ExitWhen (true or false). If we cannot
2301/// evaluate the trip count of the loop, return UnknownValue.
2302SCEVHandle ScalarEvolutionsImpl::
2303ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2304 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2305 if (PN == 0) return UnknownValue;
2306
2307 // Since the loop is canonicalized, the PHI node must have two entries. One
2308 // entry must be a constant (coming in from outside of the loop), and the
2309 // second must be derived from the same PHI.
2310 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2311 Constant *StartCST =
2312 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2313 if (StartCST == 0) return UnknownValue; // Must be a constant.
2314
2315 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2316 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2317 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2318
2319 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2320 // the loop symbolically to determine when the condition gets a value of
2321 // "ExitWhen".
2322 unsigned IterationNum = 0;
2323 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2324 for (Constant *PHIVal = StartCST;
2325 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002326 ConstantInt *CondVal =
2327 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattnerdd730472004-04-17 22:58:41 +00002328
Zhou Sheng75b871f2007-01-11 12:24:14 +00002329 // Couldn't symbolically evaluate.
Chris Lattner19cfb042007-01-12 18:28:58 +00002330 if (!CondVal) return UnknownValue;
Zhou Sheng75b871f2007-01-11 12:24:14 +00002331
Reid Spencer983e3b32007-03-01 07:25:48 +00002332 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00002333 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner4021d1a2004-04-17 18:36:24 +00002334 ++NumBruteForceTripCountsComputed;
Dan Gohmana37eaf22007-10-22 18:31:58 +00002335 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner4021d1a2004-04-17 18:36:24 +00002336 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002337
Chris Lattnerdd730472004-04-17 22:58:41 +00002338 // Compute the value of the PHI node for the next iteration.
2339 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2340 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner4021d1a2004-04-17 18:36:24 +00002341 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattnerdd730472004-04-17 22:58:41 +00002342 PHIVal = NextPHI;
Chris Lattner4021d1a2004-04-17 18:36:24 +00002343 }
2344
2345 // Too many iterations were needed to evaluate.
Chris Lattnerd934c702004-04-02 20:23:17 +00002346 return UnknownValue;
2347}
2348
2349/// getSCEVAtScope - Compute the value of the specified expression within the
2350/// indicated loop (which may be null to indicate in no loop). If the
2351/// expression cannot be evaluated, return UnknownValue.
2352SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2353 // FIXME: this should be turned into a virtual method on SCEV!
2354
Chris Lattnerdd730472004-04-17 22:58:41 +00002355 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00002356
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002357 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00002358 // exit value from the loop without using SCEVs.
2359 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2360 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2361 const Loop *LI = this->LI[I->getParent()];
2362 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2363 if (PHINode *PN = dyn_cast<PHINode>(I))
2364 if (PN->getParent() == LI->getHeader()) {
2365 // Okay, there is no closed form solution for the PHI node. Check
2366 // to see if the loop that contains it has a known iteration count.
2367 // If so, we may be able to force computation of the exit value.
2368 SCEVHandle IterationCount = getIterationCount(LI);
2369 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2370 // Okay, we know how many times the containing loop executes. If
2371 // this is a constant evolving PHI node, get the final value at
2372 // the specified iteration number.
2373 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencer983e3b32007-03-01 07:25:48 +00002374 ICC->getValue()->getValue(),
Chris Lattnerdd730472004-04-17 22:58:41 +00002375 LI);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002376 if (RV) return SE.getUnknown(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00002377 }
2378 }
2379
Reid Spencere6328ca2006-12-04 21:33:23 +00002380 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00002381 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00002382 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00002383 // result. This is particularly useful for computing loop exit values.
2384 if (CanConstantFold(I)) {
2385 std::vector<Constant*> Operands;
2386 Operands.reserve(I->getNumOperands());
2387 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2388 Value *Op = I->getOperand(i);
2389 if (Constant *C = dyn_cast<Constant>(Op)) {
2390 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00002391 } else {
Chris Lattnera8fbde32007-11-23 08:46:22 +00002392 // If any of the operands is non-constant and if they are
2393 // non-integer, don't even try to analyze them with scev techniques.
2394 if (!isa<IntegerType>(Op->getType()))
2395 return V;
2396
Chris Lattnerdd730472004-04-17 22:58:41 +00002397 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2398 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002399 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2400 Op->getType(),
2401 false));
Chris Lattnerdd730472004-04-17 22:58:41 +00002402 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2403 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00002404 Operands.push_back(ConstantExpr::getIntegerCast(C,
2405 Op->getType(),
2406 false));
Chris Lattnerdd730472004-04-17 22:58:41 +00002407 else
2408 return V;
2409 } else {
2410 return V;
2411 }
2412 }
2413 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00002414
2415 Constant *C;
2416 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2417 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2418 &Operands[0], Operands.size());
2419 else
2420 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2421 &Operands[0], Operands.size());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002422 return SE.getUnknown(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00002423 }
2424 }
2425
2426 // This is some other type of SCEVUnknown, just return it.
2427 return V;
2428 }
2429
Chris Lattnerd934c702004-04-02 20:23:17 +00002430 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2431 // Avoid performing the look-up in the common case where the specified
2432 // expression has no loop-variant portions.
2433 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2434 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2435 if (OpAtScope != Comm->getOperand(i)) {
2436 if (OpAtScope == UnknownValue) return UnknownValue;
2437 // Okay, at least one of these operands is loop variant but might be
2438 // foldable. Build a new instance of the folded commutative expression.
Chris Lattnerdd730472004-04-17 22:58:41 +00002439 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00002440 NewOps.push_back(OpAtScope);
2441
2442 for (++i; i != e; ++i) {
2443 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2444 if (OpAtScope == UnknownValue) return UnknownValue;
2445 NewOps.push_back(OpAtScope);
2446 }
2447 if (isa<SCEVAddExpr>(Comm))
Dan Gohmana37eaf22007-10-22 18:31:58 +00002448 return SE.getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002449 if (isa<SCEVMulExpr>(Comm))
2450 return SE.getMulExpr(NewOps);
2451 if (isa<SCEVSMaxExpr>(Comm))
2452 return SE.getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002453 if (isa<SCEVUMaxExpr>(Comm))
2454 return SE.getUMaxExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002455 assert(0 && "Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00002456 }
2457 }
2458 // If we got here, all operands are loop invariant.
2459 return Comm;
2460 }
2461
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00002462 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Chris Lattner98e96042006-04-01 04:48:52 +00002463 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00002464 if (LHS == UnknownValue) return LHS;
Chris Lattner98e96042006-04-01 04:48:52 +00002465 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00002466 if (RHS == UnknownValue) return RHS;
Chris Lattner98e96042006-04-01 04:48:52 +00002467 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2468 return Div; // must be loop invariant
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00002469 return SE.getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00002470 }
2471
2472 // If this is a loop recurrence for a loop that does not contain L, then we
2473 // are dealing with the final value computed by the loop.
2474 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2475 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2476 // To evaluate this recurrence, we need to know how many times the AddRec
2477 // loop iterates. Compute this now.
2478 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2479 if (IterationCount == UnknownValue) return UnknownValue;
Misha Brukman01808ca2005-04-21 21:13:18 +00002480
Eli Friedman61f67622008-08-04 23:49:06 +00002481 // Then, evaluate the AddRec.
Dan Gohmana37eaf22007-10-22 18:31:58 +00002482 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00002483 }
2484 return UnknownValue;
2485 }
2486
2487 //assert(0 && "Unknown SCEV type!");
2488 return UnknownValue;
2489}
2490
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00002491/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2492/// following equation:
2493///
2494/// A * X = B (mod N)
2495///
2496/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2497/// A and B isn't important.
2498///
2499/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2500static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2501 ScalarEvolution &SE) {
2502 uint32_t BW = A.getBitWidth();
2503 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2504 assert(A != 0 && "A must be non-zero.");
2505
2506 // 1. D = gcd(A, N)
2507 //
2508 // The gcd of A and N may have only one prime factor: 2. The number of
2509 // trailing zeros in A is its multiplicity
2510 uint32_t Mult2 = A.countTrailingZeros();
2511 // D = 2^Mult2
2512
2513 // 2. Check if B is divisible by D.
2514 //
2515 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2516 // is not less than multiplicity of this prime factor for D.
2517 if (B.countTrailingZeros() < Mult2)
2518 return new SCEVCouldNotCompute();
2519
2520 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2521 // modulo (N / D).
2522 //
2523 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2524 // bit width during computations.
2525 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2526 APInt Mod(BW + 1, 0);
2527 Mod.set(BW - Mult2); // Mod = N / D
2528 APInt I = AD.multiplicativeInverse(Mod);
2529
2530 // 4. Compute the minimum unsigned root of the equation:
2531 // I * (B / D) mod (N / D)
2532 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2533
2534 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2535 // bits.
2536 return SE.getConstant(Result.trunc(BW));
2537}
Chris Lattnerd934c702004-04-02 20:23:17 +00002538
2539/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2540/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2541/// might be the same) or two SCEVCouldNotCompute objects.
2542///
2543static std::pair<SCEVHandle,SCEVHandle>
Dan Gohmana37eaf22007-10-22 18:31:58 +00002544SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002545 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencer983e3b32007-03-01 07:25:48 +00002546 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2547 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2548 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00002549
Chris Lattnerd934c702004-04-02 20:23:17 +00002550 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00002551 if (!LC || !MC || !NC) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002552 SCEV *CNC = new SCEVCouldNotCompute();
2553 return std::make_pair(CNC, CNC);
2554 }
2555
Reid Spencer983e3b32007-03-01 07:25:48 +00002556 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnercad61e82007-04-15 19:52:49 +00002557 const APInt &L = LC->getValue()->getValue();
2558 const APInt &M = MC->getValue()->getValue();
2559 const APInt &N = NC->getValue()->getValue();
Reid Spencer983e3b32007-03-01 07:25:48 +00002560 APInt Two(BitWidth, 2);
2561 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00002562
Reid Spencer983e3b32007-03-01 07:25:48 +00002563 {
2564 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00002565 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00002566 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2567 // The B coefficient is M-N/2
2568 APInt B(M);
2569 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00002570
Reid Spencer983e3b32007-03-01 07:25:48 +00002571 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00002572 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00002573
Reid Spencer983e3b32007-03-01 07:25:48 +00002574 // Compute the B^2-4ac term.
2575 APInt SqrtTerm(B);
2576 SqrtTerm *= B;
2577 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00002578
Reid Spencer983e3b32007-03-01 07:25:48 +00002579 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2580 // integer value or else APInt::sqrt() will assert.
2581 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00002582
Reid Spencer983e3b32007-03-01 07:25:48 +00002583 // Compute the two solutions for the quadratic formula.
2584 // The divisions must be performed as signed divisions.
2585 APInt NegB(-B);
Reid Spencera3cfb8a2007-04-16 02:24:41 +00002586 APInt TwoA( A << 1 );
Reid Spencer983e3b32007-03-01 07:25:48 +00002587 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2588 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00002589
Dan Gohmana37eaf22007-10-22 18:31:58 +00002590 return std::make_pair(SE.getConstant(Solution1),
2591 SE.getConstant(Solution2));
Reid Spencer983e3b32007-03-01 07:25:48 +00002592 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00002593}
2594
2595/// HowFarToZero - Return the number of times a backedge comparing the specified
2596/// value to zero will execute. If not computable, return UnknownValue
2597SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2598 // If the value is a constant
2599 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2600 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00002601 if (C->getValue()->isZero()) return C;
Chris Lattnerd934c702004-04-02 20:23:17 +00002602 return UnknownValue; // Otherwise it will loop infinitely.
2603 }
2604
2605 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2606 if (!AddRec || AddRec->getLoop() != L)
2607 return UnknownValue;
2608
2609 if (AddRec->isAffine()) {
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00002610 // If this is an affine expression, the execution count of this branch is
2611 // the minimum unsigned root of the following equation:
Chris Lattnerd934c702004-04-02 20:23:17 +00002612 //
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00002613 // Start + Step*N = 0 (mod 2^BW)
Chris Lattnerd934c702004-04-02 20:23:17 +00002614 //
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00002615 // equivalent to:
2616 //
2617 // Step*N = -Start (mod 2^BW)
2618 //
2619 // where BW is the common bit width of Start and Step.
2620
Chris Lattnerd934c702004-04-02 20:23:17 +00002621 // Get the initial value for the loop.
2622 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner6faf3942004-10-11 04:07:27 +00002623 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002624
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00002625 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +00002626
Chris Lattnerd934c702004-04-02 20:23:17 +00002627 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00002628 // For now we handle only constant steps.
Chris Lattnerd934c702004-04-02 20:23:17 +00002629
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00002630 // First, handle unitary steps.
2631 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2632 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2633 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2634 return Start; // N = Start (as unsigned)
2635
2636 // Then, try to solve the above equation provided that Start is constant.
2637 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2638 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2639 -StartC->getValue()->getValue(),SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00002640 }
Chris Lattner03c49532007-01-15 02:27:26 +00002641 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002642 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2643 // the quadratic equation to solve it.
Dan Gohmana37eaf22007-10-22 18:31:58 +00002644 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00002645 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2646 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2647 if (R1) {
Chris Lattner09169212004-04-02 20:26:46 +00002648#if 0
Bill Wendlingf3baad32006-12-07 01:30:32 +00002649 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2650 << " sol#2: " << *R2 << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00002651#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002652 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002653 if (ConstantInt *CB =
2654 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencer266e42b2006-12-23 06:05:41 +00002655 R1->getValue(), R2->getValue()))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00002656 if (CB->getZExtValue() == false)
Chris Lattnerd934c702004-04-02 20:23:17 +00002657 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00002658
Chris Lattnerd934c702004-04-02 20:23:17 +00002659 // We can only use this value if the chrec ends up with an exact zero
2660 // value at this index. When solving for "X*X != 5", for example, we
2661 // should not accept a root of 2.
Dan Gohmana37eaf22007-10-22 18:31:58 +00002662 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmanbe928e32008-06-18 16:23:07 +00002663 if (Val->isZero())
2664 return R1; // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00002665 }
2666 }
2667 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002668
Chris Lattnerd934c702004-04-02 20:23:17 +00002669 return UnknownValue;
2670}
2671
2672/// HowFarToNonZero - Return the number of times a backedge checking the
2673/// specified value for nonzero will execute. If not computable, return
2674/// UnknownValue
2675SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2676 // Loops that look like: while (X == 0) are very strange indeed. We don't
2677 // handle them yet except for the trivial case. This could be expanded in the
2678 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00002679
Chris Lattnerd934c702004-04-02 20:23:17 +00002680 // If the value is a constant, check to see if it is known to be non-zero
2681 // already. If so, the backedge will execute zero times.
2682 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00002683 if (!C->getValue()->isNullValue())
2684 return SE.getIntegerSCEV(0, C->getType());
Chris Lattnerd934c702004-04-02 20:23:17 +00002685 return UnknownValue; // Otherwise it will loop infinitely.
2686 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002687
Chris Lattnerd934c702004-04-02 20:23:17 +00002688 // We could implement others, but I really doubt anyone writes loops like
2689 // this, and if they did, they would already be constant folded.
2690 return UnknownValue;
2691}
2692
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00002693/// executesAtLeastOnce - Test whether entry to the loop is protected by
2694/// a conditional between LHS and RHS.
2695bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2696 SCEV *LHS, SCEV *RHS) {
2697 BasicBlock *Preheader = L->getLoopPreheader();
2698 BasicBlock *PreheaderDest = L->getHeader();
2699 if (Preheader == 0) return false;
2700
2701 BranchInst *LoopEntryPredicate =
2702 dyn_cast<BranchInst>(Preheader->getTerminator());
2703 if (!LoopEntryPredicate) return false;
2704
2705 // This might be a critical edge broken out. If the loop preheader ends in
2706 // an unconditional branch to the loop, check to see if the preheader has a
2707 // single predecessor, and if so, look for its terminator.
2708 while (LoopEntryPredicate->isUnconditional()) {
2709 PreheaderDest = Preheader;
2710 Preheader = Preheader->getSinglePredecessor();
2711 if (!Preheader) return false; // Multiple preds.
2712
2713 LoopEntryPredicate =
2714 dyn_cast<BranchInst>(Preheader->getTerminator());
2715 if (!LoopEntryPredicate) return false;
2716 }
2717
2718 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2719 if (!ICI) return false;
2720
2721 // Now that we found a conditional branch that dominates the loop, check to
2722 // see if it is the comparison we are looking for.
2723 Value *PreCondLHS = ICI->getOperand(0);
2724 Value *PreCondRHS = ICI->getOperand(1);
2725 ICmpInst::Predicate Cond;
2726 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2727 Cond = ICI->getPredicate();
2728 else
2729 Cond = ICI->getInversePredicate();
2730
2731 switch (Cond) {
2732 case ICmpInst::ICMP_UGT:
2733 if (isSigned) return false;
2734 std::swap(PreCondLHS, PreCondRHS);
2735 Cond = ICmpInst::ICMP_ULT;
2736 break;
2737 case ICmpInst::ICMP_SGT:
2738 if (!isSigned) return false;
2739 std::swap(PreCondLHS, PreCondRHS);
2740 Cond = ICmpInst::ICMP_SLT;
2741 break;
2742 case ICmpInst::ICMP_ULT:
2743 if (isSigned) return false;
2744 break;
2745 case ICmpInst::ICMP_SLT:
2746 if (!isSigned) return false;
2747 break;
2748 default:
2749 return false;
2750 }
2751
Nick Lewycky970914c2008-07-15 03:47:44 +00002752 if (!PreCondLHS->getType()->isInteger()) return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00002753
Eli Friedman5ae90442008-07-30 00:04:08 +00002754 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2755 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2756 return (LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2757 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2758 RHS == SE.getNotSCEV(PreCondLHSSCEV));
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00002759}
2760
Chris Lattner587a75b2005-08-15 23:33:51 +00002761/// HowManyLessThans - Return the number of times a backedge containing the
2762/// specified less-than comparison will execute. If not computable, return
2763/// UnknownValue.
2764SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky96606ce2007-08-06 19:21:00 +00002765HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattner587a75b2005-08-15 23:33:51 +00002766 // Only handle: "ADDREC < LoopInvariant".
2767 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2768
2769 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2770 if (!AddRec || AddRec->getLoop() != L)
2771 return UnknownValue;
2772
2773 if (AddRec->isAffine()) {
2774 // FORNOW: We only support unit strides.
Dan Gohmana37eaf22007-10-22 18:31:58 +00002775 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Chris Lattner587a75b2005-08-15 23:33:51 +00002776 if (AddRec->getOperand(1) != One)
2777 return UnknownValue;
2778
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00002779 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2780 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2781 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz0e411f62008-02-13 12:21:32 +00002782 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattner587a75b2005-08-15 23:33:51 +00002783
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00002784 // First, we get the value of the LHS in the first iteration: n
2785 SCEVHandle Start = AddRec->getOperand(0);
2786
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00002787 if (executesAtLeastOnce(L, isSigned,
Nick Lewycky3752e512008-07-15 03:40:27 +00002788 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2789 // Since we know that the condition is true in order to enter the loop,
2790 // we know that it will run exactly m-n times.
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00002791 return SE.getMinusSCEV(RHS, Start);
Nick Lewycky3752e512008-07-15 03:40:27 +00002792 } else {
2793 // Then, we get the value of the LHS in the first iteration in which the
2794 // above condition doesn't hold. This equals to max(m,n).
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00002795 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2796 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00002797
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00002798 // Finally, we subtract these two values to get the number of times the
2799 // backedge is executed: max(m,n)-n.
2800 return SE.getMinusSCEV(End, Start);
2801 }
Chris Lattner587a75b2005-08-15 23:33:51 +00002802 }
2803
2804 return UnknownValue;
2805}
2806
Chris Lattnerd934c702004-04-02 20:23:17 +00002807/// getNumIterationsInRange - Return the number of iterations of this loop that
2808/// produce values in the specified constant range. Another way of looking at
2809/// this is that it returns the first iteration number where the value is not in
2810/// the condition, thus computing the exit count. If the iteration count can't
2811/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmana37eaf22007-10-22 18:31:58 +00002812SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2813 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00002814 if (Range.isFullSet()) // Infinite loop.
2815 return new SCEVCouldNotCompute();
2816
2817 // If the start is a non-zero constant, shift the range to simplify things.
2818 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00002819 if (!SC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002820 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002821 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2822 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +00002823 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2824 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohmana37eaf22007-10-22 18:31:58 +00002825 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00002826 // This is strange and shouldn't happen.
2827 return new SCEVCouldNotCompute();
2828 }
2829
2830 // The only time we can solve this is when we have all constant indices.
2831 // Otherwise, we cannot determine the overflow conditions.
2832 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2833 if (!isa<SCEVConstant>(getOperand(i)))
2834 return new SCEVCouldNotCompute();
2835
2836
2837 // Okay at this point we know that all elements of the chrec are constants and
2838 // that the start element is zero.
2839
2840 // First check to see if the range contains zero. If not, the first
2841 // iteration exits.
Reid Spencer6a440332007-03-01 07:54:15 +00002842 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohmana37eaf22007-10-22 18:31:58 +00002843 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman01808ca2005-04-21 21:13:18 +00002844
Chris Lattnerd934c702004-04-02 20:23:17 +00002845 if (isAffine()) {
2846 // If this is an affine expression then we have this situation:
2847 // Solve {0,+,A} in Range === Ax in Range
2848
Nick Lewycky52460262007-07-16 02:08:00 +00002849 // We know that zero is in the range. If A is positive then we know that
2850 // the upper value of the range must be the first possible exit value.
2851 // If A is negative then the lower of the range is the last possible loop
2852 // value. Also note that we already checked for a full range.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00002853 APInt One(getBitWidth(),1);
Nick Lewycky52460262007-07-16 02:08:00 +00002854 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2855 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00002856
Nick Lewycky52460262007-07-16 02:08:00 +00002857 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00002858 APInt ExitVal = (End + A).udiv(A);
Reid Spencerfad3f242007-03-01 19:32:33 +00002859 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00002860
2861 // Evaluate at the exit value. If we really did fall out of the valid
2862 // range, then we computed our trip count, otherwise wrap around or other
2863 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00002864 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00002865 if (Range.contains(Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00002866 return new SCEVCouldNotCompute(); // Something strange happened
2867
2868 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00002869 assert(Range.contains(
2870 EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00002871 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00002872 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00002873 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00002874 } else if (isQuadratic()) {
2875 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2876 // quadratic equation to solve it. To do this, we must frame our problem in
2877 // terms of figuring out when zero is crossed, instead of when
2878 // Range.getUpper() is crossed.
2879 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002880 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2881 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +00002882
2883 // Next, solve the constructed addrec
2884 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohmana37eaf22007-10-22 18:31:58 +00002885 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00002886 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2887 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2888 if (R1) {
2889 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002890 if (ConstantInt *CB =
2891 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencer266e42b2006-12-23 06:05:41 +00002892 R1->getValue(), R2->getValue()))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00002893 if (CB->getZExtValue() == false)
Chris Lattnerd934c702004-04-02 20:23:17 +00002894 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00002895
Chris Lattnerd934c702004-04-02 20:23:17 +00002896 // Make sure the root is not off by one. The returned iteration should
2897 // not be in the range, but the previous one should be. When solving
2898 // for "X*X < 5", for example, we should not return a root of 2.
2899 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00002900 R1->getValue(),
2901 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00002902 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002903 // The next iteration must be out of the range...
Dan Gohman0a76e7f2007-07-09 15:25:17 +00002904 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman01808ca2005-04-21 21:13:18 +00002905
Dan Gohmana37eaf22007-10-22 18:31:58 +00002906 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00002907 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00002908 return SE.getConstant(NextVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00002909 return new SCEVCouldNotCompute(); // Something strange happened
2910 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002911
Chris Lattnerd934c702004-04-02 20:23:17 +00002912 // If R1 was not in the range, then it is a good return value. Make
2913 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman0a76e7f2007-07-09 15:25:17 +00002914 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002915 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00002916 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00002917 return R1;
2918 return new SCEVCouldNotCompute(); // Something strange happened
2919 }
2920 }
2921 }
2922
2923 // Fallback, if this is a general polynomial, figure out the progression
2924 // through brute force: evaluate until we find an iteration that fails the
2925 // test. This is likely to be slow, but getting an accurate trip count is
2926 // incredibly important, we will be able to simplify the exit test a lot, and
2927 // we are almost guaranteed to get a trip count in this case.
2928 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002929 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2930 do {
2931 ++NumBruteForceEvaluations;
Dan Gohmana37eaf22007-10-22 18:31:58 +00002932 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00002933 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2934 return new SCEVCouldNotCompute();
2935
2936 // Check to see if we found the value!
Reid Spencer6a440332007-03-01 07:54:15 +00002937 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00002938 return SE.getConstant(TestVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00002939
2940 // Increment to test the next index.
Zhou Shengc0297892007-04-07 17:40:57 +00002941 TestVal = ConstantInt::get(TestVal->getValue()+1);
Chris Lattnerd934c702004-04-02 20:23:17 +00002942 } while (TestVal != EndVal);
Misha Brukman01808ca2005-04-21 21:13:18 +00002943
Chris Lattnerd934c702004-04-02 20:23:17 +00002944 return new SCEVCouldNotCompute();
2945}
2946
2947
2948
2949//===----------------------------------------------------------------------===//
2950// ScalarEvolution Class Implementation
2951//===----------------------------------------------------------------------===//
2952
2953bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmana37eaf22007-10-22 18:31:58 +00002954 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattnerd934c702004-04-02 20:23:17 +00002955 return false;
2956}
2957
2958void ScalarEvolution::releaseMemory() {
2959 delete (ScalarEvolutionsImpl*)Impl;
2960 Impl = 0;
2961}
2962
2963void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2964 AU.setPreservesAll();
Chris Lattnerd934c702004-04-02 20:23:17 +00002965 AU.addRequiredTransitive<LoopInfo>();
2966}
2967
2968SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2969 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2970}
2971
Chris Lattnerb310ac4a2005-08-09 23:36:33 +00002972/// hasSCEV - Return true if the SCEV for this value has already been
2973/// computed.
2974bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner35c0e2e2005-08-10 00:59:40 +00002975 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnerb310ac4a2005-08-09 23:36:33 +00002976}
2977
2978
2979/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2980/// the specified value.
2981void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2982 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2983}
2984
2985
Chris Lattnerd934c702004-04-02 20:23:17 +00002986SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2987 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2988}
2989
2990bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2991 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2992}
2993
2994SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2995 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2996}
2997
Dan Gohman32f53bb2007-06-19 14:28:31 +00002998void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2999 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00003000}
3001
Misha Brukman01808ca2005-04-21 21:13:18 +00003002static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00003003 const Loop *L) {
3004 // Print all inner loops first
3005 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3006 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00003007
Nick Lewyckyd1200b02008-01-02 02:49:20 +00003008 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00003009
Devang Patelb5933bb2007-08-21 00:31:24 +00003010 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00003011 L->getExitBlocks(ExitBlocks);
3012 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00003013 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00003014
3015 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyd1200b02008-01-02 02:49:20 +00003016 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattnerd934c702004-04-02 20:23:17 +00003017 } else {
Nick Lewyckyd1200b02008-01-02 02:49:20 +00003018 OS << "Unpredictable iteration count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00003019 }
3020
Nick Lewyckyd1200b02008-01-02 02:49:20 +00003021 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00003022}
3023
Reid Spencer90839362004-12-07 04:03:45 +00003024void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00003025 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3026 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3027
3028 OS << "Classifying expressions for: " << F.getName() << "\n";
3029 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner03c49532007-01-15 02:27:26 +00003030 if (I->getType()->isInteger()) {
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003031 OS << *I;
Chris Lattnerd934c702004-04-02 20:23:17 +00003032 OS << " --> ";
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003033 SCEVHandle SV = getSCEV(&*I);
Chris Lattnerd934c702004-04-02 20:23:17 +00003034 SV->print(OS);
3035 OS << "\t\t";
Misha Brukman01808ca2005-04-21 21:13:18 +00003036
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003037 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003038 OS << "Exits: ";
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003039 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +00003040 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3041 OS << "<<Unknown>>";
3042 } else {
3043 OS << *ExitValue;
3044 }
3045 }
3046
3047
3048 OS << "\n";
3049 }
3050
3051 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3052 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3053 PrintLoopInfo(OS, this, *I);
3054}