blob: 16dc281ae1792b0951d8ec0cdea10289a71fd4b1 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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.
31//
32// 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//
36// 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
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000076#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077#include "llvm/Support/InstIterator.h"
78#include "llvm/Support/ManagedStatic.h"
79#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084using namespace llvm;
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman089efff2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman089efff2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103char ScalarEvolution::ID = 0;
104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
112SCEV::~SCEV() {}
113void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000114 print(errs());
115 errs() << '\n';
116}
117
118void SCEV::print(std::ostream &o) const {
119 raw_os_ostream OS(o);
120 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121}
122
Dan Gohman7b560c42008-06-18 16:23:07 +0000123bool SCEV::isZero() const {
124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
125 return SC->getValue()->isZero();
126 return false;
127}
128
Dan Gohmanf8bc8e82009-05-18 15:22:39 +0000129bool SCEV::isOne() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isOne();
132 return false;
133}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134
135SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000136SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137
138bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 return false;
141}
142
143const Type *SCEVCouldNotCompute::getType() const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 return 0;
146}
147
148bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 return false;
151}
152
153SCEVHandle SCEVCouldNotCompute::
154replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000155 const SCEVHandle &Conc,
156 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 return this;
158}
159
Dan Gohman13058cc2009-04-21 00:47:46 +0000160void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 OS << "***COULDNOTCOMPUTE***";
162}
163
164bool SCEVCouldNotCompute::classof(const SCEV *S) {
165 return S->getSCEVType() == scCouldNotCompute;
166}
167
168
169// SCEVConstants - Only allow the creation of one SCEVConstant for any
170// particular value. Don't use a SCEVHandle here, or else the object will
171// never be deleted!
172static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
173
174
175SCEVConstant::~SCEVConstant() {
176 SCEVConstants->erase(V);
177}
178
Dan Gohman89f85052007-10-22 18:31:58 +0000179SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 SCEVConstant *&R = (*SCEVConstants)[V];
181 if (R == 0) R = new SCEVConstant(V);
182 return R;
183}
184
Dan Gohman89f85052007-10-22 18:31:58 +0000185SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
186 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187}
188
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189const Type *SCEVConstant::getType() const { return V->getType(); }
190
Dan Gohman13058cc2009-04-21 00:47:46 +0000191void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 WriteAsOperand(OS, V, false);
193}
194
Dan Gohman2a381532009-04-21 01:25:57 +0000195SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
196 const SCEVHandle &op, const Type *ty)
197 : SCEV(SCEVTy), Op(op), Ty(ty) {}
198
199SCEVCastExpr::~SCEVCastExpr() {}
200
201bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
202 return Op->dominates(BB, DT);
203}
204
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
206// particular input. Don't use a SCEVHandle here, or else the object will
207// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000208static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 SCEVTruncateExpr*> > SCEVTruncates;
210
211SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000212 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000213 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
214 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216}
217
218SCEVTruncateExpr::~SCEVTruncateExpr() {
219 SCEVTruncates->erase(std::make_pair(Op, Ty));
220}
221
Dan Gohman13058cc2009-04-21 00:47:46 +0000222void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224}
225
226// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
227// particular input. Don't use a SCEVHandle here, or else the object will never
228// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000229static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 SCEVZeroExtendExpr*> > SCEVZeroExtends;
231
232SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000233 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000234 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
235 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237}
238
239SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
240 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
241}
242
Dan Gohman13058cc2009-04-21 00:47:46 +0000243void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000244 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245}
246
247// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
248// particular input. Don't use a SCEVHandle here, or else the object will never
249// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000250static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 SCEVSignExtendExpr*> > SCEVSignExtends;
252
253SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000254 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000255 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
256 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258}
259
260SCEVSignExtendExpr::~SCEVSignExtendExpr() {
261 SCEVSignExtends->erase(std::make_pair(Op, Ty));
262}
263
Dan Gohman13058cc2009-04-21 00:47:46 +0000264void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000265 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266}
267
268// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
269// particular input. Don't use a SCEVHandle here, or else the object will never
270// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000271static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 SCEVCommutativeExpr*> > SCEVCommExprs;
273
274SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000275 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
276 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277}
278
Dan Gohman13058cc2009-04-21 00:47:46 +0000279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
286}
287
288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 if (H != getOperand(i)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000296 SmallVector<SCEVHandle, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304
305 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000306 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000308 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 else
314 assert(0 && "Unknown commutative expr!");
315 }
316 }
317 return this;
318}
319
Dan Gohman72a8a022009-05-07 14:00:19 +0000320bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
324 }
325 return true;
326}
327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000332static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000333 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337}
338
Evan Cheng98c073b2009-02-17 00:13:06 +0000339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
Dan Gohman13058cc2009-04-21 00:47:46 +0000343void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000344 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345}
346
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000348 // In most cases the types of LHS and RHS will be the same, but in some
349 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
350 // depend on the type for correctness, but handling types carefully can
351 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
352 // a pointer type than the RHS, so use the RHS' type here.
353 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354}
355
356// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
357// particular input. Don't use a SCEVHandle here, or else the object will never
358// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000359static ManagedStatic<std::map<std::pair<const Loop *,
360 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 SCEVAddRecExpr*> > SCEVAddRecExprs;
362
363SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000364 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
365 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366}
367
368SCEVHandle SCEVAddRecExpr::
369replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000370 const SCEVHandle &Conc,
371 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000373 SCEVHandle H =
374 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 if (H != getOperand(i)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000376 SmallVector<SCEVHandle, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 NewOps.reserve(getNumOperands());
378 for (unsigned j = 0; j != i; ++j)
379 NewOps.push_back(getOperand(j));
380 NewOps.push_back(H);
381 for (++i; i != e; ++i)
382 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000383 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384
Dan Gohman89f85052007-10-22 18:31:58 +0000385 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 }
387 }
388 return this;
389}
390
391
392bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
393 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
394 // contain L and if the start is invariant.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000395 // Add recurrences are never invariant in the function-body (null loop).
396 return QueryLoop &&
397 !QueryLoop->contains(L->getHeader()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 getOperand(0)->isLoopInvariant(QueryLoop);
399}
400
401
Dan Gohman13058cc2009-04-21 00:47:46 +0000402void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 OS << "{" << *Operands[0];
404 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
405 OS << ",+," << *Operands[i];
406 OS << "}<" << L->getHeader()->getName() + ">";
407}
408
409// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
410// value. Don't use a SCEVHandle here, or else the object will never be
411// deleted!
412static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
413
414SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
415
416bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
417 // All non-instruction values are loop invariant. All instructions are loop
418 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000419 // Instructions are never considered invariant in the function body
420 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000422 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 return true;
424}
425
Evan Cheng98c073b2009-02-17 00:13:06 +0000426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
430}
431
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432const Type *SCEVUnknown::getType() const {
433 return V->getType();
434}
435
Dan Gohman13058cc2009-04-21 00:47:46 +0000436void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437 WriteAsOperand(OS, V, false);
438}
439
440//===----------------------------------------------------------------------===//
441// SCEV Utilities
442//===----------------------------------------------------------------------===//
443
444namespace {
445 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
446 /// than the complexity of the RHS. This comparator is used to canonicalize
447 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000448 class VISIBILITY_HIDDEN SCEVComplexityCompare {
449 LoopInfo *LI;
450 public:
451 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
452
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000453 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000454 // Primarily, sort the SCEVs by their getSCEVType().
455 if (LHS->getSCEVType() != RHS->getSCEVType())
456 return LHS->getSCEVType() < RHS->getSCEVType();
457
458 // Aside from the getSCEVType() ordering, the particular ordering
459 // isn't very important except that it's beneficial to be consistent,
460 // so that (a + b) and (b + a) don't end up as different expressions.
461
462 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
463 // not as complete as it could be.
464 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
465 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
466
Dan Gohmand0c01232009-05-19 02:15:55 +0000467 // Order pointer values after integer values. This helps SCEVExpander
468 // form GEPs.
469 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
470 return false;
471 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
472 return true;
473
Dan Gohman5d486452009-05-07 14:39:04 +0000474 // Compare getValueID values.
475 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
476 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
477
478 // Sort arguments by their position.
479 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
480 const Argument *RA = cast<Argument>(RU->getValue());
481 return LA->getArgNo() < RA->getArgNo();
482 }
483
484 // For instructions, compare their loop depth, and their opcode.
485 // This is pretty loose.
486 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
487 Instruction *RV = cast<Instruction>(RU->getValue());
488
489 // Compare loop depths.
490 if (LI->getLoopDepth(LV->getParent()) !=
491 LI->getLoopDepth(RV->getParent()))
492 return LI->getLoopDepth(LV->getParent()) <
493 LI->getLoopDepth(RV->getParent());
494
495 // Compare opcodes.
496 if (LV->getOpcode() != RV->getOpcode())
497 return LV->getOpcode() < RV->getOpcode();
498
499 // Compare the number of operands.
500 if (LV->getNumOperands() != RV->getNumOperands())
501 return LV->getNumOperands() < RV->getNumOperands();
502 }
503
504 return false;
505 }
506
Dan Gohman56fc8f12009-06-14 22:51:25 +0000507 // Compare constant values.
508 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
509 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
510 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
511 }
512
513 // Compare addrec loop depths.
514 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
515 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
516 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
517 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
518 }
Dan Gohman5d486452009-05-07 14:39:04 +0000519
520 // Lexicographically compare n-ary expressions.
521 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
522 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
523 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
524 if (i >= RC->getNumOperands())
525 return false;
526 if (operator()(LC->getOperand(i), RC->getOperand(i)))
527 return true;
528 if (operator()(RC->getOperand(i), LC->getOperand(i)))
529 return false;
530 }
531 return LC->getNumOperands() < RC->getNumOperands();
532 }
533
Dan Gohman6e10db12009-05-07 19:23:21 +0000534 // Lexicographically compare udiv expressions.
535 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
536 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
537 if (operator()(LC->getLHS(), RC->getLHS()))
538 return true;
539 if (operator()(RC->getLHS(), LC->getLHS()))
540 return false;
541 if (operator()(LC->getRHS(), RC->getRHS()))
542 return true;
543 if (operator()(RC->getRHS(), LC->getRHS()))
544 return false;
545 return false;
546 }
547
Dan Gohman5d486452009-05-07 14:39:04 +0000548 // Compare cast expressions by operand.
549 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
550 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
551 return operator()(LC->getOperand(), RC->getOperand());
552 }
553
554 assert(0 && "Unknown SCEV kind!");
555 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556 }
557 };
558}
559
560/// GroupByComplexity - Given a list of SCEV objects, order them by their
561/// complexity, and group objects of the same complexity together by value.
562/// When this routine is finished, we know that any duplicates in the vector are
563/// consecutive and that complexity is monotonically increasing.
564///
565/// Note that we go take special precautions to ensure that we get determinstic
566/// results from this routine. In other words, we don't want the results of
567/// this to depend on where the addresses of various SCEV objects happened to
568/// land in memory.
569///
Dan Gohman02ff9392009-06-14 22:47:23 +0000570static void GroupByComplexity(SmallVectorImpl<SCEVHandle> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000571 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572 if (Ops.size() < 2) return; // Noop
573 if (Ops.size() == 2) {
574 // This is the common case, which also happens to be trivially simple.
575 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000576 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 std::swap(Ops[0], Ops[1]);
578 return;
579 }
580
581 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000582 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583
584 // Now that we are sorted by complexity, group elements of the same
585 // complexity. Note that this is, at worst, N^2, but the vector is likely to
586 // be extremely short in practice. Note that we take this approach because we
587 // do not want to depend on the addresses of the objects we are grouping.
588 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000589 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 unsigned Complexity = S->getSCEVType();
591
592 // If there are any objects of the same complexity and same value as this
593 // one, group them.
594 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
595 if (Ops[j] == S) { // Found a duplicate.
596 // Move it to immediately after i'th element.
597 std::swap(Ops[i+1], Ops[j]);
598 ++i; // no need to rescan it.
599 if (i == e-2) return; // Done!
600 }
601 }
602 }
603}
604
605
606
607//===----------------------------------------------------------------------===//
608// Simple SCEV method implementations
609//===----------------------------------------------------------------------===//
610
Eli Friedman7489ec92008-08-04 23:49:06 +0000611/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000612/// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000613static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000614 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000615 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000616 // Handle the simplest case efficiently.
617 if (K == 1)
618 return SE.getTruncateOrZeroExtend(It, ResultTy);
619
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000620 // We are using the following formula for BC(It, K):
621 //
622 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
623 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000624 // Suppose, W is the bitwidth of the return value. We must be prepared for
625 // overflow. Hence, we must assure that the result of our computation is
626 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
627 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000628 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000629 // However, this code doesn't use exactly that formula; the formula it uses
630 // is something like the following, where T is the number of factors of 2 in
631 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
632 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000633 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000634 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000635 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000636 // This formula is trivially equivalent to the previous formula. However,
637 // this formula can be implemented much more efficiently. The trick is that
638 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
639 // arithmetic. To do exact division in modular arithmetic, all we have
640 // to do is multiply by the inverse. Therefore, this step can be done at
641 // width W.
642 //
643 // The next issue is how to safely do the division by 2^T. The way this
644 // is done is by doing the multiplication step at a width of at least W + T
645 // bits. This way, the bottom W+T bits of the product are accurate. Then,
646 // when we perform the division by 2^T (which is equivalent to a right shift
647 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
648 // truncated out after the division by 2^T.
649 //
650 // In comparison to just directly using the first formula, this technique
651 // is much more efficient; using the first formula requires W * K bits,
652 // but this formula less than W + K bits. Also, the first formula requires
653 // a division step, whereas this formula only requires multiplies and shifts.
654 //
655 // It doesn't matter whether the subtraction step is done in the calculation
656 // width or the input iteration count's width; if the subtraction overflows,
657 // the result must be zero anyway. We prefer here to do it in the width of
658 // the induction variable because it helps a lot for certain cases; CodeGen
659 // isn't smart enough to ignore the overflow, which leads to much less
660 // efficient code if the width of the subtraction is wider than the native
661 // register width.
662 //
663 // (It's possible to not widen at all by pulling out factors of 2 before
664 // the multiplication; for example, K=2 can be calculated as
665 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
666 // extra arithmetic, so it's not an obvious win, and it gets
667 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000668
Eli Friedman7489ec92008-08-04 23:49:06 +0000669 // Protection from insane SCEVs; this bound is conservative,
670 // but it probably doesn't matter.
671 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000672 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000673
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000674 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000675
Eli Friedman7489ec92008-08-04 23:49:06 +0000676 // Calculate K! / 2^T and T; we divide out the factors of two before
677 // multiplying for calculating K! / 2^T to avoid overflow.
678 // Other overflow doesn't matter because we only care about the bottom
679 // W bits of the result.
680 APInt OddFactorial(W, 1);
681 unsigned T = 1;
682 for (unsigned i = 3; i <= K; ++i) {
683 APInt Mult(W, i);
684 unsigned TwoFactors = Mult.countTrailingZeros();
685 T += TwoFactors;
686 Mult = Mult.lshr(TwoFactors);
687 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000689
Eli Friedman7489ec92008-08-04 23:49:06 +0000690 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000691 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000692
693 // Calcuate 2^T, at width T+W.
694 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
695
696 // Calculate the multiplicative inverse of K! / 2^T;
697 // this multiplication factor will perform the exact division by
698 // K! / 2^T.
699 APInt Mod = APInt::getSignedMinValue(W+1);
700 APInt MultiplyFactor = OddFactorial.zext(W+1);
701 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
702 MultiplyFactor = MultiplyFactor.trunc(W);
703
704 // Calculate the product, at width T+W
705 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
706 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
707 for (unsigned i = 1; i != K; ++i) {
708 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
709 Dividend = SE.getMulExpr(Dividend,
710 SE.getTruncateOrZeroExtend(S, CalculationTy));
711 }
712
713 // Divide by 2^T
714 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
715
716 // Truncate the result, and divide by K! / 2^T.
717
718 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
719 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720}
721
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722/// evaluateAtIteration - Return the value of this chain of recurrences at
723/// the specified iteration number. We can evaluate this recurrence by
724/// multiplying each element in the chain by the binomial coefficient
725/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
726///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000727/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000729/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730///
Dan Gohman89f85052007-10-22 18:31:58 +0000731SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
732 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000735 // The computation is correct in the face of overflow provided that the
736 // multiplication is performed _after_ the evaluation of the binomial
737 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000738 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000739 if (isa<SCEVCouldNotCompute>(Coeff))
740 return Coeff;
741
742 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 }
744 return Result;
745}
746
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747//===----------------------------------------------------------------------===//
748// SCEV Expression folder implementations
749//===----------------------------------------------------------------------===//
750
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000751SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
752 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000753 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000754 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000755 assert(isSCEVable(Ty) &&
756 "This is not a conversion to a SCEVable type!");
757 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000758
Dan Gohmanc76b5452009-05-04 22:02:23 +0000759 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000760 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 ConstantExpr::getTrunc(SC->getValue(), Ty));
762
Dan Gohman1a5c4992009-04-22 16:20:48 +0000763 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000764 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000765 return getTruncateExpr(ST->getOperand(), Ty);
766
Nick Lewycky37d04642009-04-23 05:15:08 +0000767 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000768 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000769 return getTruncateOrSignExtend(SS->getOperand(), Ty);
770
771 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000772 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000773 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
774
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 // If the input value is a chrec scev made out of constants, truncate
776 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000777 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000778 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000780 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
781 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 }
783
784 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
785 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
786 return Result;
787}
788
Dan Gohman36d40922009-04-16 19:25:55 +0000789SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
790 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000791 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000792 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000793 assert(isSCEVable(Ty) &&
794 "This is not a conversion to a SCEVable type!");
795 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000796
Dan Gohmanc76b5452009-05-04 22:02:23 +0000797 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000798 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000799 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
800 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
801 return getUnknown(C);
802 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803
Dan Gohman1a5c4992009-04-22 16:20:48 +0000804 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000805 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000806 return getZeroExtendExpr(SZ->getOperand(), Ty);
807
Dan Gohmana9dba962009-04-27 20:16:15 +0000808 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000810 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000812 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000813 if (AR->isAffine()) {
814 // Check whether the backedge-taken count is SCEVCouldNotCompute.
815 // Note that this serves two purposes: It filters out loops that are
816 // simply not analyzable, and it covers the case where this code is
817 // being called from within backedge-taken count analysis, such that
818 // attempting to ask for the backedge-taken count would likely result
819 // in infinite recursion. In the later case, the analysis code will
820 // cope with a conservative value, and it will take care to purge
821 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000822 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
823 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000824 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000825 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000826 SCEVHandle Start = AR->getStart();
827 SCEVHandle Step = AR->getStepRecurrence(*this);
828
829 // Check whether the backedge-taken count can be losslessly casted to
830 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000831 SCEVHandle CastedMaxBECount =
832 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000833 SCEVHandle RecastedMaxBECount =
834 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
835 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000836 const Type *WideTy =
837 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000838 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000839 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000840 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000841 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000842 SCEVHandle Add = getAddExpr(Start, ZMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000843 SCEVHandle OperandExtendedAdd =
844 getAddExpr(getZeroExtendExpr(Start, WideTy),
845 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
846 getZeroExtendExpr(Step, WideTy)));
847 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000848 // Return the expression with the addrec on the outside.
849 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
850 getZeroExtendExpr(Step, Ty),
851 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000852
853 // Similar to above, only this time treat the step value as signed.
854 // This covers loops that count down.
855 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000856 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000857 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000858 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000859 OperandExtendedAdd =
860 getAddExpr(getZeroExtendExpr(Start, WideTy),
861 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
862 getSignExtendExpr(Step, WideTy)));
863 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000864 // Return the expression with the addrec on the outside.
865 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
866 getSignExtendExpr(Step, Ty),
867 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000868 }
869 }
870 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871
872 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
873 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
874 return Result;
875}
876
Dan Gohmana9dba962009-04-27 20:16:15 +0000877SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
878 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000879 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000880 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000881 assert(isSCEVable(Ty) &&
882 "This is not a conversion to a SCEVable type!");
883 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000884
Dan Gohmanc76b5452009-05-04 22:02:23 +0000885 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000886 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000887 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
888 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
889 return getUnknown(C);
890 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891
Dan Gohman1a5c4992009-04-22 16:20:48 +0000892 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000893 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000894 return getSignExtendExpr(SS->getOperand(), Ty);
895
Dan Gohmana9dba962009-04-27 20:16:15 +0000896 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000898 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000900 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000901 if (AR->isAffine()) {
902 // Check whether the backedge-taken count is SCEVCouldNotCompute.
903 // Note that this serves two purposes: It filters out loops that are
904 // simply not analyzable, and it covers the case where this code is
905 // being called from within backedge-taken count analysis, such that
906 // attempting to ask for the backedge-taken count would likely result
907 // in infinite recursion. In the later case, the analysis code will
908 // cope with a conservative value, and it will take care to purge
909 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000910 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
911 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000912 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000913 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000914 SCEVHandle Start = AR->getStart();
915 SCEVHandle Step = AR->getStepRecurrence(*this);
916
917 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000918 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000919 SCEVHandle CastedMaxBECount =
920 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000921 SCEVHandle RecastedMaxBECount =
922 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
923 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000924 const Type *WideTy =
925 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000926 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000927 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000928 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000929 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000930 SCEVHandle Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000931 SCEVHandle OperandExtendedAdd =
932 getAddExpr(getSignExtendExpr(Start, WideTy),
933 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
934 getSignExtendExpr(Step, WideTy)));
935 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000936 // Return the expression with the addrec on the outside.
937 return getAddRecExpr(getSignExtendExpr(Start, Ty),
938 getSignExtendExpr(Step, Ty),
939 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000940 }
941 }
942 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943
944 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
945 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
946 return Result;
947}
948
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000949/// getAnyExtendExpr - Return a SCEV for the given operand extended with
950/// unspecified bits out to the given type.
951///
952SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
953 const Type *Ty) {
954 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
955 "This is not an extending conversion!");
956 assert(isSCEVable(Ty) &&
957 "This is not a conversion to a SCEVable type!");
958 Ty = getEffectiveSCEVType(Ty);
959
960 // Sign-extend negative constants.
961 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
962 if (SC->getValue()->getValue().isNegative())
963 return getSignExtendExpr(Op, Ty);
964
965 // Peel off a truncate cast.
966 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
967 SCEVHandle NewOp = T->getOperand();
968 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
969 return getAnyExtendExpr(NewOp, Ty);
970 return getTruncateOrNoop(NewOp, Ty);
971 }
972
973 // Next try a zext cast. If the cast is folded, use it.
974 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
975 if (!isa<SCEVZeroExtendExpr>(ZExt))
976 return ZExt;
977
978 // Next try a sext cast. If the cast is folded, use it.
979 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
980 if (!isa<SCEVSignExtendExpr>(SExt))
981 return SExt;
982
983 // If the expression is obviously signed, use the sext cast value.
984 if (isa<SCEVSMaxExpr>(Op))
985 return SExt;
986
987 // Absent any other information, use the zext cast value.
988 return ZExt;
989}
990
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000991/// CollectAddOperandsWithScales - Process the given Ops list, which is
992/// a list of operands to be added under the given scale, update the given
993/// map. This is a helper function for getAddRecExpr. As an example of
994/// what it does, given a sequence of operands that would form an add
995/// expression like this:
996///
997/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
998///
999/// where A and B are constants, update the map with these values:
1000///
1001/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1002///
1003/// and add 13 + A*B*29 to AccumulatedConstant.
1004/// This will allow getAddRecExpr to produce this:
1005///
1006/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1007///
1008/// This form often exposes folding opportunities that are hidden in
1009/// the original operand list.
1010///
1011/// Return true iff it appears that any interesting folding opportunities
1012/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1013/// the common case where no interesting opportunities are present, and
1014/// is also used as a check to avoid infinite recursion.
1015///
1016static bool
1017CollectAddOperandsWithScales(DenseMap<SCEVHandle, APInt> &M,
1018 SmallVector<SCEVHandle, 8> &NewOps,
1019 APInt &AccumulatedConstant,
1020 const SmallVectorImpl<SCEVHandle> &Ops,
1021 const APInt &Scale,
1022 ScalarEvolution &SE) {
1023 bool Interesting = false;
1024
1025 // Iterate over the add operands.
1026 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1027 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1028 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1029 APInt NewScale =
1030 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1031 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1032 // A multiplication of a constant with another add; recurse.
1033 Interesting |=
1034 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1035 cast<SCEVAddExpr>(Mul->getOperand(1))
1036 ->getOperands(),
1037 NewScale, SE);
1038 } else {
1039 // A multiplication of a constant with some other value. Update
1040 // the map.
1041 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1042 SCEVHandle Key = SE.getMulExpr(MulOps);
1043 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1044 M.insert(std::make_pair(Key, APInt()));
1045 if (Pair.second) {
1046 Pair.first->second = NewScale;
1047 NewOps.push_back(Pair.first->first);
1048 } else {
1049 Pair.first->second += NewScale;
1050 // The map already had an entry for this value, which may indicate
1051 // a folding opportunity.
1052 Interesting = true;
1053 }
1054 }
1055 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1056 // Pull a buried constant out to the outside.
1057 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1058 Interesting = true;
1059 AccumulatedConstant += Scale * C->getValue()->getValue();
1060 } else {
1061 // An ordinary operand. Update the map.
1062 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1063 M.insert(std::make_pair(Ops[i], APInt()));
1064 if (Pair.second) {
1065 Pair.first->second = Scale;
1066 NewOps.push_back(Pair.first->first);
1067 } else {
1068 Pair.first->second += Scale;
1069 // The map already had an entry for this value, which may indicate
1070 // a folding opportunity.
1071 Interesting = true;
1072 }
1073 }
1074 }
1075
1076 return Interesting;
1077}
1078
1079namespace {
1080 struct APIntCompare {
1081 bool operator()(const APInt &LHS, const APInt &RHS) const {
1082 return LHS.ult(RHS);
1083 }
1084 };
1085}
1086
Dan Gohmanc8a29272009-05-24 23:45:28 +00001087/// getAddExpr - Get a canonical add expression, or something simpler if
1088/// possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001089SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090 assert(!Ops.empty() && "Cannot get empty add!");
1091 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001092#ifndef NDEBUG
1093 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1094 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1095 getEffectiveSCEVType(Ops[0]->getType()) &&
1096 "SCEVAddExpr operand types don't match!");
1097#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098
1099 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001100 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101
1102 // If there are any constants, fold them together.
1103 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001104 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 ++Idx;
1106 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001107 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001109 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1110 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001111 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001112 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001113 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 }
1115
1116 // If we are left with a constant zero being added, strip it off.
1117 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1118 Ops.erase(Ops.begin());
1119 --Idx;
1120 }
1121 }
1122
1123 if (Ops.size() == 1) return Ops[0];
1124
1125 // Okay, check to see if the same value occurs in the operand list twice. If
1126 // so, merge them together into an multiply expression. Since we sorted the
1127 // list, these values are required to be adjacent.
1128 const Type *Ty = Ops[0]->getType();
1129 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1130 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1131 // Found a match, merge the two values into a multiply, and add any
1132 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +00001133 SCEVHandle Two = getIntegerSCEV(2, Ty);
1134 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 if (Ops.size() == 2)
1136 return Mul;
1137 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1138 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001139 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 }
1141
Dan Gohman45b3b542009-05-08 21:03:19 +00001142 // Check for truncates. If all the operands are truncated from the same
1143 // type, see if factoring out the truncate would permit the result to be
1144 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1145 // if the contents of the resulting outer trunc fold to something simple.
1146 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1147 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1148 const Type *DstType = Trunc->getType();
1149 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman02ff9392009-06-14 22:47:23 +00001150 SmallVector<SCEVHandle, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001151 bool Ok = true;
1152 // Check all the operands to see if they can be represented in the
1153 // source type of the truncate.
1154 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1155 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1156 if (T->getOperand()->getType() != SrcType) {
1157 Ok = false;
1158 break;
1159 }
1160 LargeOps.push_back(T->getOperand());
1161 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1162 // This could be either sign or zero extension, but sign extension
1163 // is much more likely to be foldable here.
1164 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1165 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001166 SmallVector<SCEVHandle, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001167 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1168 if (const SCEVTruncateExpr *T =
1169 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1170 if (T->getOperand()->getType() != SrcType) {
1171 Ok = false;
1172 break;
1173 }
1174 LargeMulOps.push_back(T->getOperand());
1175 } else if (const SCEVConstant *C =
1176 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1177 // This could be either sign or zero extension, but sign extension
1178 // is much more likely to be foldable here.
1179 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1180 } else {
1181 Ok = false;
1182 break;
1183 }
1184 }
1185 if (Ok)
1186 LargeOps.push_back(getMulExpr(LargeMulOps));
1187 } else {
1188 Ok = false;
1189 break;
1190 }
1191 }
1192 if (Ok) {
1193 // Evaluate the expression in the larger type.
1194 SCEVHandle Fold = getAddExpr(LargeOps);
1195 // If it folds to something simple, use it. Otherwise, don't.
1196 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1197 return getTruncateExpr(Fold, DstType);
1198 }
1199 }
1200
1201 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1203 ++Idx;
1204
1205 // If there are add operands they would be next.
1206 if (Idx < Ops.size()) {
1207 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001208 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 // If we have an add, expand the add operands onto the end of the operands
1210 // list.
1211 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1212 Ops.erase(Ops.begin()+Idx);
1213 DeletedAdd = true;
1214 }
1215
1216 // If we deleted at least one add, we added operands to the end of the list,
1217 // and they are not necessarily sorted. Recurse to resort and resimplify
1218 // any operands we just aquired.
1219 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001220 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221 }
1222
1223 // Skip over the add expression until we get to a multiply.
1224 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1225 ++Idx;
1226
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001227 // Check to see if there are any folding opportunities present with
1228 // operands multiplied by constant values.
1229 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1230 uint64_t BitWidth = getTypeSizeInBits(Ty);
1231 DenseMap<SCEVHandle, APInt> M;
1232 SmallVector<SCEVHandle, 8> NewOps;
1233 APInt AccumulatedConstant(BitWidth, 0);
1234 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1235 Ops, APInt(BitWidth, 1), *this)) {
1236 // Some interesting folding opportunity is present, so its worthwhile to
1237 // re-generate the operands list. Group the operands by constant scale,
1238 // to avoid multiplying by the same constant scale multiple times.
1239 std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare> MulOpLists;
1240 for (SmallVector<SCEVHandle, 8>::iterator I = NewOps.begin(),
1241 E = NewOps.end(); I != E; ++I)
1242 MulOpLists[M.find(*I)->second].push_back(*I);
1243 // Re-generate the operands list.
1244 Ops.clear();
1245 if (AccumulatedConstant != 0)
1246 Ops.push_back(getConstant(AccumulatedConstant));
1247 for (std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare>::iterator I =
1248 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1249 if (I->first != 0)
1250 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1251 if (Ops.empty())
1252 return getIntegerSCEV(0, Ty);
1253 if (Ops.size() == 1)
1254 return Ops[0];
1255 return getAddExpr(Ops);
1256 }
1257 }
1258
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 // If we are adding something to a multiply expression, make sure the
1260 // something is not already an operand of the multiply. If so, merge it into
1261 // the multiply.
1262 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001263 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001265 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001267 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1269 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1270 if (Mul->getNumOperands() != 2) {
1271 // If the multiply has more than two operands, we must get the
1272 // Y*Z term.
Dan Gohman02ff9392009-06-14 22:47:23 +00001273 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001275 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 }
Dan Gohman89f85052007-10-22 18:31:58 +00001277 SCEVHandle One = getIntegerSCEV(1, Ty);
1278 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1279 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 if (Ops.size() == 2) return OuterMul;
1281 if (AddOp < Idx) {
1282 Ops.erase(Ops.begin()+AddOp);
1283 Ops.erase(Ops.begin()+Idx-1);
1284 } else {
1285 Ops.erase(Ops.begin()+Idx);
1286 Ops.erase(Ops.begin()+AddOp-1);
1287 }
1288 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001289 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 }
1291
1292 // Check this multiply against other multiplies being added together.
1293 for (unsigned OtherMulIdx = Idx+1;
1294 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1295 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001296 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 // If MulOp occurs in OtherMul, we can fold the two multiplies
1298 // together.
1299 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1300 OMulOp != e; ++OMulOp)
1301 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1302 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1303 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1304 if (Mul->getNumOperands() != 2) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001305 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001307 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308 }
1309 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1310 if (OtherMul->getNumOperands() != 2) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001311 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 OtherMul->op_end());
1313 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001314 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 }
Dan Gohman89f85052007-10-22 18:31:58 +00001316 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1317 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 if (Ops.size() == 2) return OuterMul;
1319 Ops.erase(Ops.begin()+Idx);
1320 Ops.erase(Ops.begin()+OtherMulIdx-1);
1321 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001322 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 }
1324 }
1325 }
1326 }
1327
1328 // If there are any add recurrences in the operands list, see if any other
1329 // added values are loop invariant. If so, we can fold them into the
1330 // recurrence.
1331 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1332 ++Idx;
1333
1334 // Scan over all recurrences, trying to fold loop invariants into them.
1335 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1336 // Scan all of the other operands to this add and add them to the vector if
1337 // they are loop invariant w.r.t. the recurrence.
Dan Gohman02ff9392009-06-14 22:47:23 +00001338 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001339 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1341 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1342 LIOps.push_back(Ops[i]);
1343 Ops.erase(Ops.begin()+i);
1344 --i; --e;
1345 }
1346
1347 // If we found some loop invariants, fold them into the recurrence.
1348 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001349 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 LIOps.push_back(AddRec->getStart());
1351
Dan Gohman02ff9392009-06-14 22:47:23 +00001352 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1353 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001354 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355
Dan Gohman89f85052007-10-22 18:31:58 +00001356 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 // If all of the other operands were loop invariant, we are done.
1358 if (Ops.size() == 1) return NewRec;
1359
1360 // Otherwise, add the folded AddRec by the non-liv parts.
1361 for (unsigned i = 0;; ++i)
1362 if (Ops[i] == AddRec) {
1363 Ops[i] = NewRec;
1364 break;
1365 }
Dan Gohman89f85052007-10-22 18:31:58 +00001366 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367 }
1368
1369 // Okay, if there weren't any loop invariants to be folded, check to see if
1370 // there are multiple AddRec's with the same loop induction variable being
1371 // added together. If so, we can fold them.
1372 for (unsigned OtherIdx = Idx+1;
1373 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1374 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001375 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1377 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman02ff9392009-06-14 22:47:23 +00001378 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1380 if (i >= NewOps.size()) {
1381 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1382 OtherAddRec->op_end());
1383 break;
1384 }
Dan Gohman89f85052007-10-22 18:31:58 +00001385 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 }
Dan Gohman89f85052007-10-22 18:31:58 +00001387 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388
1389 if (Ops.size() == 2) return NewAddRec;
1390
1391 Ops.erase(Ops.begin()+Idx);
1392 Ops.erase(Ops.begin()+OtherIdx-1);
1393 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001394 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001395 }
1396 }
1397
1398 // Otherwise couldn't fold anything into this recurrence. Move onto the
1399 // next one.
1400 }
1401
1402 // Okay, it looks like we really DO need an add expr. Check to see if we
1403 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001404 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1406 SCEVOps)];
1407 if (Result == 0) Result = new SCEVAddExpr(Ops);
1408 return Result;
1409}
1410
1411
Dan Gohmanc8a29272009-05-24 23:45:28 +00001412/// getMulExpr - Get a canonical multiply expression, or something simpler if
1413/// possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001414SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001416#ifndef NDEBUG
1417 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1418 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1419 getEffectiveSCEVType(Ops[0]->getType()) &&
1420 "SCEVMulExpr operand types don't match!");
1421#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422
1423 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001424 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425
1426 // If there are any constants, fold them together.
1427 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001428 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429
1430 // C1*(C2+V) -> C1*C2 + C1*V
1431 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001432 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 if (Add->getNumOperands() == 2 &&
1434 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001435 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1436 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437
1438
1439 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001440 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001441 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001442 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1443 RHSC->getValue()->getValue());
1444 Ops[0] = getConstant(Fold);
1445 Ops.erase(Ops.begin()+1); // Erase the folded element
1446 if (Ops.size() == 1) return Ops[0];
1447 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 }
1449
1450 // If we are left with a constant one being multiplied, strip it off.
1451 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1452 Ops.erase(Ops.begin());
1453 --Idx;
1454 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1455 // If we have a multiply of zero, it will always be zero.
1456 return Ops[0];
1457 }
1458 }
1459
1460 // Skip over the add expression until we get to a multiply.
1461 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1462 ++Idx;
1463
1464 if (Ops.size() == 1)
1465 return Ops[0];
1466
1467 // If there are mul operands inline them all into this expression.
1468 if (Idx < Ops.size()) {
1469 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001470 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 // If we have an mul, expand the mul operands onto the end of the operands
1472 // list.
1473 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1474 Ops.erase(Ops.begin()+Idx);
1475 DeletedMul = true;
1476 }
1477
1478 // If we deleted at least one mul, we added operands to the end of the list,
1479 // and they are not necessarily sorted. Recurse to resort and resimplify
1480 // any operands we just aquired.
1481 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001482 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483 }
1484
1485 // If there are any add recurrences in the operands list, see if any other
1486 // added values are loop invariant. If so, we can fold them into the
1487 // recurrence.
1488 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1489 ++Idx;
1490
1491 // Scan over all recurrences, trying to fold loop invariants into them.
1492 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1493 // Scan all of the other operands to this mul and add them to the vector if
1494 // they are loop invariant w.r.t. the recurrence.
Dan Gohman02ff9392009-06-14 22:47:23 +00001495 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001496 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001497 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1498 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1499 LIOps.push_back(Ops[i]);
1500 Ops.erase(Ops.begin()+i);
1501 --i; --e;
1502 }
1503
1504 // If we found some loop invariants, fold them into the recurrence.
1505 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001506 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman02ff9392009-06-14 22:47:23 +00001507 SmallVector<SCEVHandle, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001508 NewOps.reserve(AddRec->getNumOperands());
1509 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001510 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001511 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001512 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 } else {
1514 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001515 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001517 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518 }
1519 }
1520
Dan Gohman89f85052007-10-22 18:31:58 +00001521 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522
1523 // If all of the other operands were loop invariant, we are done.
1524 if (Ops.size() == 1) return NewRec;
1525
1526 // Otherwise, multiply the folded AddRec by the non-liv parts.
1527 for (unsigned i = 0;; ++i)
1528 if (Ops[i] == AddRec) {
1529 Ops[i] = NewRec;
1530 break;
1531 }
Dan Gohman89f85052007-10-22 18:31:58 +00001532 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 }
1534
1535 // Okay, if there weren't any loop invariants to be folded, check to see if
1536 // there are multiple AddRec's with the same loop induction variable being
1537 // multiplied together. If so, we can fold them.
1538 for (unsigned OtherIdx = Idx+1;
1539 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1540 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001541 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1543 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001544 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001545 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001547 SCEVHandle B = F->getStepRecurrence(*this);
1548 SCEVHandle D = G->getStepRecurrence(*this);
1549 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1550 getMulExpr(G, B),
1551 getMulExpr(B, D));
1552 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1553 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554 if (Ops.size() == 2) return NewAddRec;
1555
1556 Ops.erase(Ops.begin()+Idx);
1557 Ops.erase(Ops.begin()+OtherIdx-1);
1558 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001559 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 }
1561 }
1562
1563 // Otherwise couldn't fold anything into this recurrence. Move onto the
1564 // next one.
1565 }
1566
1567 // Okay, it looks like we really DO need an mul expr. Check to see if we
1568 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001569 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001570 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1571 SCEVOps)];
1572 if (Result == 0)
1573 Result = new SCEVMulExpr(Ops);
1574 return Result;
1575}
1576
Dan Gohmanc8a29272009-05-24 23:45:28 +00001577/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1578/// possible.
Dan Gohman77841cd2009-05-04 22:23:18 +00001579SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1580 const SCEVHandle &RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001581 assert(getEffectiveSCEVType(LHS->getType()) ==
1582 getEffectiveSCEVType(RHS->getType()) &&
1583 "SCEVUDivExpr operand types don't match!");
1584
Dan Gohmanc76b5452009-05-04 22:02:23 +00001585 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001586 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001587 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001588 if (RHSC->isZero())
1589 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001590
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001591 // Determine if the division can be folded into the operands of
1592 // its operands.
1593 // TODO: Generalize this to non-constants by using known-bits information.
1594 const Type *Ty = LHS->getType();
1595 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1596 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1597 // For non-power-of-two values, effectively round the value up to the
1598 // nearest power of two.
1599 if (!RHSC->getValue()->getValue().isPowerOf2())
1600 ++MaxShiftAmt;
1601 const IntegerType *ExtTy =
1602 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1603 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1604 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1605 if (const SCEVConstant *Step =
1606 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1607 if (!Step->getValue()->getValue()
1608 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001609 getZeroExtendExpr(AR, ExtTy) ==
1610 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1611 getZeroExtendExpr(Step, ExtTy),
1612 AR->getLoop())) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001613 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001614 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1615 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1616 return getAddRecExpr(Operands, AR->getLoop());
1617 }
1618 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001619 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001620 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001621 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1622 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1623 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001624 // Find an operand that's safely divisible.
1625 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1626 SCEVHandle Op = M->getOperand(i);
1627 SCEVHandle Div = getUDivExpr(Op, RHSC);
1628 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001629 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1630 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1631 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001632 Operands[i] = Div;
1633 return getMulExpr(Operands);
1634 }
1635 }
Dan Gohman14374d32009-05-08 23:11:16 +00001636 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001637 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001638 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001639 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001640 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1641 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1642 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1643 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001644 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1645 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1646 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1647 break;
1648 Operands.push_back(Op);
1649 }
1650 if (Operands.size() == A->getNumOperands())
1651 return getAddExpr(Operands);
1652 }
Dan Gohman14374d32009-05-08 23:11:16 +00001653 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001654
1655 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001656 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 Constant *LHSCV = LHSC->getValue();
1658 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001659 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 }
1661 }
1662
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001663 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1664 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001665 return Result;
1666}
1667
1668
Dan Gohmanc8a29272009-05-24 23:45:28 +00001669/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1670/// Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001671SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001672 const SCEVHandle &Step, const Loop *L) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001673 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001675 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676 if (StepChrec->getLoop() == L) {
1677 Operands.insert(Operands.end(), StepChrec->op_begin(),
1678 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001679 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 }
1681
1682 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001683 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001684}
1685
Dan Gohmanc8a29272009-05-24 23:45:28 +00001686/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1687/// Simplify the expression as much as possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001688SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001689 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001691#ifndef NDEBUG
1692 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1693 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1694 getEffectiveSCEVType(Operands[0]->getType()) &&
1695 "SCEVAddRecExpr operand types don't match!");
1696#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697
Dan Gohman7b560c42008-06-18 16:23:07 +00001698 if (Operands.back()->isZero()) {
1699 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001700 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001701 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702
Dan Gohman42936882008-08-08 18:33:12 +00001703 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001704 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001705 const Loop* NestedLoop = NestedAR->getLoop();
1706 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001707 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1708 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001709 SCEVHandle NestedARHandle(NestedAR);
1710 Operands[0] = NestedAR->getStart();
1711 NestedOperands[0] = getAddRecExpr(Operands, L);
1712 return getAddRecExpr(NestedOperands, NestedLoop);
1713 }
1714 }
1715
Dan Gohmanbff6b582009-05-04 22:30:44 +00001716 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1717 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001718 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1719 return Result;
1720}
1721
Nick Lewycky711640a2007-11-25 22:41:31 +00001722SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1723 const SCEVHandle &RHS) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001724 SmallVector<SCEVHandle, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001725 Ops.push_back(LHS);
1726 Ops.push_back(RHS);
1727 return getSMaxExpr(Ops);
1728}
1729
Dan Gohman02ff9392009-06-14 22:47:23 +00001730SCEVHandle
1731ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001732 assert(!Ops.empty() && "Cannot get empty smax!");
1733 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001734#ifndef NDEBUG
1735 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1736 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1737 getEffectiveSCEVType(Ops[0]->getType()) &&
1738 "SCEVSMaxExpr operand types don't match!");
1739#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001740
1741 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001742 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001743
1744 // If there are any constants, fold them together.
1745 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001746 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001747 ++Idx;
1748 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001749 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001750 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001751 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001752 APIntOps::smax(LHSC->getValue()->getValue(),
1753 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001754 Ops[0] = getConstant(Fold);
1755 Ops.erase(Ops.begin()+1); // Erase the folded element
1756 if (Ops.size() == 1) return Ops[0];
1757 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001758 }
1759
1760 // If we are left with a constant -inf, strip it off.
1761 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1762 Ops.erase(Ops.begin());
1763 --Idx;
1764 }
1765 }
1766
1767 if (Ops.size() == 1) return Ops[0];
1768
1769 // Find the first SMax
1770 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1771 ++Idx;
1772
1773 // Check to see if one of the operands is an SMax. If so, expand its operands
1774 // onto our operand list, and recurse to simplify.
1775 if (Idx < Ops.size()) {
1776 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001777 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001778 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1779 Ops.erase(Ops.begin()+Idx);
1780 DeletedSMax = true;
1781 }
1782
1783 if (DeletedSMax)
1784 return getSMaxExpr(Ops);
1785 }
1786
1787 // Okay, check to see if the same value occurs in the operand list twice. If
1788 // so, delete one. Since we sorted the list, these values are required to
1789 // be adjacent.
1790 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1791 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1792 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1793 --i; --e;
1794 }
1795
1796 if (Ops.size() == 1) return Ops[0];
1797
1798 assert(!Ops.empty() && "Reduced smax down to nothing!");
1799
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001800 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001801 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001802 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001803 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1804 SCEVOps)];
1805 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1806 return Result;
1807}
1808
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001809SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1810 const SCEVHandle &RHS) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001811 SmallVector<SCEVHandle, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001812 Ops.push_back(LHS);
1813 Ops.push_back(RHS);
1814 return getUMaxExpr(Ops);
1815}
1816
Dan Gohman02ff9392009-06-14 22:47:23 +00001817SCEVHandle
1818ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001819 assert(!Ops.empty() && "Cannot get empty umax!");
1820 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001821#ifndef NDEBUG
1822 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1823 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1824 getEffectiveSCEVType(Ops[0]->getType()) &&
1825 "SCEVUMaxExpr operand types don't match!");
1826#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001827
1828 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001829 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001830
1831 // If there are any constants, fold them together.
1832 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001833 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001834 ++Idx;
1835 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001836 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001837 // We found two constants, fold them together!
1838 ConstantInt *Fold = ConstantInt::get(
1839 APIntOps::umax(LHSC->getValue()->getValue(),
1840 RHSC->getValue()->getValue()));
1841 Ops[0] = getConstant(Fold);
1842 Ops.erase(Ops.begin()+1); // Erase the folded element
1843 if (Ops.size() == 1) return Ops[0];
1844 LHSC = cast<SCEVConstant>(Ops[0]);
1845 }
1846
1847 // If we are left with a constant zero, strip it off.
1848 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1849 Ops.erase(Ops.begin());
1850 --Idx;
1851 }
1852 }
1853
1854 if (Ops.size() == 1) return Ops[0];
1855
1856 // Find the first UMax
1857 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1858 ++Idx;
1859
1860 // Check to see if one of the operands is a UMax. If so, expand its operands
1861 // onto our operand list, and recurse to simplify.
1862 if (Idx < Ops.size()) {
1863 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001864 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001865 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1866 Ops.erase(Ops.begin()+Idx);
1867 DeletedUMax = true;
1868 }
1869
1870 if (DeletedUMax)
1871 return getUMaxExpr(Ops);
1872 }
1873
1874 // Okay, check to see if the same value occurs in the operand list twice. If
1875 // so, delete one. Since we sorted the list, these values are required to
1876 // be adjacent.
1877 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1878 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1879 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1880 --i; --e;
1881 }
1882
1883 if (Ops.size() == 1) return Ops[0];
1884
1885 assert(!Ops.empty() && "Reduced umax down to nothing!");
1886
1887 // Okay, it looks like we really DO need a umax expr. Check to see if we
1888 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001889 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001890 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1891 SCEVOps)];
1892 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1893 return Result;
1894}
1895
Dan Gohman89f85052007-10-22 18:31:58 +00001896SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001897 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001898 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001899 if (isa<ConstantPointerNull>(V))
1900 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1902 if (Result == 0) Result = new SCEVUnknown(V);
1903 return Result;
1904}
1905
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907// Basic SCEV Analysis and PHI Idiom Recognition Code
1908//
1909
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001910/// isSCEVable - Test if values of the given type are analyzable within
1911/// the SCEV framework. This primarily includes integer types, and it
1912/// can optionally include pointer types if the ScalarEvolution class
1913/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001914bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001915 // Integers are always SCEVable.
1916 if (Ty->isInteger())
1917 return true;
1918
1919 // Pointers are SCEVable if TargetData information is available
1920 // to provide pointer size information.
1921 if (isa<PointerType>(Ty))
1922 return TD != NULL;
1923
1924 // Otherwise it's not SCEVable.
1925 return false;
1926}
1927
1928/// getTypeSizeInBits - Return the size in bits of the specified type,
1929/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001930uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001931 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1932
1933 // If we have a TargetData, use it!
1934 if (TD)
1935 return TD->getTypeSizeInBits(Ty);
1936
1937 // Otherwise, we support only integer types.
1938 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1939 return Ty->getPrimitiveSizeInBits();
1940}
1941
1942/// getEffectiveSCEVType - Return a type with the same bitwidth as
1943/// the given type and which represents how SCEV will treat the given
1944/// type, for which isSCEVable must return true. For pointer types,
1945/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001946const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001947 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1948
1949 if (Ty->isInteger())
1950 return Ty;
1951
1952 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1953 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001954}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001955
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001956SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001957 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001958}
1959
Dan Gohmand83d4af2009-05-04 22:20:30 +00001960/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001961/// computed.
1962bool ScalarEvolution::hasSCEV(Value *V) const {
1963 return Scalars.count(V);
1964}
1965
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001966/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1967/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001968SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001969 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001970
Dan Gohmanbff6b582009-05-04 22:30:44 +00001971 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001972 if (I != Scalars.end()) return I->second;
1973 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001974 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001975 return S;
1976}
1977
Dan Gohman01c2ee72009-04-16 03:18:22 +00001978/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1979/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001980SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1981 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001982 Constant *C;
1983 if (Val == 0)
1984 C = Constant::getNullValue(Ty);
1985 else if (Ty->isFloatingPoint())
1986 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1987 APFloat::IEEEdouble, Val));
1988 else
1989 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001990 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001991}
1992
1993/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1994///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001995SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001996 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001997 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001998
1999 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002000 Ty = getEffectiveSCEVType(Ty);
2001 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002002}
2003
2004/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002005SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002006 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002007 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002008
2009 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002010 Ty = getEffectiveSCEVType(Ty);
2011 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002012 return getMinusSCEV(AllOnes, V);
2013}
2014
2015/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2016///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002017SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00002018 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002019 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002020 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002021}
2022
2023/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2024/// input value to the specified type. If the type must be extended, it is zero
2025/// extended.
2026SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002027ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002028 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002029 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002030 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2031 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002032 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002033 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002034 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002035 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002036 return getTruncateExpr(V, Ty);
2037 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002038}
2039
2040/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2041/// input value to the specified type. If the type must be extended, it is sign
2042/// extended.
2043SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002044ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002045 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002046 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002047 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2048 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002049 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002050 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002051 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002052 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002053 return getTruncateExpr(V, Ty);
2054 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002055}
2056
Dan Gohmanac959332009-05-13 03:46:30 +00002057/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2058/// input value to the specified type. If the type must be extended, it is zero
2059/// extended. The conversion must not be narrowing.
2060SCEVHandle
2061ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
2062 const Type *SrcTy = V->getType();
2063 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2064 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2065 "Cannot noop or zero extend with non-integer arguments!");
2066 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2067 "getNoopOrZeroExtend cannot truncate!");
2068 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2069 return V; // No conversion
2070 return getZeroExtendExpr(V, Ty);
2071}
2072
2073/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2074/// input value to the specified type. If the type must be extended, it is sign
2075/// extended. The conversion must not be narrowing.
2076SCEVHandle
2077ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
2078 const Type *SrcTy = V->getType();
2079 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2080 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2081 "Cannot noop or sign extend with non-integer arguments!");
2082 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2083 "getNoopOrSignExtend cannot truncate!");
2084 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2085 return V; // No conversion
2086 return getSignExtendExpr(V, Ty);
2087}
2088
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002089/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2090/// the input value to the specified type. If the type must be extended,
2091/// it is extended with unspecified bits. The conversion must not be
2092/// narrowing.
2093SCEVHandle
2094ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
2095 const Type *SrcTy = V->getType();
2096 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2097 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2098 "Cannot noop or any extend with non-integer arguments!");
2099 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2100 "getNoopOrAnyExtend cannot truncate!");
2101 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2102 return V; // No conversion
2103 return getAnyExtendExpr(V, Ty);
2104}
2105
Dan Gohmanac959332009-05-13 03:46:30 +00002106/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2107/// input value to the specified type. The conversion must not be widening.
2108SCEVHandle
2109ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
2110 const Type *SrcTy = V->getType();
2111 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2112 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2113 "Cannot truncate or noop with non-integer arguments!");
2114 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2115 "getTruncateOrNoop cannot extend!");
2116 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2117 return V; // No conversion
2118 return getTruncateExpr(V, Ty);
2119}
2120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002121/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2122/// the specified instruction and replaces any references to the symbolic value
2123/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002124void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
2126 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002127 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2128 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 if (SI == Scalars.end()) return;
2130
2131 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002132 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002133 if (NV == SI->second) return; // No change.
2134
2135 SI->second = NV; // Update the scalars map!
2136
2137 // Any instruction values that use this instruction might also need to be
2138 // updated!
2139 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2140 UI != E; ++UI)
2141 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2142}
2143
2144/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2145/// a loop header, making it a potential recurrence, or it doesn't.
2146///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002147SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002148 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002149 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002150 if (L->getHeader() == PN->getParent()) {
2151 // If it lives in the loop header, it has two incoming values, one
2152 // from outside the loop, and one from inside.
2153 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2154 unsigned BackEdge = IncomingEdge^1;
2155
2156 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002157 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002158 assert(Scalars.find(PN) == Scalars.end() &&
2159 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002160 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161
2162 // Using this symbolic name for the PHI, analyze the value coming around
2163 // the back-edge.
2164 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2165
2166 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2167 // has a special value for the first iteration of the loop.
2168
2169 // If the value coming around the backedge is an add with the symbolic
2170 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002171 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172 // If there is a single occurrence of the symbolic value, replace it
2173 // with a recurrence.
2174 unsigned FoundIndex = Add->getNumOperands();
2175 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2176 if (Add->getOperand(i) == SymbolicName)
2177 if (FoundIndex == e) {
2178 FoundIndex = i;
2179 break;
2180 }
2181
2182 if (FoundIndex != Add->getNumOperands()) {
2183 // Create an add with everything but the specified operand.
Dan Gohman02ff9392009-06-14 22:47:23 +00002184 SmallVector<SCEVHandle, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002185 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2186 if (i != FoundIndex)
2187 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002188 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189
2190 // This is not a valid addrec if the step amount is varying each
2191 // loop iteration, but is not itself an addrec in this loop.
2192 if (Accum->isLoopInvariant(L) ||
2193 (isa<SCEVAddRecExpr>(Accum) &&
2194 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2195 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002196 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002197
2198 // Okay, for the entire analysis of this edge we assumed the PHI
2199 // to be symbolic. We now need to go back and update all of the
2200 // entries for the scalars that use the PHI (except for the PHI
2201 // itself) to use the new analyzed value instead of the "symbolic"
2202 // value.
2203 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2204 return PHISCEV;
2205 }
2206 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002207 } else if (const SCEVAddRecExpr *AddRec =
2208 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209 // Otherwise, this could be a loop like this:
2210 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2211 // In this case, j = {1,+,1} and BEValue is j.
2212 // Because the other in-value of i (0) fits the evolution of BEValue
2213 // i really is an addrec evolution.
2214 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2215 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2216
2217 // If StartVal = j.start - j.stride, we can use StartVal as the
2218 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002219 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002220 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002222 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002223
2224 // Okay, for the entire analysis of this edge we assumed the PHI
2225 // to be symbolic. We now need to go back and update all of the
2226 // entries for the scalars that use the PHI (except for the PHI
2227 // itself) to use the new analyzed value instead of the "symbolic"
2228 // value.
2229 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2230 return PHISCEV;
2231 }
2232 }
2233 }
2234
2235 return SymbolicName;
2236 }
2237
2238 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002239 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240}
2241
Dan Gohman509cf4d2009-05-08 20:26:55 +00002242/// createNodeForGEP - Expand GEP instructions into add and multiply
2243/// operations. This allows them to be analyzed by regular SCEV code.
2244///
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002245SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002246
2247 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002248 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002249 // Don't attempt to analyze GEPs over unsized objects.
2250 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2251 return getUnknown(GEP);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002252 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002253 gep_type_iterator GTI = gep_type_begin(GEP);
2254 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2255 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002256 I != E; ++I) {
2257 Value *Index = *I;
2258 // Compute the (potentially symbolic) offset in bytes for this index.
2259 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2260 // For a struct, add the member offset.
2261 const StructLayout &SL = *TD->getStructLayout(STy);
2262 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2263 uint64_t Offset = SL.getElementOffset(FieldNo);
2264 TotalOffset = getAddExpr(TotalOffset,
2265 getIntegerSCEV(Offset, IntPtrTy));
2266 } else {
2267 // For an array, add the element offset, explicitly scaled.
2268 SCEVHandle LocalOffset = getSCEV(Index);
2269 if (!isa<PointerType>(LocalOffset->getType()))
2270 // Getelementptr indicies are signed.
2271 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2272 IntPtrTy);
2273 LocalOffset =
2274 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002275 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002276 IntPtrTy));
2277 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2278 }
2279 }
2280 return getAddExpr(getSCEV(Base), TotalOffset);
2281}
2282
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002283/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2284/// guaranteed to end in (at every loop iteration). It is, at the same time,
2285/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2286/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002287static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002288 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002289 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002290
Dan Gohmanc76b5452009-05-04 22:02:23 +00002291 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002292 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2293 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002294
Dan Gohmanc76b5452009-05-04 22:02:23 +00002295 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002296 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2297 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002298 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002299 }
2300
Dan Gohmanc76b5452009-05-04 22:02:23 +00002301 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002302 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2303 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002304 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002305 }
2306
Dan Gohmanc76b5452009-05-04 22:02:23 +00002307 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002308 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002309 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002310 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002311 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002312 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 }
2314
Dan Gohmanc76b5452009-05-04 22:02:23 +00002315 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002316 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002317 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2318 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002319 for (unsigned i = 1, e = M->getNumOperands();
2320 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002321 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002322 BitWidth);
2323 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002325
Dan Gohmanc76b5452009-05-04 22:02:23 +00002326 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002327 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002328 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002329 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002330 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002331 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002332 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002333
Dan Gohmanc76b5452009-05-04 22:02:23 +00002334 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002335 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002336 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00002337 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002338 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00002339 return MinOpRes;
2340 }
2341
Dan Gohmanc76b5452009-05-04 22:02:23 +00002342 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002343 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002344 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002345 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002346 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002347 return MinOpRes;
2348 }
2349
Nick Lewycky35b56022009-01-13 09:18:58 +00002350 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002351 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002352}
2353
2354/// createSCEV - We know that there is no SCEV for the specified value.
2355/// Analyze the expression.
2356///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002357SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002358 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002359 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002360
Dan Gohman3996f472008-06-22 19:56:46 +00002361 unsigned Opcode = Instruction::UserOp1;
2362 if (Instruction *I = dyn_cast<Instruction>(V))
2363 Opcode = I->getOpcode();
2364 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2365 Opcode = CE->getOpcode();
2366 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002367 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002368
Dan Gohman3996f472008-06-22 19:56:46 +00002369 User *U = cast<User>(V);
2370 switch (Opcode) {
2371 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002372 return getAddExpr(getSCEV(U->getOperand(0)),
2373 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002374 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002375 return getMulExpr(getSCEV(U->getOperand(0)),
2376 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002377 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002378 return getUDivExpr(getSCEV(U->getOperand(0)),
2379 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002380 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002381 return getMinusSCEV(getSCEV(U->getOperand(0)),
2382 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002383 case Instruction::And:
2384 // For an expression like x&255 that merely masks off the high bits,
2385 // use zext(trunc(x)) as the SCEV expression.
2386 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002387 if (CI->isNullValue())
2388 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002389 if (CI->isAllOnesValue())
2390 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002391 const APInt &A = CI->getValue();
2392 unsigned Ones = A.countTrailingOnes();
2393 if (APIntOps::isMask(Ones, A))
2394 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002395 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2396 IntegerType::get(Ones)),
2397 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002398 }
2399 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002400 case Instruction::Or:
2401 // If the RHS of the Or is a constant, we may have something like:
2402 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2403 // optimizations will transparently handle this case.
2404 //
2405 // In order for this transformation to be safe, the LHS must be of the
2406 // form X*(2^n) and the Or constant must be less than 2^n.
2407 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2408 SCEVHandle LHS = getSCEV(U->getOperand(0));
2409 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002410 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002411 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002412 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002413 }
Dan Gohman3996f472008-06-22 19:56:46 +00002414 break;
2415 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002416 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002417 // If the RHS of the xor is a signbit, then this is just an add.
2418 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002419 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002420 return getAddExpr(getSCEV(U->getOperand(0)),
2421 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002422
2423 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002424 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002425 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002426
2427 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2428 // This is a variant of the check for xor with -1, and it handles
2429 // the case where instcombine has trimmed non-demanded bits out
2430 // of an xor with -1.
2431 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2432 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2433 if (BO->getOpcode() == Instruction::And &&
2434 LCI->getValue() == CI->getValue())
2435 if (const SCEVZeroExtendExpr *Z =
2436 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0))))
2437 return getZeroExtendExpr(getNotSCEV(Z->getOperand()),
2438 U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002439 }
2440 break;
2441
2442 case Instruction::Shl:
2443 // Turn shift left of a constant amount into a multiply.
2444 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2445 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2446 Constant *X = ConstantInt::get(
2447 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002448 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002449 }
2450 break;
2451
Nick Lewycky7fd27892008-07-07 06:15:49 +00002452 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002453 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002454 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2455 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2456 Constant *X = ConstantInt::get(
2457 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002458 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002459 }
2460 break;
2461
Dan Gohman53bf64a2009-04-21 02:26:00 +00002462 case Instruction::AShr:
2463 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2464 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2465 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2466 if (L->getOpcode() == Instruction::Shl &&
2467 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002468 unsigned BitWidth = getTypeSizeInBits(U->getType());
2469 uint64_t Amt = BitWidth - CI->getZExtValue();
2470 if (Amt == BitWidth)
2471 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2472 if (Amt > BitWidth)
2473 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002474 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002475 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002476 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002477 U->getType());
2478 }
2479 break;
2480
Dan Gohman3996f472008-06-22 19:56:46 +00002481 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002482 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002483
2484 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002485 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002486
2487 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002488 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002489
2490 case Instruction::BitCast:
2491 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002492 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002493 return getSCEV(U->getOperand(0));
2494 break;
2495
Dan Gohman01c2ee72009-04-16 03:18:22 +00002496 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002497 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002498 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002499 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002500
2501 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002502 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002503 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2504 U->getType());
2505
Dan Gohman509cf4d2009-05-08 20:26:55 +00002506 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002507 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002508 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002509
Dan Gohman3996f472008-06-22 19:56:46 +00002510 case Instruction::PHI:
2511 return createNodeForPHI(cast<PHINode>(U));
2512
2513 case Instruction::Select:
2514 // This could be a smax or umax that was lowered earlier.
2515 // Try to recover it.
2516 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2517 Value *LHS = ICI->getOperand(0);
2518 Value *RHS = ICI->getOperand(1);
2519 switch (ICI->getPredicate()) {
2520 case ICmpInst::ICMP_SLT:
2521 case ICmpInst::ICMP_SLE:
2522 std::swap(LHS, RHS);
2523 // fall through
2524 case ICmpInst::ICMP_SGT:
2525 case ICmpInst::ICMP_SGE:
2526 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002527 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002528 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002529 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002530 return getNotSCEV(getSMaxExpr(
2531 getNotSCEV(getSCEV(LHS)),
2532 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002533 break;
2534 case ICmpInst::ICMP_ULT:
2535 case ICmpInst::ICMP_ULE:
2536 std::swap(LHS, RHS);
2537 // fall through
2538 case ICmpInst::ICMP_UGT:
2539 case ICmpInst::ICMP_UGE:
2540 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002541 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002542 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2543 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002544 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2545 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002546 break;
2547 default:
2548 break;
2549 }
2550 }
2551
2552 default: // We cannot analyze this expression.
2553 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002554 }
2555
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002556 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002557}
2558
2559
2560
2561//===----------------------------------------------------------------------===//
2562// Iteration Count Computation Code
2563//
2564
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002565/// getBackedgeTakenCount - If the specified loop has a predictable
2566/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2567/// object. The backedge-taken count is the number of times the loop header
2568/// will be branched to from within the loop. This is one less than the
2569/// trip count of the loop, since it doesn't count the first iteration,
2570/// when the header is branched to from outside the loop.
2571///
2572/// Note that it is not valid to call this method on a loop without a
2573/// loop-invariant backedge-taken count (see
2574/// hasLoopInvariantBackedgeTakenCount).
2575///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002576SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002577 return getBackedgeTakenInfo(L).Exact;
2578}
2579
2580/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2581/// return the least SCEV value that is known never to be less than the
2582/// actual backedge taken count.
2583SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2584 return getBackedgeTakenInfo(L).Max;
2585}
2586
2587const ScalarEvolution::BackedgeTakenInfo &
2588ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002589 // Initially insert a CouldNotCompute for this loop. If the insertion
2590 // succeeds, procede to actually compute a backedge-taken count and
2591 // update the value. The temporary CouldNotCompute value tells SCEV
2592 // code elsewhere that it shouldn't attempt to request a new
2593 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002594 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002595 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2596 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002597 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002598 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002599 assert(ItCount.Exact->isLoopInvariant(L) &&
2600 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002601 "Computed trip count isn't loop invariant for loop!");
2602 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002603
Dan Gohmana9dba962009-04-27 20:16:15 +00002604 // Update the value in the map.
2605 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002606 } else if (isa<PHINode>(L->getHeader()->begin())) {
2607 // Only count loops that have phi nodes as not being computable.
2608 ++NumTripCountsNotComputed;
2609 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002610
2611 // Now that we know more about the trip count for this loop, forget any
2612 // existing SCEV values for PHI nodes in this loop since they are only
2613 // conservative estimates made without the benefit
2614 // of trip count information.
2615 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002616 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002617 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002618 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002619}
2620
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002621/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002622/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002623/// ScalarEvolution's ability to compute a trip count, or if the loop
2624/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002625void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002626 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002627 forgetLoopPHIs(L);
2628}
2629
2630/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2631/// PHI nodes in the given loop. This is used when the trip count of
2632/// the loop may have changed.
2633void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002634 BasicBlock *Header = L->getHeader();
2635
Dan Gohman9fd4a002009-05-12 01:27:58 +00002636 // Push all Loop-header PHIs onto the Worklist stack, except those
2637 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2638 // a PHI either means that it has an unrecognized structure, or it's
2639 // a PHI that's in the progress of being computed by createNodeForPHI.
2640 // In the former case, additional loop trip count information isn't
2641 // going to change anything. In the later case, createNodeForPHI will
2642 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002643 SmallVector<Instruction *, 16> Worklist;
2644 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002645 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2646 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2647 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2648 Worklist.push_back(PN);
2649 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002650
2651 while (!Worklist.empty()) {
2652 Instruction *I = Worklist.pop_back_val();
2653 if (Scalars.erase(I))
2654 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2655 UI != UE; ++UI)
2656 Worklist.push_back(cast<Instruction>(UI));
2657 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002658}
2659
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002660/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2661/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002662ScalarEvolution::BackedgeTakenInfo
2663ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel7388a9a2009-06-05 23:08:56 +00002665 BasicBlock *ExitBlock = L->getExitBlock();
2666 if (!ExitBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002667 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002668
2669 // Okay, there is one exit block. Try to find the condition that causes the
2670 // loop to be exited.
Devang Patel7388a9a2009-06-05 23:08:56 +00002671 BasicBlock *ExitingBlock = L->getExitingBlock();
2672 if (!ExitingBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002673 return CouldNotCompute; // More than one block exiting!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674
2675 // Okay, we've computed the exiting block. See what condition causes us to
2676 // exit.
2677 //
2678 // FIXME: we should be able to handle switch instructions (with a single exit)
2679 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002680 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2682
2683 // At this point, we know we have a conditional branch that determines whether
2684 // the loop is exited. However, we don't know if the branch is executed each
2685 // time through the loop. If not, then the execution count of the branch will
2686 // not be equal to the trip count of the loop.
2687 //
2688 // Currently we check for this by checking to see if the Exit branch goes to
2689 // the loop header. If so, we know it will always execute the same number of
2690 // times as the loop. We also handle the case where the exit block *is* the
2691 // loop header. This is common for un-rotated loops. More extensive analysis
2692 // could be done to handle more cases here.
2693 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2694 ExitBr->getSuccessor(1) != L->getHeader() &&
2695 ExitBr->getParent() != L->getHeader())
Dan Gohman0c850912009-06-06 14:37:11 +00002696 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697
2698 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2699
Eli Friedman459d7292009-05-09 12:32:42 +00002700 // If it's not an integer or pointer comparison then compute it the hard way.
2701 if (ExitCond == 0)
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002702 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 ExitBr->getSuccessor(0) == ExitBlock);
2704
2705 // If the condition was exit on true, convert the condition to exit on false
2706 ICmpInst::Predicate Cond;
2707 if (ExitBr->getSuccessor(1) == ExitBlock)
2708 Cond = ExitCond->getPredicate();
2709 else
2710 Cond = ExitCond->getInversePredicate();
2711
2712 // Handle common loops like: for (X = "string"; *X; ++X)
2713 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2714 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2715 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002716 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002717 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2718 }
2719
2720 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2721 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2722
2723 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00002724 LHS = getSCEVAtScope(LHS, L);
2725 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002726
2727 // At this point, we would like to compute how many iterations of the
2728 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002729 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2730 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731 std::swap(LHS, RHS);
2732 Cond = ICmpInst::getSwappedPredicate(Cond);
2733 }
2734
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735 // If we have a comparison of a chrec against a constant, try to use value
2736 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002737 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2738 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00002740 // Form the constant range.
2741 ConstantRange CompRange(
2742 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002743
Eli Friedman459d7292009-05-09 12:32:42 +00002744 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2745 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002746 }
2747
2748 switch (Cond) {
2749 case ICmpInst::ICMP_NE: { // while (X != Y)
2750 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002751 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2753 break;
2754 }
2755 case ICmpInst::ICMP_EQ: {
2756 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002757 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2759 break;
2760 }
2761 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002762 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2763 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002764 break;
2765 }
2766 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002767 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2768 getNotSCEV(RHS), L, true);
2769 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002770 break;
2771 }
2772 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002773 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2774 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002775 break;
2776 }
2777 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002778 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2779 getNotSCEV(RHS), L, false);
2780 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002781 break;
2782 }
2783 default:
2784#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002785 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002787 errs() << "[unsigned] ";
2788 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002789 << Instruction::getOpcodeName(Instruction::ICmp)
2790 << " " << *RHS << "\n";
2791#endif
2792 break;
2793 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002794 return
2795 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2796 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797}
2798
2799static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002800EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2801 ScalarEvolution &SE) {
2802 SCEVHandle InVal = SE.getConstant(C);
2803 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804 assert(isa<SCEVConstant>(Val) &&
2805 "Evaluation of SCEV at constant didn't fold correctly?");
2806 return cast<SCEVConstant>(Val)->getValue();
2807}
2808
2809/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2810/// and a GEP expression (missing the pointer index) indexing into it, return
2811/// the addressed element of the initializer or null if the index expression is
2812/// invalid.
2813static Constant *
2814GetAddressedElementFromGlobal(GlobalVariable *GV,
2815 const std::vector<ConstantInt*> &Indices) {
2816 Constant *Init = GV->getInitializer();
2817 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2818 uint64_t Idx = Indices[i]->getZExtValue();
2819 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2820 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2821 Init = cast<Constant>(CS->getOperand(Idx));
2822 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2823 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2824 Init = cast<Constant>(CA->getOperand(Idx));
2825 } else if (isa<ConstantAggregateZero>(Init)) {
2826 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2827 assert(Idx < STy->getNumElements() && "Bad struct index!");
2828 Init = Constant::getNullValue(STy->getElementType(Idx));
2829 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2830 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2831 Init = Constant::getNullValue(ATy->getElementType());
2832 } else {
2833 assert(0 && "Unknown constant aggregate type!");
2834 }
2835 return 0;
2836 } else {
2837 return 0; // Unknown initializer type
2838 }
2839 }
2840 return Init;
2841}
2842
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002843/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2844/// 'icmp op load X, cst', try to see if we can compute the backedge
2845/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002846SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002847ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2848 const Loop *L,
2849 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00002850 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002851
2852 // Check to see if the loaded pointer is a getelementptr of a global.
2853 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00002854 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002855
2856 // Make sure that it is really a constant global we are gepping, with an
2857 // initializer, and make sure the first IDX is really 0.
2858 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2859 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2860 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2861 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00002862 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863
2864 // Okay, we allow one non-constant index into the GEP instruction.
2865 Value *VarIdx = 0;
2866 std::vector<ConstantInt*> Indexes;
2867 unsigned VarIdxNum = 0;
2868 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2869 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2870 Indexes.push_back(CI);
2871 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00002872 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873 VarIdx = GEP->getOperand(i);
2874 VarIdxNum = i-2;
2875 Indexes.push_back(0);
2876 }
2877
2878 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2879 // Check to see if X is a loop variant variable value now.
2880 SCEVHandle Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00002881 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002882
2883 // We can only recognize very limited forms of loop index expressions, in
2884 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002885 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2887 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2888 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00002889 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002890
2891 unsigned MaxSteps = MaxBruteForceIterations;
2892 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2893 ConstantInt *ItCst =
2894 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002895 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002896
2897 // Form the GEP offset.
2898 Indexes[VarIdxNum] = Val;
2899
2900 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2901 if (Result == 0) break; // Cannot compute!
2902
2903 // Evaluate the condition for this iteration.
2904 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2905 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2906 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2907#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002908 errs() << "\n***\n*** Computed loop count " << *ItCst
2909 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2910 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911#endif
2912 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002913 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002914 }
2915 }
Dan Gohman0c850912009-06-06 14:37:11 +00002916 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917}
2918
2919
2920/// CanConstantFold - Return true if we can constant fold an instruction of the
2921/// specified type, assuming that all operands were constants.
2922static bool CanConstantFold(const Instruction *I) {
2923 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2924 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2925 return true;
2926
2927 if (const CallInst *CI = dyn_cast<CallInst>(I))
2928 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002929 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002930 return false;
2931}
2932
2933/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2934/// in the loop that V is derived from. We allow arbitrary operations along the
2935/// way, but the operands of an operation must either be constants or a value
2936/// derived from a constant PHI. If this expression does not fit with these
2937/// constraints, return null.
2938static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2939 // If this is not an instruction, or if this is an instruction outside of the
2940 // loop, it can't be derived from a loop PHI.
2941 Instruction *I = dyn_cast<Instruction>(V);
2942 if (I == 0 || !L->contains(I->getParent())) return 0;
2943
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002944 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002945 if (L->getHeader() == I->getParent())
2946 return PN;
2947 else
2948 // We don't currently keep track of the control flow needed to evaluate
2949 // PHIs, so we cannot handle PHIs inside of loops.
2950 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002951 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952
2953 // If we won't be able to constant fold this expression even if the operands
2954 // are constants, return early.
2955 if (!CanConstantFold(I)) return 0;
2956
2957 // Otherwise, we can evaluate this instruction if all of its operands are
2958 // constant or derived from a PHI node themselves.
2959 PHINode *PHI = 0;
2960 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2961 if (!(isa<Constant>(I->getOperand(Op)) ||
2962 isa<GlobalValue>(I->getOperand(Op)))) {
2963 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2964 if (P == 0) return 0; // Not evolving from PHI
2965 if (PHI == 0)
2966 PHI = P;
2967 else if (PHI != P)
2968 return 0; // Evolving from multiple different PHIs.
2969 }
2970
2971 // This is a expression evolving from a constant PHI!
2972 return PHI;
2973}
2974
2975/// EvaluateExpression - Given an expression that passes the
2976/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2977/// in the loop has the value PHIVal. If we can't fold this expression for some
2978/// reason, return null.
2979static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2980 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002982 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 Instruction *I = cast<Instruction>(V);
2984
2985 std::vector<Constant*> Operands;
2986 Operands.resize(I->getNumOperands());
2987
2988 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2989 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2990 if (Operands[i] == 0) return 0;
2991 }
2992
Chris Lattnerd6e56912007-12-10 22:53:04 +00002993 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2994 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2995 &Operands[0], Operands.size());
2996 else
2997 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2998 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002999}
3000
3001/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3002/// in the header of its containing loop, we know the loop executes a
3003/// constant number of times, and the PHI node is just a recurrence
3004/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003005Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003006getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003007 std::map<PHINode*, Constant*>::iterator I =
3008 ConstantEvolutionLoopExitValue.find(PN);
3009 if (I != ConstantEvolutionLoopExitValue.end())
3010 return I->second;
3011
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003012 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3014
3015 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3016
3017 // Since the loop is canonicalized, the PHI node must have two entries. One
3018 // entry must be a constant (coming in from outside of the loop), and the
3019 // second must be derived from the same PHI.
3020 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3021 Constant *StartCST =
3022 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3023 if (StartCST == 0)
3024 return RetVal = 0; // Must be a constant.
3025
3026 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3027 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3028 if (PN2 != PN)
3029 return RetVal = 0; // Not derived from same PHI.
3030
3031 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003032 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3034
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003035 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003036 unsigned IterationNum = 0;
3037 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3038 if (IterationNum == NumIterations)
3039 return RetVal = PHIVal; // Got exit value!
3040
3041 // Compute the value of the PHI node for the next iteration.
3042 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3043 if (NextPHI == PHIVal)
3044 return RetVal = NextPHI; // Stopped evolving!
3045 if (NextPHI == 0)
3046 return 0; // Couldn't evaluate!
3047 PHIVal = NextPHI;
3048 }
3049}
3050
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003051/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003052/// constant number of times (the condition evolves only from constants),
3053/// try to evaluate a few iterations of the loop until we get the exit
3054/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00003055/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003056SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003057ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003058 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003059 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003060
3061 // Since the loop is canonicalized, the PHI node must have two entries. One
3062 // entry must be a constant (coming in from outside of the loop), and the
3063 // second must be derived from the same PHI.
3064 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3065 Constant *StartCST =
3066 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00003067 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003068
3069 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3070 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003071 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003072
3073 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3074 // the loop symbolically to determine when the condition gets a value of
3075 // "ExitWhen".
3076 unsigned IterationNum = 0;
3077 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3078 for (Constant *PHIVal = StartCST;
3079 IterationNum != MaxIterations; ++IterationNum) {
3080 ConstantInt *CondVal =
3081 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3082
3083 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003084 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003085
3086 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3087 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3088 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003089 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003090 }
3091
3092 // Compute the value of the PHI node for the next iteration.
3093 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3094 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00003095 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003096 PHIVal = NextPHI;
3097 }
3098
3099 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003100 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003101}
3102
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003103/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3104/// at the specified scope in the program. The L value specifies a loop
3105/// nest to evaluate the expression at, where null is the top-level or a
3106/// specified loop is immediately inside of the loop.
3107///
3108/// This method can be used to compute the exit value for a variable defined
3109/// in a loop by querying what the value will hold in the parent loop.
3110///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003111/// In the case that a relevant loop exit value cannot be computed, the
3112/// original value V is returned.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003113SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003114 // FIXME: this should be turned into a virtual method on SCEV!
3115
3116 if (isa<SCEVConstant>(V)) return V;
3117
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003118 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003119 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003120 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003122 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003123 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3124 if (PHINode *PN = dyn_cast<PHINode>(I))
3125 if (PN->getParent() == LI->getHeader()) {
3126 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003127 // to see if the loop that contains it has a known backedge-taken
3128 // count. If so, we may be able to force computation of the exit
3129 // value.
3130 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003131 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003132 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003133 // Okay, we know how many times the containing loop executes. If
3134 // this is a constant evolving PHI node, get the final value at
3135 // the specified iteration number.
3136 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003137 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003139 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140 }
3141 }
3142
3143 // Okay, this is an expression that we cannot symbolically evaluate
3144 // into a SCEV. Check to see if it's possible to symbolically evaluate
3145 // the arguments into constants, and if so, try to constant propagate the
3146 // result. This is particularly useful for computing loop exit values.
3147 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003148 // Check to see if we've folded this instruction at this loop before.
3149 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3150 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3151 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3152 if (!Pair.second)
3153 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 std::vector<Constant*> Operands;
3156 Operands.reserve(I->getNumOperands());
3157 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3158 Value *Op = I->getOperand(i);
3159 if (Constant *C = dyn_cast<Constant>(Op)) {
3160 Operands.push_back(C);
3161 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003162 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003163 // non-integer and non-pointer, don't even try to analyze them
3164 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003165 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003166 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003167
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003169 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003170 Constant *C = SC->getValue();
3171 if (C->getType() != Op->getType())
3172 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3173 Op->getType(),
3174 false),
3175 C, Op->getType());
3176 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003177 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003178 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3179 if (C->getType() != Op->getType())
3180 C =
3181 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3182 Op->getType(),
3183 false),
3184 C, Op->getType());
3185 Operands.push_back(C);
3186 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003187 return V;
3188 } else {
3189 return V;
3190 }
3191 }
3192 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00003193
3194 Constant *C;
3195 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3196 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3197 &Operands[0], Operands.size());
3198 else
3199 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3200 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003201 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003202 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 }
3204 }
3205
3206 // This is some other type of SCEVUnknown, just return it.
3207 return V;
3208 }
3209
Dan Gohmanc76b5452009-05-04 22:02:23 +00003210 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211 // Avoid performing the look-up in the common case where the specified
3212 // expression has no loop-variant portions.
3213 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3214 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3215 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216 // Okay, at least one of these operands is loop variant but might be
3217 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman02ff9392009-06-14 22:47:23 +00003218 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 NewOps.push_back(OpAtScope);
3220
3221 for (++i; i != e; ++i) {
3222 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003223 NewOps.push_back(OpAtScope);
3224 }
3225 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003226 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003227 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003228 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003229 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003230 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003231 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003232 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003233 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003234 }
3235 }
3236 // If we got here, all operands are loop invariant.
3237 return Comm;
3238 }
3239
Dan Gohmanc76b5452009-05-04 22:02:23 +00003240 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003241 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003242 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003243 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3244 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003245 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003246 }
3247
3248 // If this is a loop recurrence for a loop that does not contain L, then we
3249 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003250 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003251 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3252 // To evaluate this recurrence, we need to know how many times the AddRec
3253 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003254 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003255 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256
Eli Friedman7489ec92008-08-04 23:49:06 +00003257 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003258 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003260 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003261 }
3262
Dan Gohmanc76b5452009-05-04 22:02:23 +00003263 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003264 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003265 if (Op == Cast->getOperand())
3266 return Cast; // must be loop invariant
3267 return getZeroExtendExpr(Op, Cast->getType());
3268 }
3269
Dan Gohmanc76b5452009-05-04 22:02:23 +00003270 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003271 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003272 if (Op == Cast->getOperand())
3273 return Cast; // must be loop invariant
3274 return getSignExtendExpr(Op, Cast->getType());
3275 }
3276
Dan Gohmanc76b5452009-05-04 22:02:23 +00003277 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003278 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003279 if (Op == Cast->getOperand())
3280 return Cast; // must be loop invariant
3281 return getTruncateExpr(Op, Cast->getType());
3282 }
3283
3284 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003285 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003286}
3287
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003288/// getSCEVAtScope - This is a convenience function which does
3289/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003290SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3291 return getSCEVAtScope(getSCEV(V), L);
3292}
3293
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003294/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3295/// following equation:
3296///
3297/// A * X = B (mod N)
3298///
3299/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3300/// A and B isn't important.
3301///
3302/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3303static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3304 ScalarEvolution &SE) {
3305 uint32_t BW = A.getBitWidth();
3306 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3307 assert(A != 0 && "A must be non-zero.");
3308
3309 // 1. D = gcd(A, N)
3310 //
3311 // The gcd of A and N may have only one prime factor: 2. The number of
3312 // trailing zeros in A is its multiplicity
3313 uint32_t Mult2 = A.countTrailingZeros();
3314 // D = 2^Mult2
3315
3316 // 2. Check if B is divisible by D.
3317 //
3318 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3319 // is not less than multiplicity of this prime factor for D.
3320 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003321 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003322
3323 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3324 // modulo (N / D).
3325 //
3326 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3327 // bit width during computations.
3328 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3329 APInt Mod(BW + 1, 0);
3330 Mod.set(BW - Mult2); // Mod = N / D
3331 APInt I = AD.multiplicativeInverse(Mod);
3332
3333 // 4. Compute the minimum unsigned root of the equation:
3334 // I * (B / D) mod (N / D)
3335 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3336
3337 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3338 // bits.
3339 return SE.getConstant(Result.trunc(BW));
3340}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003341
3342/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3343/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3344/// might be the same) or two SCEVCouldNotCompute objects.
3345///
3346static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00003347SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003348 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003349 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3350 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3351 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003352
3353 // We currently can only solve this if the coefficients are constants.
3354 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003355 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356 return std::make_pair(CNC, CNC);
3357 }
3358
3359 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3360 const APInt &L = LC->getValue()->getValue();
3361 const APInt &M = MC->getValue()->getValue();
3362 const APInt &N = NC->getValue()->getValue();
3363 APInt Two(BitWidth, 2);
3364 APInt Four(BitWidth, 4);
3365
3366 {
3367 using namespace APIntOps;
3368 const APInt& C = L;
3369 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3370 // The B coefficient is M-N/2
3371 APInt B(M);
3372 B -= sdiv(N,Two);
3373
3374 // The A coefficient is N/2
3375 APInt A(N.sdiv(Two));
3376
3377 // Compute the B^2-4ac term.
3378 APInt SqrtTerm(B);
3379 SqrtTerm *= B;
3380 SqrtTerm -= Four * (A * C);
3381
3382 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3383 // integer value or else APInt::sqrt() will assert.
3384 APInt SqrtVal(SqrtTerm.sqrt());
3385
3386 // Compute the two solutions for the quadratic formula.
3387 // The divisions must be performed as signed divisions.
3388 APInt NegB(-B);
3389 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003390 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003391 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003392 return std::make_pair(CNC, CNC);
3393 }
3394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003395 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3396 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3397
Dan Gohman89f85052007-10-22 18:31:58 +00003398 return std::make_pair(SE.getConstant(Solution1),
3399 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003400 } // end APIntOps namespace
3401}
3402
3403/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003404/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003405SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003407 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003408 // If the value is already zero, the branch will execute zero times.
3409 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003410 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411 }
3412
Dan Gohmanbff6b582009-05-04 22:30:44 +00003413 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003414 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003415 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003416
3417 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003418 // If this is an affine expression, the execution count of this branch is
3419 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003420 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003421 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003422 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003423 // equivalent to:
3424 //
3425 // Step*N = -Start (mod 2^BW)
3426 //
3427 // where BW is the common bit width of Start and Step.
3428
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003429 // Get the initial value for the loop.
3430 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003431 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003432
Dan Gohmanc76b5452009-05-04 22:02:23 +00003433 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003434 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003435
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003436 // First, handle unitary steps.
3437 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003438 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003439 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3440 return Start; // N = Start (as unsigned)
3441
3442 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003443 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003444 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003445 -StartC->getValue()->getValue(),
3446 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447 }
3448 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3449 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3450 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003451 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3452 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003453 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3454 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455 if (R1) {
3456#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003457 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3458 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003459#endif
3460 // Pick the smallest positive root value.
3461 if (ConstantInt *CB =
3462 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3463 R1->getValue(), R2->getValue()))) {
3464 if (CB->getZExtValue() == false)
3465 std::swap(R1, R2); // R1 is the minimum root now.
3466
3467 // We can only use this value if the chrec ends up with an exact zero
3468 // value at this index. When solving for "X*X != 5", for example, we
3469 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003470 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003471 if (Val->isZero())
3472 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003473 }
3474 }
3475 }
3476
Dan Gohman0c850912009-06-06 14:37:11 +00003477 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478}
3479
3480/// HowFarToNonZero - Return the number of times a backedge checking the
3481/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003482/// CouldNotCompute
Dan Gohmanbff6b582009-05-04 22:30:44 +00003483SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003484 // Loops that look like: while (X == 0) are very strange indeed. We don't
3485 // handle them yet except for the trivial case. This could be expanded in the
3486 // future as needed.
3487
3488 // If the value is a constant, check to see if it is known to be non-zero
3489 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003490 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003491 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003492 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003493 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003494 }
3495
3496 // We could implement others, but I really doubt anyone writes loops like
3497 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003498 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499}
3500
Dan Gohmanab157b22009-05-18 15:36:09 +00003501/// getLoopPredecessor - If the given loop's header has exactly one unique
3502/// predecessor outside the loop, return it. Otherwise return null.
3503///
3504BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3505 BasicBlock *Header = L->getHeader();
3506 BasicBlock *Pred = 0;
3507 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3508 PI != E; ++PI)
3509 if (!L->contains(*PI)) {
3510 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3511 Pred = *PI;
3512 }
3513 return Pred;
3514}
3515
Dan Gohman1cddf972008-09-15 22:18:04 +00003516/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3517/// (which may not be an immediate predecessor) which has exactly one
3518/// successor from which BB is reachable, or null if no such block is
3519/// found.
3520///
3521BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003522ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003523 // If the block has a unique predecessor, then there is no path from the
3524 // predecessor to the block that does not go through the direct edge
3525 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003526 if (BasicBlock *Pred = BB->getSinglePredecessor())
3527 return Pred;
3528
3529 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003530 // If the header has a unique predecessor outside the loop, it must be
3531 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003532 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003533 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003534
3535 return 0;
3536}
3537
Dan Gohmancacd2012009-02-12 22:19:27 +00003538/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003539/// a conditional between LHS and RHS. This is used to help avoid max
3540/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003541bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003542 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003543 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003544 // Interpret a null as meaning no loop, where there is obviously no guard
3545 // (interprocedural conditions notwithstanding).
3546 if (!L) return false;
3547
Dan Gohmanab157b22009-05-18 15:36:09 +00003548 BasicBlock *Predecessor = getLoopPredecessor(L);
3549 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003550
Dan Gohmanab157b22009-05-18 15:36:09 +00003551 // Starting at the loop predecessor, climb up the predecessor chain, as long
3552 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003553 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003554 for (; Predecessor;
3555 PredecessorDest = Predecessor,
3556 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003557
3558 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003559 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003560 if (!LoopEntryPredicate ||
3561 LoopEntryPredicate->isUnconditional())
3562 continue;
3563
3564 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3565 if (!ICI) continue;
3566
3567 // Now that we found a conditional branch that dominates the loop, check to
3568 // see if it is the comparison we are looking for.
3569 Value *PreCondLHS = ICI->getOperand(0);
3570 Value *PreCondRHS = ICI->getOperand(1);
3571 ICmpInst::Predicate Cond;
Dan Gohmanab157b22009-05-18 15:36:09 +00003572 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohmanab678fb2008-08-12 20:17:31 +00003573 Cond = ICI->getPredicate();
3574 else
3575 Cond = ICI->getInversePredicate();
3576
Dan Gohmancacd2012009-02-12 22:19:27 +00003577 if (Cond == Pred)
3578 ; // An exact match.
3579 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3580 ; // The actual condition is beyond sufficient.
3581 else
3582 // Check a few special cases.
3583 switch (Cond) {
3584 case ICmpInst::ICMP_UGT:
3585 if (Pred == ICmpInst::ICMP_ULT) {
3586 std::swap(PreCondLHS, PreCondRHS);
3587 Cond = ICmpInst::ICMP_ULT;
3588 break;
3589 }
3590 continue;
3591 case ICmpInst::ICMP_SGT:
3592 if (Pred == ICmpInst::ICMP_SLT) {
3593 std::swap(PreCondLHS, PreCondRHS);
3594 Cond = ICmpInst::ICMP_SLT;
3595 break;
3596 }
3597 continue;
3598 case ICmpInst::ICMP_NE:
3599 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3600 // so check for this case by checking if the NE is comparing against
3601 // a minimum or maximum constant.
3602 if (!ICmpInst::isTrueWhenEqual(Pred))
3603 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3604 const APInt &A = CI->getValue();
3605 switch (Pred) {
3606 case ICmpInst::ICMP_SLT:
3607 if (A.isMaxSignedValue()) break;
3608 continue;
3609 case ICmpInst::ICMP_SGT:
3610 if (A.isMinSignedValue()) break;
3611 continue;
3612 case ICmpInst::ICMP_ULT:
3613 if (A.isMaxValue()) break;
3614 continue;
3615 case ICmpInst::ICMP_UGT:
3616 if (A.isMinValue()) break;
3617 continue;
3618 default:
3619 continue;
3620 }
3621 Cond = ICmpInst::ICMP_NE;
3622 // NE is symmetric but the original comparison may not be. Swap
3623 // the operands if necessary so that they match below.
3624 if (isa<SCEVConstant>(LHS))
3625 std::swap(PreCondLHS, PreCondRHS);
3626 break;
3627 }
3628 continue;
3629 default:
3630 // We weren't able to reconcile the condition.
3631 continue;
3632 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003633
3634 if (!PreCondLHS->getType()->isInteger()) continue;
3635
3636 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3637 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3638 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003639 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3640 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003641 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003642 }
3643
Dan Gohmanab678fb2008-08-12 20:17:31 +00003644 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003645}
3646
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003647/// HowManyLessThans - Return the number of times a backedge containing the
3648/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003649/// CouldNotCompute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003650ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003651HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3652 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003653 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00003654 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655
Dan Gohmanbff6b582009-05-04 22:30:44 +00003656 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003657 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003658 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003659
3660 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003661 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003662 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3663 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3664 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3665
3666 // TODO: handle non-constant strides.
3667 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3668 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00003669 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00003670 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003671 // With unit stride, the iteration never steps past the limit value.
3672 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3673 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3674 // Test whether a positive iteration iteration can step past the limit
3675 // value and past the maximum value for its type in a single step.
3676 if (isSigned) {
3677 APInt Max = APInt::getSignedMaxValue(BitWidth);
3678 if ((Max - CStep->getValue()->getValue())
3679 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003680 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003681 } else {
3682 APInt Max = APInt::getMaxValue(BitWidth);
3683 if ((Max - CStep->getValue()->getValue())
3684 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003685 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003686 }
3687 } else
3688 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00003689 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003690 } else
3691 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00003692 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003694 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3695 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3696 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003697 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003699 // First, we get the value of the LHS in the first iteration: n
3700 SCEVHandle Start = AddRec->getOperand(0);
3701
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003702 // Determine the minimum constant start value.
3703 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3704 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3705 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003706
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003707 // If we know that the condition is true in order to enter the loop,
3708 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00003709 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3710 // the division must round up.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003711 SCEVHandle End = RHS;
3712 if (!isLoopGuardedByCond(L,
3713 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3714 getMinusSCEV(Start, Step), RHS))
3715 End = isSigned ? getSMaxExpr(RHS, Start)
3716 : getUMaxExpr(RHS, Start);
3717
3718 // Determine the maximum constant end value.
3719 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3720 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3721 APInt::getMaxValue(BitWidth));
3722
3723 // Finally, we subtract these two values and divide, rounding up, to get
3724 // the number of times the backedge is executed.
3725 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3726 getAddExpr(Step, NegOne)),
3727 Step);
3728
3729 // The maximum backedge count is similar, except using the minimum start
3730 // value and the maximum end value.
3731 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3732 MinStart),
3733 getAddExpr(Step, NegOne)),
3734 Step);
3735
3736 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003737 }
3738
Dan Gohman0c850912009-06-06 14:37:11 +00003739 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003740}
3741
3742/// getNumIterationsInRange - Return the number of iterations of this loop that
3743/// produce values in the specified constant range. Another way of looking at
3744/// this is that it returns the first iteration number where the value is not in
3745/// the condition, thus computing the exit count. If the iteration count can't
3746/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003747SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3748 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003749 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003750 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003751
3752 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003753 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003754 if (!SC->getValue()->isZero()) {
Dan Gohman02ff9392009-06-14 22:47:23 +00003755 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003756 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3757 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003758 if (const SCEVAddRecExpr *ShiftedAddRec =
3759 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003760 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003761 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003762 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003763 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003764 }
3765
3766 // The only time we can solve this is when we have all constant indices.
3767 // Otherwise, we cannot determine the overflow conditions.
3768 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3769 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003770 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003771
3772
3773 // Okay at this point we know that all elements of the chrec are constants and
3774 // that the start element is zero.
3775
3776 // First check to see if the range contains zero. If not, the first
3777 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003778 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003779 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003780 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003781
3782 if (isAffine()) {
3783 // If this is an affine expression then we have this situation:
3784 // Solve {0,+,A} in Range === Ax in Range
3785
3786 // We know that zero is in the range. If A is positive then we know that
3787 // the upper value of the range must be the first possible exit value.
3788 // If A is negative then the lower of the range is the last possible loop
3789 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003790 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003791 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3792 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3793
3794 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003795 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3797
3798 // Evaluate at the exit value. If we really did fall out of the valid
3799 // range, then we computed our trip count, otherwise wrap around or other
3800 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003801 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003802 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003803 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003804
3805 // Ensure that the previous value is in the range. This is a sanity check.
3806 assert(Range.contains(
3807 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003808 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003809 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003810 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003811 } else if (isQuadratic()) {
3812 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3813 // quadratic equation to solve it. To do this, we must frame our problem in
3814 // terms of figuring out when zero is crossed, instead of when
3815 // Range.getUpper() is crossed.
Dan Gohman02ff9392009-06-14 22:47:23 +00003816 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003817 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3818 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003819
3820 // Next, solve the constructed addrec
3821 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003822 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003823 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3824 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003825 if (R1) {
3826 // Pick the smallest positive root value.
3827 if (ConstantInt *CB =
3828 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3829 R1->getValue(), R2->getValue()))) {
3830 if (CB->getZExtValue() == false)
3831 std::swap(R1, R2); // R1 is the minimum root now.
3832
3833 // Make sure the root is not off by one. The returned iteration should
3834 // not be in the range, but the previous one should be. When solving
3835 // for "X*X < 5", for example, we should not return a root of 2.
3836 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003837 R1->getValue(),
3838 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003839 if (Range.contains(R1Val->getValue())) {
3840 // The next iteration must be out of the range...
3841 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3842
Dan Gohman89f85052007-10-22 18:31:58 +00003843 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003844 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003845 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003846 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003847 }
3848
3849 // If R1 was not in the range, then it is a good return value. Make
3850 // sure that R1-1 WAS in the range though, just in case.
3851 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003852 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003853 if (Range.contains(R1Val->getValue()))
3854 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003855 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003856 }
3857 }
3858 }
3859
Dan Gohman0ad08b02009-04-18 17:58:19 +00003860 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003861}
3862
3863
3864
3865//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003866// SCEVCallbackVH Class Implementation
3867//===----------------------------------------------------------------------===//
3868
Dan Gohman999d14e2009-05-19 19:22:47 +00003869void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003870 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3871 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3872 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003873 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3874 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003875 SE->Scalars.erase(getValPtr());
3876 // this now dangles!
3877}
3878
Dan Gohman999d14e2009-05-19 19:22:47 +00003879void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003880 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3881
3882 // Forget all the expressions associated with users of the old value,
3883 // so that future queries will recompute the expressions using the new
3884 // value.
3885 SmallVector<User *, 16> Worklist;
3886 Value *Old = getValPtr();
3887 bool DeleteOld = false;
3888 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3889 UI != UE; ++UI)
3890 Worklist.push_back(*UI);
3891 while (!Worklist.empty()) {
3892 User *U = Worklist.pop_back_val();
3893 // Deleting the Old value will cause this to dangle. Postpone
3894 // that until everything else is done.
3895 if (U == Old) {
3896 DeleteOld = true;
3897 continue;
3898 }
3899 if (PHINode *PN = dyn_cast<PHINode>(U))
3900 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003901 if (Instruction *I = dyn_cast<Instruction>(U))
3902 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003903 if (SE->Scalars.erase(U))
3904 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3905 UI != UE; ++UI)
3906 Worklist.push_back(*UI);
3907 }
3908 if (DeleteOld) {
3909 if (PHINode *PN = dyn_cast<PHINode>(Old))
3910 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003911 if (Instruction *I = dyn_cast<Instruction>(Old))
3912 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003913 SE->Scalars.erase(Old);
3914 // this now dangles!
3915 }
3916 // this may dangle!
3917}
3918
Dan Gohman999d14e2009-05-19 19:22:47 +00003919ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00003920 : CallbackVH(V), SE(se) {}
3921
3922//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003923// ScalarEvolution Class Implementation
3924//===----------------------------------------------------------------------===//
3925
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003926ScalarEvolution::ScalarEvolution()
Dan Gohman0c850912009-06-06 14:37:11 +00003927 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003928}
3929
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003930bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003931 this->F = &F;
3932 LI = &getAnalysis<LoopInfo>();
3933 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003934 return false;
3935}
3936
3937void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003938 Scalars.clear();
3939 BackedgeTakenCounts.clear();
3940 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00003941 ValuesAtScopes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003942}
3943
3944void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3945 AU.setPreservesAll();
3946 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003947}
3948
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003949bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003950 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003951}
3952
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003953static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003954 const Loop *L) {
3955 // Print all inner loops first
3956 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3957 PrintLoopInfo(OS, SE, *I);
3958
Nick Lewyckye5da1912008-01-02 02:49:20 +00003959 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003960
Devang Patel02451fa2007-08-21 00:31:24 +00003961 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003962 L->getExitBlocks(ExitBlocks);
3963 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003964 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003965
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003966 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3967 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003968 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003969 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003970 }
3971
Nick Lewyckye5da1912008-01-02 02:49:20 +00003972 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003973}
3974
Dan Gohman13058cc2009-04-21 00:47:46 +00003975void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003976 // ScalarEvolution's implementaiton of the print method is to print
3977 // out SCEV values of all instructions that are interesting. Doing
3978 // this potentially causes it to create new SCEV objects though,
3979 // which technically conflicts with the const qualifier. This isn't
3980 // observable from outside the class though (the hasSCEV function
3981 // notwithstanding), so casting away the const isn't dangerous.
3982 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003983
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003984 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003985 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003986 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003987 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003988 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003989 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003990 SV->print(OS);
3991 OS << "\t\t";
3992
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003993 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003994 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003995 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00003996 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003997 OS << "<<Unknown>>";
3998 } else {
3999 OS << *ExitValue;
4000 }
4001 }
4002
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004003 OS << "\n";
4004 }
4005
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004006 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4007 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4008 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004009}
Dan Gohman13058cc2009-04-21 00:47:46 +00004010
4011void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4012 raw_os_ostream OS(o);
4013 print(OS, M);
4014}