blob: ee077d56b628ae3da838f9f9a75465a4cc86ae44 [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 Gohmanc8a29272009-05-24 23:45:28 +0000991/// getAddExpr - Get a canonical add expression, or something simpler if
992/// possible.
Dan Gohman02ff9392009-06-14 22:47:23 +0000993SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 assert(!Ops.empty() && "Cannot get empty add!");
995 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +0000996#ifndef NDEBUG
997 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
998 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
999 getEffectiveSCEVType(Ops[0]->getType()) &&
1000 "SCEVAddExpr operand types don't match!");
1001#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002
1003 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001004 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005
1006 // If there are any constants, fold them together.
1007 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001008 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 ++Idx;
1010 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001011 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001013 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1014 RHSC->getValue()->getValue());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001015 Ops.erase(Ops.begin()+1); // Erase the folded element
1016 if (Ops.size() == 1) return Ops[0];
1017 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 }
1019
1020 // If we are left with a constant zero being added, strip it off.
1021 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1022 Ops.erase(Ops.begin());
1023 --Idx;
1024 }
1025 }
1026
1027 if (Ops.size() == 1) return Ops[0];
1028
1029 // Okay, check to see if the same value occurs in the operand list twice. If
1030 // so, merge them together into an multiply expression. Since we sorted the
1031 // list, these values are required to be adjacent.
1032 const Type *Ty = Ops[0]->getType();
1033 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1034 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1035 // Found a match, merge the two values into a multiply, and add any
1036 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +00001037 SCEVHandle Two = getIntegerSCEV(2, Ty);
1038 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 if (Ops.size() == 2)
1040 return Mul;
1041 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1042 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001043 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 }
1045
Dan Gohman45b3b542009-05-08 21:03:19 +00001046 // Check for truncates. If all the operands are truncated from the same
1047 // type, see if factoring out the truncate would permit the result to be
1048 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1049 // if the contents of the resulting outer trunc fold to something simple.
1050 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1051 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1052 const Type *DstType = Trunc->getType();
1053 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman02ff9392009-06-14 22:47:23 +00001054 SmallVector<SCEVHandle, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001055 bool Ok = true;
1056 // Check all the operands to see if they can be represented in the
1057 // source type of the truncate.
1058 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1059 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1060 if (T->getOperand()->getType() != SrcType) {
1061 Ok = false;
1062 break;
1063 }
1064 LargeOps.push_back(T->getOperand());
1065 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1066 // This could be either sign or zero extension, but sign extension
1067 // is much more likely to be foldable here.
1068 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1069 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001070 SmallVector<SCEVHandle, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001071 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1072 if (const SCEVTruncateExpr *T =
1073 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1074 if (T->getOperand()->getType() != SrcType) {
1075 Ok = false;
1076 break;
1077 }
1078 LargeMulOps.push_back(T->getOperand());
1079 } else if (const SCEVConstant *C =
1080 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1081 // This could be either sign or zero extension, but sign extension
1082 // is much more likely to be foldable here.
1083 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1084 } else {
1085 Ok = false;
1086 break;
1087 }
1088 }
1089 if (Ok)
1090 LargeOps.push_back(getMulExpr(LargeMulOps));
1091 } else {
1092 Ok = false;
1093 break;
1094 }
1095 }
1096 if (Ok) {
1097 // Evaluate the expression in the larger type.
1098 SCEVHandle Fold = getAddExpr(LargeOps);
1099 // If it folds to something simple, use it. Otherwise, don't.
1100 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1101 return getTruncateExpr(Fold, DstType);
1102 }
1103 }
1104
1105 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1107 ++Idx;
1108
1109 // If there are add operands they would be next.
1110 if (Idx < Ops.size()) {
1111 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001112 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 // If we have an add, expand the add operands onto the end of the operands
1114 // list.
1115 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1116 Ops.erase(Ops.begin()+Idx);
1117 DeletedAdd = true;
1118 }
1119
1120 // If we deleted at least one add, we added operands to the end of the list,
1121 // and they are not necessarily sorted. Recurse to resort and resimplify
1122 // any operands we just aquired.
1123 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001124 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 }
1126
1127 // Skip over the add expression until we get to a multiply.
1128 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1129 ++Idx;
1130
1131 // If we are adding something to a multiply expression, make sure the
1132 // something is not already an operand of the multiply. If so, merge it into
1133 // the multiply.
1134 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001135 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001137 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001139 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1141 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1142 if (Mul->getNumOperands() != 2) {
1143 // If the multiply has more than two operands, we must get the
1144 // Y*Z term.
Dan Gohman02ff9392009-06-14 22:47:23 +00001145 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001147 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 }
Dan Gohman89f85052007-10-22 18:31:58 +00001149 SCEVHandle One = getIntegerSCEV(1, Ty);
1150 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1151 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 if (Ops.size() == 2) return OuterMul;
1153 if (AddOp < Idx) {
1154 Ops.erase(Ops.begin()+AddOp);
1155 Ops.erase(Ops.begin()+Idx-1);
1156 } else {
1157 Ops.erase(Ops.begin()+Idx);
1158 Ops.erase(Ops.begin()+AddOp-1);
1159 }
1160 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001161 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162 }
1163
1164 // Check this multiply against other multiplies being added together.
1165 for (unsigned OtherMulIdx = Idx+1;
1166 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1167 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001168 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001169 // If MulOp occurs in OtherMul, we can fold the two multiplies
1170 // together.
1171 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1172 OMulOp != e; ++OMulOp)
1173 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1174 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1175 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1176 if (Mul->getNumOperands() != 2) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001177 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001179 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 }
1181 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1182 if (OtherMul->getNumOperands() != 2) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001183 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 OtherMul->op_end());
1185 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001186 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 }
Dan Gohman89f85052007-10-22 18:31:58 +00001188 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1189 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 if (Ops.size() == 2) return OuterMul;
1191 Ops.erase(Ops.begin()+Idx);
1192 Ops.erase(Ops.begin()+OtherMulIdx-1);
1193 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001194 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195 }
1196 }
1197 }
1198 }
1199
1200 // If there are any add recurrences in the operands list, see if any other
1201 // added values are loop invariant. If so, we can fold them into the
1202 // recurrence.
1203 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1204 ++Idx;
1205
1206 // Scan over all recurrences, trying to fold loop invariants into them.
1207 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1208 // Scan all of the other operands to this add and add them to the vector if
1209 // they are loop invariant w.r.t. the recurrence.
Dan Gohman02ff9392009-06-14 22:47:23 +00001210 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001211 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1213 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1214 LIOps.push_back(Ops[i]);
1215 Ops.erase(Ops.begin()+i);
1216 --i; --e;
1217 }
1218
1219 // If we found some loop invariants, fold them into the recurrence.
1220 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001221 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001222 LIOps.push_back(AddRec->getStart());
1223
Dan Gohman02ff9392009-06-14 22:47:23 +00001224 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1225 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001226 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227
Dan Gohman89f85052007-10-22 18:31:58 +00001228 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 // If all of the other operands were loop invariant, we are done.
1230 if (Ops.size() == 1) return NewRec;
1231
1232 // Otherwise, add the folded AddRec by the non-liv parts.
1233 for (unsigned i = 0;; ++i)
1234 if (Ops[i] == AddRec) {
1235 Ops[i] = NewRec;
1236 break;
1237 }
Dan Gohman89f85052007-10-22 18:31:58 +00001238 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 }
1240
1241 // Okay, if there weren't any loop invariants to be folded, check to see if
1242 // there are multiple AddRec's with the same loop induction variable being
1243 // added together. If so, we can fold them.
1244 for (unsigned OtherIdx = Idx+1;
1245 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1246 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001247 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1249 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman02ff9392009-06-14 22:47:23 +00001250 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1252 if (i >= NewOps.size()) {
1253 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1254 OtherAddRec->op_end());
1255 break;
1256 }
Dan Gohman89f85052007-10-22 18:31:58 +00001257 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 }
Dan Gohman89f85052007-10-22 18:31:58 +00001259 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260
1261 if (Ops.size() == 2) return NewAddRec;
1262
1263 Ops.erase(Ops.begin()+Idx);
1264 Ops.erase(Ops.begin()+OtherIdx-1);
1265 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001266 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 }
1268 }
1269
1270 // Otherwise couldn't fold anything into this recurrence. Move onto the
1271 // next one.
1272 }
1273
1274 // Okay, it looks like we really DO need an add expr. Check to see if we
1275 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001276 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1278 SCEVOps)];
1279 if (Result == 0) Result = new SCEVAddExpr(Ops);
1280 return Result;
1281}
1282
1283
Dan Gohmanc8a29272009-05-24 23:45:28 +00001284/// getMulExpr - Get a canonical multiply expression, or something simpler if
1285/// possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001286SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001288#ifndef NDEBUG
1289 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1290 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1291 getEffectiveSCEVType(Ops[0]->getType()) &&
1292 "SCEVMulExpr operand types don't match!");
1293#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294
1295 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001296 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297
1298 // If there are any constants, fold them together.
1299 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001300 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301
1302 // C1*(C2+V) -> C1*C2 + C1*V
1303 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001304 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 if (Add->getNumOperands() == 2 &&
1306 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001307 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1308 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309
1310
1311 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001312 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001314 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1315 RHSC->getValue()->getValue());
1316 Ops[0] = getConstant(Fold);
1317 Ops.erase(Ops.begin()+1); // Erase the folded element
1318 if (Ops.size() == 1) return Ops[0];
1319 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 }
1321
1322 // If we are left with a constant one being multiplied, strip it off.
1323 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1324 Ops.erase(Ops.begin());
1325 --Idx;
1326 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1327 // If we have a multiply of zero, it will always be zero.
1328 return Ops[0];
1329 }
1330 }
1331
1332 // Skip over the add expression until we get to a multiply.
1333 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1334 ++Idx;
1335
1336 if (Ops.size() == 1)
1337 return Ops[0];
1338
1339 // If there are mul operands inline them all into this expression.
1340 if (Idx < Ops.size()) {
1341 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001342 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 // If we have an mul, expand the mul operands onto the end of the operands
1344 // list.
1345 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1346 Ops.erase(Ops.begin()+Idx);
1347 DeletedMul = true;
1348 }
1349
1350 // If we deleted at least one mul, we added operands to the end of the list,
1351 // and they are not necessarily sorted. Recurse to resort and resimplify
1352 // any operands we just aquired.
1353 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001354 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 }
1356
1357 // If there are any add recurrences in the operands list, see if any other
1358 // added values are loop invariant. If so, we can fold them into the
1359 // recurrence.
1360 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1361 ++Idx;
1362
1363 // Scan over all recurrences, trying to fold loop invariants into them.
1364 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1365 // Scan all of the other operands to this mul and add them to the vector if
1366 // they are loop invariant w.r.t. the recurrence.
Dan Gohman02ff9392009-06-14 22:47:23 +00001367 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001368 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1370 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1371 LIOps.push_back(Ops[i]);
1372 Ops.erase(Ops.begin()+i);
1373 --i; --e;
1374 }
1375
1376 // If we found some loop invariants, fold them into the recurrence.
1377 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001378 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman02ff9392009-06-14 22:47:23 +00001379 SmallVector<SCEVHandle, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 NewOps.reserve(AddRec->getNumOperands());
1381 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001382 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001384 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 } else {
1386 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001387 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001389 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 }
1391 }
1392
Dan Gohman89f85052007-10-22 18:31:58 +00001393 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394
1395 // If all of the other operands were loop invariant, we are done.
1396 if (Ops.size() == 1) return NewRec;
1397
1398 // Otherwise, multiply the folded AddRec by the non-liv parts.
1399 for (unsigned i = 0;; ++i)
1400 if (Ops[i] == AddRec) {
1401 Ops[i] = NewRec;
1402 break;
1403 }
Dan Gohman89f85052007-10-22 18:31:58 +00001404 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 }
1406
1407 // Okay, if there weren't any loop invariants to be folded, check to see if
1408 // there are multiple AddRec's with the same loop induction variable being
1409 // multiplied together. If so, we can fold them.
1410 for (unsigned OtherIdx = Idx+1;
1411 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1412 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001413 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001414 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1415 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001416 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001417 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001419 SCEVHandle B = F->getStepRecurrence(*this);
1420 SCEVHandle D = G->getStepRecurrence(*this);
1421 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1422 getMulExpr(G, B),
1423 getMulExpr(B, D));
1424 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1425 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 if (Ops.size() == 2) return NewAddRec;
1427
1428 Ops.erase(Ops.begin()+Idx);
1429 Ops.erase(Ops.begin()+OtherIdx-1);
1430 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001431 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 }
1433 }
1434
1435 // Otherwise couldn't fold anything into this recurrence. Move onto the
1436 // next one.
1437 }
1438
1439 // Okay, it looks like we really DO need an mul expr. Check to see if we
1440 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001441 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1443 SCEVOps)];
1444 if (Result == 0)
1445 Result = new SCEVMulExpr(Ops);
1446 return Result;
1447}
1448
Dan Gohmanc8a29272009-05-24 23:45:28 +00001449/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1450/// possible.
Dan Gohman77841cd2009-05-04 22:23:18 +00001451SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1452 const SCEVHandle &RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001453 assert(getEffectiveSCEVType(LHS->getType()) ==
1454 getEffectiveSCEVType(RHS->getType()) &&
1455 "SCEVUDivExpr operand types don't match!");
1456
Dan Gohmanc76b5452009-05-04 22:02:23 +00001457 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001459 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001460 if (RHSC->isZero())
1461 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001463 // Determine if the division can be folded into the operands of
1464 // its operands.
1465 // TODO: Generalize this to non-constants by using known-bits information.
1466 const Type *Ty = LHS->getType();
1467 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1468 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1469 // For non-power-of-two values, effectively round the value up to the
1470 // nearest power of two.
1471 if (!RHSC->getValue()->getValue().isPowerOf2())
1472 ++MaxShiftAmt;
1473 const IntegerType *ExtTy =
1474 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1475 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1476 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1477 if (const SCEVConstant *Step =
1478 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1479 if (!Step->getValue()->getValue()
1480 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001481 getZeroExtendExpr(AR, ExtTy) ==
1482 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1483 getZeroExtendExpr(Step, ExtTy),
1484 AR->getLoop())) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001485 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001486 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1487 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1488 return getAddRecExpr(Operands, AR->getLoop());
1489 }
1490 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001491 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001492 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001493 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1494 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1495 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001496 // Find an operand that's safely divisible.
1497 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1498 SCEVHandle Op = M->getOperand(i);
1499 SCEVHandle Div = getUDivExpr(Op, RHSC);
1500 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001501 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1502 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1503 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001504 Operands[i] = Div;
1505 return getMulExpr(Operands);
1506 }
1507 }
Dan Gohman14374d32009-05-08 23:11:16 +00001508 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001509 // (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 +00001510 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001511 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001512 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1513 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1514 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1515 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001516 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1517 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1518 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1519 break;
1520 Operands.push_back(Op);
1521 }
1522 if (Operands.size() == A->getNumOperands())
1523 return getAddExpr(Operands);
1524 }
Dan Gohman14374d32009-05-08 23:11:16 +00001525 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001526
1527 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001528 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529 Constant *LHSCV = LHSC->getValue();
1530 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001531 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532 }
1533 }
1534
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001535 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1536 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537 return Result;
1538}
1539
1540
Dan Gohmanc8a29272009-05-24 23:45:28 +00001541/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1542/// Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001543SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001544 const SCEVHandle &Step, const Loop *L) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001545 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001547 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548 if (StepChrec->getLoop() == L) {
1549 Operands.insert(Operands.end(), StepChrec->op_begin(),
1550 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001551 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001552 }
1553
1554 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001555 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556}
1557
Dan Gohmanc8a29272009-05-24 23:45:28 +00001558/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1559/// Simplify the expression as much as possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001560SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001561 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001562 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001563#ifndef NDEBUG
1564 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1565 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1566 getEffectiveSCEVType(Operands[0]->getType()) &&
1567 "SCEVAddRecExpr operand types don't match!");
1568#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001569
Dan Gohman7b560c42008-06-18 16:23:07 +00001570 if (Operands.back()->isZero()) {
1571 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001572 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001573 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001574
Dan Gohman42936882008-08-08 18:33:12 +00001575 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001576 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001577 const Loop* NestedLoop = NestedAR->getLoop();
1578 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001579 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1580 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001581 SCEVHandle NestedARHandle(NestedAR);
1582 Operands[0] = NestedAR->getStart();
1583 NestedOperands[0] = getAddRecExpr(Operands, L);
1584 return getAddRecExpr(NestedOperands, NestedLoop);
1585 }
1586 }
1587
Dan Gohmanbff6b582009-05-04 22:30:44 +00001588 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1589 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001590 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1591 return Result;
1592}
1593
Nick Lewycky711640a2007-11-25 22:41:31 +00001594SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1595 const SCEVHandle &RHS) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001596 SmallVector<SCEVHandle, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001597 Ops.push_back(LHS);
1598 Ops.push_back(RHS);
1599 return getSMaxExpr(Ops);
1600}
1601
Dan Gohman02ff9392009-06-14 22:47:23 +00001602SCEVHandle
1603ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001604 assert(!Ops.empty() && "Cannot get empty smax!");
1605 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001606#ifndef NDEBUG
1607 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1608 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1609 getEffectiveSCEVType(Ops[0]->getType()) &&
1610 "SCEVSMaxExpr operand types don't match!");
1611#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001612
1613 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001614 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001615
1616 // If there are any constants, fold them together.
1617 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001618 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001619 ++Idx;
1620 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001621 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001622 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001623 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001624 APIntOps::smax(LHSC->getValue()->getValue(),
1625 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001626 Ops[0] = getConstant(Fold);
1627 Ops.erase(Ops.begin()+1); // Erase the folded element
1628 if (Ops.size() == 1) return Ops[0];
1629 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001630 }
1631
1632 // If we are left with a constant -inf, strip it off.
1633 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1634 Ops.erase(Ops.begin());
1635 --Idx;
1636 }
1637 }
1638
1639 if (Ops.size() == 1) return Ops[0];
1640
1641 // Find the first SMax
1642 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1643 ++Idx;
1644
1645 // Check to see if one of the operands is an SMax. If so, expand its operands
1646 // onto our operand list, and recurse to simplify.
1647 if (Idx < Ops.size()) {
1648 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001649 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001650 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1651 Ops.erase(Ops.begin()+Idx);
1652 DeletedSMax = true;
1653 }
1654
1655 if (DeletedSMax)
1656 return getSMaxExpr(Ops);
1657 }
1658
1659 // Okay, check to see if the same value occurs in the operand list twice. If
1660 // so, delete one. Since we sorted the list, these values are required to
1661 // be adjacent.
1662 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1663 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1664 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1665 --i; --e;
1666 }
1667
1668 if (Ops.size() == 1) return Ops[0];
1669
1670 assert(!Ops.empty() && "Reduced smax down to nothing!");
1671
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001672 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001673 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001674 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001675 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1676 SCEVOps)];
1677 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1678 return Result;
1679}
1680
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001681SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1682 const SCEVHandle &RHS) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001683 SmallVector<SCEVHandle, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001684 Ops.push_back(LHS);
1685 Ops.push_back(RHS);
1686 return getUMaxExpr(Ops);
1687}
1688
Dan Gohman02ff9392009-06-14 22:47:23 +00001689SCEVHandle
1690ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001691 assert(!Ops.empty() && "Cannot get empty umax!");
1692 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001693#ifndef NDEBUG
1694 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1695 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1696 getEffectiveSCEVType(Ops[0]->getType()) &&
1697 "SCEVUMaxExpr operand types don't match!");
1698#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001699
1700 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001701 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001702
1703 // If there are any constants, fold them together.
1704 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001705 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001706 ++Idx;
1707 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001708 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001709 // We found two constants, fold them together!
1710 ConstantInt *Fold = ConstantInt::get(
1711 APIntOps::umax(LHSC->getValue()->getValue(),
1712 RHSC->getValue()->getValue()));
1713 Ops[0] = getConstant(Fold);
1714 Ops.erase(Ops.begin()+1); // Erase the folded element
1715 if (Ops.size() == 1) return Ops[0];
1716 LHSC = cast<SCEVConstant>(Ops[0]);
1717 }
1718
1719 // If we are left with a constant zero, strip it off.
1720 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1721 Ops.erase(Ops.begin());
1722 --Idx;
1723 }
1724 }
1725
1726 if (Ops.size() == 1) return Ops[0];
1727
1728 // Find the first UMax
1729 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1730 ++Idx;
1731
1732 // Check to see if one of the operands is a UMax. If so, expand its operands
1733 // onto our operand list, and recurse to simplify.
1734 if (Idx < Ops.size()) {
1735 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001736 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001737 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1738 Ops.erase(Ops.begin()+Idx);
1739 DeletedUMax = true;
1740 }
1741
1742 if (DeletedUMax)
1743 return getUMaxExpr(Ops);
1744 }
1745
1746 // Okay, check to see if the same value occurs in the operand list twice. If
1747 // so, delete one. Since we sorted the list, these values are required to
1748 // be adjacent.
1749 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1750 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1751 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1752 --i; --e;
1753 }
1754
1755 if (Ops.size() == 1) return Ops[0];
1756
1757 assert(!Ops.empty() && "Reduced umax down to nothing!");
1758
1759 // Okay, it looks like we really DO need a umax expr. Check to see if we
1760 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001761 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001762 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1763 SCEVOps)];
1764 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1765 return Result;
1766}
1767
Dan Gohman89f85052007-10-22 18:31:58 +00001768SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001770 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001771 if (isa<ConstantPointerNull>(V))
1772 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1774 if (Result == 0) Result = new SCEVUnknown(V);
1775 return Result;
1776}
1777
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001778//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779// Basic SCEV Analysis and PHI Idiom Recognition Code
1780//
1781
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001782/// isSCEVable - Test if values of the given type are analyzable within
1783/// the SCEV framework. This primarily includes integer types, and it
1784/// can optionally include pointer types if the ScalarEvolution class
1785/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001786bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001787 // Integers are always SCEVable.
1788 if (Ty->isInteger())
1789 return true;
1790
1791 // Pointers are SCEVable if TargetData information is available
1792 // to provide pointer size information.
1793 if (isa<PointerType>(Ty))
1794 return TD != NULL;
1795
1796 // Otherwise it's not SCEVable.
1797 return false;
1798}
1799
1800/// getTypeSizeInBits - Return the size in bits of the specified type,
1801/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001802uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001803 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1804
1805 // If we have a TargetData, use it!
1806 if (TD)
1807 return TD->getTypeSizeInBits(Ty);
1808
1809 // Otherwise, we support only integer types.
1810 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1811 return Ty->getPrimitiveSizeInBits();
1812}
1813
1814/// getEffectiveSCEVType - Return a type with the same bitwidth as
1815/// the given type and which represents how SCEV will treat the given
1816/// type, for which isSCEVable must return true. For pointer types,
1817/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001818const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001819 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1820
1821 if (Ty->isInteger())
1822 return Ty;
1823
1824 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1825 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001826}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001828SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001829 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001830}
1831
Dan Gohmand83d4af2009-05-04 22:20:30 +00001832/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001833/// computed.
1834bool ScalarEvolution::hasSCEV(Value *V) const {
1835 return Scalars.count(V);
1836}
1837
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001838/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1839/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001840SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001841 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842
Dan Gohmanbff6b582009-05-04 22:30:44 +00001843 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001844 if (I != Scalars.end()) return I->second;
1845 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001846 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001847 return S;
1848}
1849
Dan Gohman01c2ee72009-04-16 03:18:22 +00001850/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1851/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001852SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1853 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001854 Constant *C;
1855 if (Val == 0)
1856 C = Constant::getNullValue(Ty);
1857 else if (Ty->isFloatingPoint())
1858 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1859 APFloat::IEEEdouble, Val));
1860 else
1861 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001862 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001863}
1864
1865/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1866///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001867SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001868 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001869 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001870
1871 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001872 Ty = getEffectiveSCEVType(Ty);
1873 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001874}
1875
1876/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001877SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001878 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001879 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001880
1881 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001882 Ty = getEffectiveSCEVType(Ty);
1883 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001884 return getMinusSCEV(AllOnes, V);
1885}
1886
1887/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1888///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001889SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001890 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001891 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001892 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001893}
1894
1895/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1896/// input value to the specified type. If the type must be extended, it is zero
1897/// extended.
1898SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001899ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001900 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001901 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001902 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1903 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001904 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001905 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001906 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001907 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001908 return getTruncateExpr(V, Ty);
1909 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001910}
1911
1912/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1913/// input value to the specified type. If the type must be extended, it is sign
1914/// extended.
1915SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001916ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001917 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001918 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001919 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1920 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001921 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001922 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001923 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001924 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001925 return getTruncateExpr(V, Ty);
1926 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001927}
1928
Dan Gohmanac959332009-05-13 03:46:30 +00001929/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
1930/// input value to the specified type. If the type must be extended, it is zero
1931/// extended. The conversion must not be narrowing.
1932SCEVHandle
1933ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
1934 const Type *SrcTy = V->getType();
1935 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1936 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1937 "Cannot noop or zero extend with non-integer arguments!");
1938 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1939 "getNoopOrZeroExtend cannot truncate!");
1940 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1941 return V; // No conversion
1942 return getZeroExtendExpr(V, Ty);
1943}
1944
1945/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
1946/// input value to the specified type. If the type must be extended, it is sign
1947/// extended. The conversion must not be narrowing.
1948SCEVHandle
1949ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
1950 const Type *SrcTy = V->getType();
1951 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1952 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1953 "Cannot noop or sign extend with non-integer arguments!");
1954 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1955 "getNoopOrSignExtend cannot truncate!");
1956 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1957 return V; // No conversion
1958 return getSignExtendExpr(V, Ty);
1959}
1960
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001961/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
1962/// the input value to the specified type. If the type must be extended,
1963/// it is extended with unspecified bits. The conversion must not be
1964/// narrowing.
1965SCEVHandle
1966ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
1967 const Type *SrcTy = V->getType();
1968 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1969 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1970 "Cannot noop or any extend with non-integer arguments!");
1971 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1972 "getNoopOrAnyExtend cannot truncate!");
1973 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1974 return V; // No conversion
1975 return getAnyExtendExpr(V, Ty);
1976}
1977
Dan Gohmanac959332009-05-13 03:46:30 +00001978/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
1979/// input value to the specified type. The conversion must not be widening.
1980SCEVHandle
1981ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
1982 const Type *SrcTy = V->getType();
1983 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1984 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1985 "Cannot truncate or noop with non-integer arguments!");
1986 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
1987 "getTruncateOrNoop cannot extend!");
1988 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1989 return V; // No conversion
1990 return getTruncateExpr(V, Ty);
1991}
1992
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001993/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1994/// the specified instruction and replaces any references to the symbolic value
1995/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001996void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001997ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1998 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001999 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2000 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001 if (SI == Scalars.end()) return;
2002
2003 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002004 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005 if (NV == SI->second) return; // No change.
2006
2007 SI->second = NV; // Update the scalars map!
2008
2009 // Any instruction values that use this instruction might also need to be
2010 // updated!
2011 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2012 UI != E; ++UI)
2013 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2014}
2015
2016/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2017/// a loop header, making it a potential recurrence, or it doesn't.
2018///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002019SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002020 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002021 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002022 if (L->getHeader() == PN->getParent()) {
2023 // If it lives in the loop header, it has two incoming values, one
2024 // from outside the loop, and one from inside.
2025 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2026 unsigned BackEdge = IncomingEdge^1;
2027
2028 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002029 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 assert(Scalars.find(PN) == Scalars.end() &&
2031 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002032 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002033
2034 // Using this symbolic name for the PHI, analyze the value coming around
2035 // the back-edge.
2036 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2037
2038 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2039 // has a special value for the first iteration of the loop.
2040
2041 // If the value coming around the backedge is an add with the symbolic
2042 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002043 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002044 // If there is a single occurrence of the symbolic value, replace it
2045 // with a recurrence.
2046 unsigned FoundIndex = Add->getNumOperands();
2047 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2048 if (Add->getOperand(i) == SymbolicName)
2049 if (FoundIndex == e) {
2050 FoundIndex = i;
2051 break;
2052 }
2053
2054 if (FoundIndex != Add->getNumOperands()) {
2055 // Create an add with everything but the specified operand.
Dan Gohman02ff9392009-06-14 22:47:23 +00002056 SmallVector<SCEVHandle, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002057 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2058 if (i != FoundIndex)
2059 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002060 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061
2062 // This is not a valid addrec if the step amount is varying each
2063 // loop iteration, but is not itself an addrec in this loop.
2064 if (Accum->isLoopInvariant(L) ||
2065 (isa<SCEVAddRecExpr>(Accum) &&
2066 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2067 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002068 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069
2070 // Okay, for the entire analysis of this edge we assumed the PHI
2071 // to be symbolic. We now need to go back and update all of the
2072 // entries for the scalars that use the PHI (except for the PHI
2073 // itself) to use the new analyzed value instead of the "symbolic"
2074 // value.
2075 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2076 return PHISCEV;
2077 }
2078 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002079 } else if (const SCEVAddRecExpr *AddRec =
2080 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002081 // Otherwise, this could be a loop like this:
2082 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2083 // In this case, j = {1,+,1} and BEValue is j.
2084 // Because the other in-value of i (0) fits the evolution of BEValue
2085 // i really is an addrec evolution.
2086 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2087 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2088
2089 // If StartVal = j.start - j.stride, we can use StartVal as the
2090 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002091 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002092 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002093 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002094 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095
2096 // Okay, for the entire analysis of this edge we assumed the PHI
2097 // to be symbolic. We now need to go back and update all of the
2098 // entries for the scalars that use the PHI (except for the PHI
2099 // itself) to use the new analyzed value instead of the "symbolic"
2100 // value.
2101 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2102 return PHISCEV;
2103 }
2104 }
2105 }
2106
2107 return SymbolicName;
2108 }
2109
2110 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002111 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002112}
2113
Dan Gohman509cf4d2009-05-08 20:26:55 +00002114/// createNodeForGEP - Expand GEP instructions into add and multiply
2115/// operations. This allows them to be analyzed by regular SCEV code.
2116///
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002117SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002118
2119 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002120 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002121 // Don't attempt to analyze GEPs over unsized objects.
2122 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2123 return getUnknown(GEP);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002124 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002125 gep_type_iterator GTI = gep_type_begin(GEP);
2126 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2127 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002128 I != E; ++I) {
2129 Value *Index = *I;
2130 // Compute the (potentially symbolic) offset in bytes for this index.
2131 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2132 // For a struct, add the member offset.
2133 const StructLayout &SL = *TD->getStructLayout(STy);
2134 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2135 uint64_t Offset = SL.getElementOffset(FieldNo);
2136 TotalOffset = getAddExpr(TotalOffset,
2137 getIntegerSCEV(Offset, IntPtrTy));
2138 } else {
2139 // For an array, add the element offset, explicitly scaled.
2140 SCEVHandle LocalOffset = getSCEV(Index);
2141 if (!isa<PointerType>(LocalOffset->getType()))
2142 // Getelementptr indicies are signed.
2143 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2144 IntPtrTy);
2145 LocalOffset =
2146 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002147 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002148 IntPtrTy));
2149 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2150 }
2151 }
2152 return getAddExpr(getSCEV(Base), TotalOffset);
2153}
2154
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002155/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2156/// guaranteed to end in (at every loop iteration). It is, at the same time,
2157/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2158/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002159static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002160 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002161 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002162
Dan Gohmanc76b5452009-05-04 22:02:23 +00002163 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002164 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2165 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002166
Dan Gohmanc76b5452009-05-04 22:02:23 +00002167 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002168 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2169 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002170 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002171 }
2172
Dan Gohmanc76b5452009-05-04 22:02:23 +00002173 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002174 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2175 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002176 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002177 }
2178
Dan Gohmanc76b5452009-05-04 22:02:23 +00002179 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002180 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002181 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002182 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002183 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002184 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002185 }
2186
Dan Gohmanc76b5452009-05-04 22:02:23 +00002187 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002188 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002189 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2190 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002191 for (unsigned i = 1, e = M->getNumOperands();
2192 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002193 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002194 BitWidth);
2195 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002196 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002197
Dan Gohmanc76b5452009-05-04 22:02:23 +00002198 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002199 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002200 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002201 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002202 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002203 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002204 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002205
Dan Gohmanc76b5452009-05-04 22:02:23 +00002206 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002207 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002208 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00002209 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002210 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00002211 return MinOpRes;
2212 }
2213
Dan Gohmanc76b5452009-05-04 22:02:23 +00002214 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002215 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002216 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002217 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002218 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002219 return MinOpRes;
2220 }
2221
Nick Lewycky35b56022009-01-13 09:18:58 +00002222 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002223 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002224}
2225
2226/// createSCEV - We know that there is no SCEV for the specified value.
2227/// Analyze the expression.
2228///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002229SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002230 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002231 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002232
Dan Gohman3996f472008-06-22 19:56:46 +00002233 unsigned Opcode = Instruction::UserOp1;
2234 if (Instruction *I = dyn_cast<Instruction>(V))
2235 Opcode = I->getOpcode();
2236 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2237 Opcode = CE->getOpcode();
2238 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002239 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240
Dan Gohman3996f472008-06-22 19:56:46 +00002241 User *U = cast<User>(V);
2242 switch (Opcode) {
2243 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002244 return getAddExpr(getSCEV(U->getOperand(0)),
2245 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002246 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002247 return getMulExpr(getSCEV(U->getOperand(0)),
2248 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002249 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002250 return getUDivExpr(getSCEV(U->getOperand(0)),
2251 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002252 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002253 return getMinusSCEV(getSCEV(U->getOperand(0)),
2254 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002255 case Instruction::And:
2256 // For an expression like x&255 that merely masks off the high bits,
2257 // use zext(trunc(x)) as the SCEV expression.
2258 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002259 if (CI->isNullValue())
2260 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002261 if (CI->isAllOnesValue())
2262 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002263 const APInt &A = CI->getValue();
2264 unsigned Ones = A.countTrailingOnes();
2265 if (APIntOps::isMask(Ones, A))
2266 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002267 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2268 IntegerType::get(Ones)),
2269 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002270 }
2271 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002272 case Instruction::Or:
2273 // If the RHS of the Or is a constant, we may have something like:
2274 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2275 // optimizations will transparently handle this case.
2276 //
2277 // In order for this transformation to be safe, the LHS must be of the
2278 // form X*(2^n) and the Or constant must be less than 2^n.
2279 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2280 SCEVHandle LHS = getSCEV(U->getOperand(0));
2281 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002282 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002283 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002284 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002285 }
Dan Gohman3996f472008-06-22 19:56:46 +00002286 break;
2287 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002288 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002289 // If the RHS of the xor is a signbit, then this is just an add.
2290 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002291 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002292 return getAddExpr(getSCEV(U->getOperand(0)),
2293 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002294
2295 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002296 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002297 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002298
2299 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2300 // This is a variant of the check for xor with -1, and it handles
2301 // the case where instcombine has trimmed non-demanded bits out
2302 // of an xor with -1.
2303 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2304 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2305 if (BO->getOpcode() == Instruction::And &&
2306 LCI->getValue() == CI->getValue())
2307 if (const SCEVZeroExtendExpr *Z =
2308 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0))))
2309 return getZeroExtendExpr(getNotSCEV(Z->getOperand()),
2310 U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002311 }
2312 break;
2313
2314 case Instruction::Shl:
2315 // Turn shift left of a constant amount into a multiply.
2316 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2317 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2318 Constant *X = ConstantInt::get(
2319 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002320 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002321 }
2322 break;
2323
Nick Lewycky7fd27892008-07-07 06:15:49 +00002324 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002325 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002326 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2327 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2328 Constant *X = ConstantInt::get(
2329 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002330 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002331 }
2332 break;
2333
Dan Gohman53bf64a2009-04-21 02:26:00 +00002334 case Instruction::AShr:
2335 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2336 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2337 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2338 if (L->getOpcode() == Instruction::Shl &&
2339 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002340 unsigned BitWidth = getTypeSizeInBits(U->getType());
2341 uint64_t Amt = BitWidth - CI->getZExtValue();
2342 if (Amt == BitWidth)
2343 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2344 if (Amt > BitWidth)
2345 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002346 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002347 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002348 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002349 U->getType());
2350 }
2351 break;
2352
Dan Gohman3996f472008-06-22 19:56:46 +00002353 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002354 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002355
2356 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002357 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002358
2359 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002360 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002361
2362 case Instruction::BitCast:
2363 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002364 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002365 return getSCEV(U->getOperand(0));
2366 break;
2367
Dan Gohman01c2ee72009-04-16 03:18:22 +00002368 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002369 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002370 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002371 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002372
2373 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002374 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002375 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2376 U->getType());
2377
Dan Gohman509cf4d2009-05-08 20:26:55 +00002378 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002379 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002380 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002381
Dan Gohman3996f472008-06-22 19:56:46 +00002382 case Instruction::PHI:
2383 return createNodeForPHI(cast<PHINode>(U));
2384
2385 case Instruction::Select:
2386 // This could be a smax or umax that was lowered earlier.
2387 // Try to recover it.
2388 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2389 Value *LHS = ICI->getOperand(0);
2390 Value *RHS = ICI->getOperand(1);
2391 switch (ICI->getPredicate()) {
2392 case ICmpInst::ICMP_SLT:
2393 case ICmpInst::ICMP_SLE:
2394 std::swap(LHS, RHS);
2395 // fall through
2396 case ICmpInst::ICMP_SGT:
2397 case ICmpInst::ICMP_SGE:
2398 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002399 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002400 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002401 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002402 return getNotSCEV(getSMaxExpr(
2403 getNotSCEV(getSCEV(LHS)),
2404 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002405 break;
2406 case ICmpInst::ICMP_ULT:
2407 case ICmpInst::ICMP_ULE:
2408 std::swap(LHS, RHS);
2409 // fall through
2410 case ICmpInst::ICMP_UGT:
2411 case ICmpInst::ICMP_UGE:
2412 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002413 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002414 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2415 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002416 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2417 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002418 break;
2419 default:
2420 break;
2421 }
2422 }
2423
2424 default: // We cannot analyze this expression.
2425 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002426 }
2427
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002428 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429}
2430
2431
2432
2433//===----------------------------------------------------------------------===//
2434// Iteration Count Computation Code
2435//
2436
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002437/// getBackedgeTakenCount - If the specified loop has a predictable
2438/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2439/// object. The backedge-taken count is the number of times the loop header
2440/// will be branched to from within the loop. This is one less than the
2441/// trip count of the loop, since it doesn't count the first iteration,
2442/// when the header is branched to from outside the loop.
2443///
2444/// Note that it is not valid to call this method on a loop without a
2445/// loop-invariant backedge-taken count (see
2446/// hasLoopInvariantBackedgeTakenCount).
2447///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002448SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002449 return getBackedgeTakenInfo(L).Exact;
2450}
2451
2452/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2453/// return the least SCEV value that is known never to be less than the
2454/// actual backedge taken count.
2455SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2456 return getBackedgeTakenInfo(L).Max;
2457}
2458
2459const ScalarEvolution::BackedgeTakenInfo &
2460ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002461 // Initially insert a CouldNotCompute for this loop. If the insertion
2462 // succeeds, procede to actually compute a backedge-taken count and
2463 // update the value. The temporary CouldNotCompute value tells SCEV
2464 // code elsewhere that it shouldn't attempt to request a new
2465 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002466 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002467 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2468 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002469 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002470 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002471 assert(ItCount.Exact->isLoopInvariant(L) &&
2472 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473 "Computed trip count isn't loop invariant for loop!");
2474 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002475
Dan Gohmana9dba962009-04-27 20:16:15 +00002476 // Update the value in the map.
2477 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 } else if (isa<PHINode>(L->getHeader()->begin())) {
2479 // Only count loops that have phi nodes as not being computable.
2480 ++NumTripCountsNotComputed;
2481 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002482
2483 // Now that we know more about the trip count for this loop, forget any
2484 // existing SCEV values for PHI nodes in this loop since they are only
2485 // conservative estimates made without the benefit
2486 // of trip count information.
2487 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002488 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002490 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491}
2492
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002493/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002494/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002495/// ScalarEvolution's ability to compute a trip count, or if the loop
2496/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002497void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002498 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002499 forgetLoopPHIs(L);
2500}
2501
2502/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2503/// PHI nodes in the given loop. This is used when the trip count of
2504/// the loop may have changed.
2505void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002506 BasicBlock *Header = L->getHeader();
2507
Dan Gohman9fd4a002009-05-12 01:27:58 +00002508 // Push all Loop-header PHIs onto the Worklist stack, except those
2509 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2510 // a PHI either means that it has an unrecognized structure, or it's
2511 // a PHI that's in the progress of being computed by createNodeForPHI.
2512 // In the former case, additional loop trip count information isn't
2513 // going to change anything. In the later case, createNodeForPHI will
2514 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002515 SmallVector<Instruction *, 16> Worklist;
2516 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002517 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2518 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2519 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2520 Worklist.push_back(PN);
2521 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002522
2523 while (!Worklist.empty()) {
2524 Instruction *I = Worklist.pop_back_val();
2525 if (Scalars.erase(I))
2526 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2527 UI != UE; ++UI)
2528 Worklist.push_back(cast<Instruction>(UI));
2529 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002530}
2531
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002532/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2533/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002534ScalarEvolution::BackedgeTakenInfo
2535ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002536 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel7388a9a2009-06-05 23:08:56 +00002537 BasicBlock *ExitBlock = L->getExitBlock();
2538 if (!ExitBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002539 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002540
2541 // Okay, there is one exit block. Try to find the condition that causes the
2542 // loop to be exited.
Devang Patel7388a9a2009-06-05 23:08:56 +00002543 BasicBlock *ExitingBlock = L->getExitingBlock();
2544 if (!ExitingBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002545 return CouldNotCompute; // More than one block exiting!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002546
2547 // Okay, we've computed the exiting block. See what condition causes us to
2548 // exit.
2549 //
2550 // FIXME: we should be able to handle switch instructions (with a single exit)
2551 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002552 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2554
2555 // At this point, we know we have a conditional branch that determines whether
2556 // the loop is exited. However, we don't know if the branch is executed each
2557 // time through the loop. If not, then the execution count of the branch will
2558 // not be equal to the trip count of the loop.
2559 //
2560 // Currently we check for this by checking to see if the Exit branch goes to
2561 // the loop header. If so, we know it will always execute the same number of
2562 // times as the loop. We also handle the case where the exit block *is* the
2563 // loop header. This is common for un-rotated loops. More extensive analysis
2564 // could be done to handle more cases here.
2565 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2566 ExitBr->getSuccessor(1) != L->getHeader() &&
2567 ExitBr->getParent() != L->getHeader())
Dan Gohman0c850912009-06-06 14:37:11 +00002568 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569
2570 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2571
Eli Friedman459d7292009-05-09 12:32:42 +00002572 // If it's not an integer or pointer comparison then compute it the hard way.
2573 if (ExitCond == 0)
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002574 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002575 ExitBr->getSuccessor(0) == ExitBlock);
2576
2577 // If the condition was exit on true, convert the condition to exit on false
2578 ICmpInst::Predicate Cond;
2579 if (ExitBr->getSuccessor(1) == ExitBlock)
2580 Cond = ExitCond->getPredicate();
2581 else
2582 Cond = ExitCond->getInversePredicate();
2583
2584 // Handle common loops like: for (X = "string"; *X; ++X)
2585 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2586 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2587 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002588 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002589 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2590 }
2591
2592 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2593 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2594
2595 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00002596 LHS = getSCEVAtScope(LHS, L);
2597 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598
2599 // At this point, we would like to compute how many iterations of the
2600 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002601 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2602 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002603 std::swap(LHS, RHS);
2604 Cond = ICmpInst::getSwappedPredicate(Cond);
2605 }
2606
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002607 // If we have a comparison of a chrec against a constant, try to use value
2608 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002609 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2610 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002611 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00002612 // Form the constant range.
2613 ConstantRange CompRange(
2614 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002615
Eli Friedman459d7292009-05-09 12:32:42 +00002616 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2617 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002618 }
2619
2620 switch (Cond) {
2621 case ICmpInst::ICMP_NE: { // while (X != Y)
2622 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002623 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002624 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2625 break;
2626 }
2627 case ICmpInst::ICMP_EQ: {
2628 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002629 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002630 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2631 break;
2632 }
2633 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002634 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2635 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002636 break;
2637 }
2638 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002639 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2640 getNotSCEV(RHS), L, true);
2641 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002642 break;
2643 }
2644 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002645 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2646 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002647 break;
2648 }
2649 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002650 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2651 getNotSCEV(RHS), L, false);
2652 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002653 break;
2654 }
2655 default:
2656#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002657 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002658 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002659 errs() << "[unsigned] ";
2660 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002661 << Instruction::getOpcodeName(Instruction::ICmp)
2662 << " " << *RHS << "\n";
2663#endif
2664 break;
2665 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002666 return
2667 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2668 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669}
2670
2671static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002672EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2673 ScalarEvolution &SE) {
2674 SCEVHandle InVal = SE.getConstant(C);
2675 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002676 assert(isa<SCEVConstant>(Val) &&
2677 "Evaluation of SCEV at constant didn't fold correctly?");
2678 return cast<SCEVConstant>(Val)->getValue();
2679}
2680
2681/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2682/// and a GEP expression (missing the pointer index) indexing into it, return
2683/// the addressed element of the initializer or null if the index expression is
2684/// invalid.
2685static Constant *
2686GetAddressedElementFromGlobal(GlobalVariable *GV,
2687 const std::vector<ConstantInt*> &Indices) {
2688 Constant *Init = GV->getInitializer();
2689 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2690 uint64_t Idx = Indices[i]->getZExtValue();
2691 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2692 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2693 Init = cast<Constant>(CS->getOperand(Idx));
2694 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2695 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2696 Init = cast<Constant>(CA->getOperand(Idx));
2697 } else if (isa<ConstantAggregateZero>(Init)) {
2698 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2699 assert(Idx < STy->getNumElements() && "Bad struct index!");
2700 Init = Constant::getNullValue(STy->getElementType(Idx));
2701 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2702 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2703 Init = Constant::getNullValue(ATy->getElementType());
2704 } else {
2705 assert(0 && "Unknown constant aggregate type!");
2706 }
2707 return 0;
2708 } else {
2709 return 0; // Unknown initializer type
2710 }
2711 }
2712 return Init;
2713}
2714
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002715/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2716/// 'icmp op load X, cst', try to see if we can compute the backedge
2717/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002718SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002719ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2720 const Loop *L,
2721 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00002722 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723
2724 // Check to see if the loaded pointer is a getelementptr of a global.
2725 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00002726 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002727
2728 // Make sure that it is really a constant global we are gepping, with an
2729 // initializer, and make sure the first IDX is really 0.
2730 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2731 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2732 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2733 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00002734 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735
2736 // Okay, we allow one non-constant index into the GEP instruction.
2737 Value *VarIdx = 0;
2738 std::vector<ConstantInt*> Indexes;
2739 unsigned VarIdxNum = 0;
2740 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2741 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2742 Indexes.push_back(CI);
2743 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00002744 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 VarIdx = GEP->getOperand(i);
2746 VarIdxNum = i-2;
2747 Indexes.push_back(0);
2748 }
2749
2750 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2751 // Check to see if X is a loop variant variable value now.
2752 SCEVHandle Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00002753 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754
2755 // We can only recognize very limited forms of loop index expressions, in
2756 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002757 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2759 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2760 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00002761 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002762
2763 unsigned MaxSteps = MaxBruteForceIterations;
2764 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2765 ConstantInt *ItCst =
2766 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002767 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768
2769 // Form the GEP offset.
2770 Indexes[VarIdxNum] = Val;
2771
2772 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2773 if (Result == 0) break; // Cannot compute!
2774
2775 // Evaluate the condition for this iteration.
2776 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2777 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2778 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2779#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002780 errs() << "\n***\n*** Computed loop count " << *ItCst
2781 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2782 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002783#endif
2784 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002785 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786 }
2787 }
Dan Gohman0c850912009-06-06 14:37:11 +00002788 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002789}
2790
2791
2792/// CanConstantFold - Return true if we can constant fold an instruction of the
2793/// specified type, assuming that all operands were constants.
2794static bool CanConstantFold(const Instruction *I) {
2795 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2796 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2797 return true;
2798
2799 if (const CallInst *CI = dyn_cast<CallInst>(I))
2800 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002801 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 return false;
2803}
2804
2805/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2806/// in the loop that V is derived from. We allow arbitrary operations along the
2807/// way, but the operands of an operation must either be constants or a value
2808/// derived from a constant PHI. If this expression does not fit with these
2809/// constraints, return null.
2810static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2811 // If this is not an instruction, or if this is an instruction outside of the
2812 // loop, it can't be derived from a loop PHI.
2813 Instruction *I = dyn_cast<Instruction>(V);
2814 if (I == 0 || !L->contains(I->getParent())) return 0;
2815
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002816 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002817 if (L->getHeader() == I->getParent())
2818 return PN;
2819 else
2820 // We don't currently keep track of the control flow needed to evaluate
2821 // PHIs, so we cannot handle PHIs inside of loops.
2822 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002823 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002824
2825 // If we won't be able to constant fold this expression even if the operands
2826 // are constants, return early.
2827 if (!CanConstantFold(I)) return 0;
2828
2829 // Otherwise, we can evaluate this instruction if all of its operands are
2830 // constant or derived from a PHI node themselves.
2831 PHINode *PHI = 0;
2832 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2833 if (!(isa<Constant>(I->getOperand(Op)) ||
2834 isa<GlobalValue>(I->getOperand(Op)))) {
2835 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2836 if (P == 0) return 0; // Not evolving from PHI
2837 if (PHI == 0)
2838 PHI = P;
2839 else if (PHI != P)
2840 return 0; // Evolving from multiple different PHIs.
2841 }
2842
2843 // This is a expression evolving from a constant PHI!
2844 return PHI;
2845}
2846
2847/// EvaluateExpression - Given an expression that passes the
2848/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2849/// in the loop has the value PHIVal. If we can't fold this expression for some
2850/// reason, return null.
2851static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2852 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002853 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002854 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002855 Instruction *I = cast<Instruction>(V);
2856
2857 std::vector<Constant*> Operands;
2858 Operands.resize(I->getNumOperands());
2859
2860 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2861 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2862 if (Operands[i] == 0) return 0;
2863 }
2864
Chris Lattnerd6e56912007-12-10 22:53:04 +00002865 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2866 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2867 &Operands[0], Operands.size());
2868 else
2869 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2870 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871}
2872
2873/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2874/// in the header of its containing loop, we know the loop executes a
2875/// constant number of times, and the PHI node is just a recurrence
2876/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002877Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002878getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 std::map<PHINode*, Constant*>::iterator I =
2880 ConstantEvolutionLoopExitValue.find(PN);
2881 if (I != ConstantEvolutionLoopExitValue.end())
2882 return I->second;
2883
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002884 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002885 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2886
2887 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2888
2889 // Since the loop is canonicalized, the PHI node must have two entries. One
2890 // entry must be a constant (coming in from outside of the loop), and the
2891 // second must be derived from the same PHI.
2892 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2893 Constant *StartCST =
2894 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2895 if (StartCST == 0)
2896 return RetVal = 0; // Must be a constant.
2897
2898 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2899 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2900 if (PN2 != PN)
2901 return RetVal = 0; // Not derived from same PHI.
2902
2903 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002904 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2906
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002907 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002908 unsigned IterationNum = 0;
2909 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2910 if (IterationNum == NumIterations)
2911 return RetVal = PHIVal; // Got exit value!
2912
2913 // Compute the value of the PHI node for the next iteration.
2914 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2915 if (NextPHI == PHIVal)
2916 return RetVal = NextPHI; // Stopped evolving!
2917 if (NextPHI == 0)
2918 return 0; // Couldn't evaluate!
2919 PHIVal = NextPHI;
2920 }
2921}
2922
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002923/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002924/// constant number of times (the condition evolves only from constants),
2925/// try to evaluate a few iterations of the loop until we get the exit
2926/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00002927/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002928SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002929ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002930 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00002931 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932
2933 // Since the loop is canonicalized, the PHI node must have two entries. One
2934 // entry must be a constant (coming in from outside of the loop), and the
2935 // second must be derived from the same PHI.
2936 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2937 Constant *StartCST =
2938 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00002939 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940
2941 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2942 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00002943 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944
2945 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2946 // the loop symbolically to determine when the condition gets a value of
2947 // "ExitWhen".
2948 unsigned IterationNum = 0;
2949 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2950 for (Constant *PHIVal = StartCST;
2951 IterationNum != MaxIterations; ++IterationNum) {
2952 ConstantInt *CondVal =
2953 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2954
2955 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00002956 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002957
2958 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2959 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2960 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002961 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002962 }
2963
2964 // Compute the value of the PHI node for the next iteration.
2965 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2966 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00002967 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002968 PHIVal = NextPHI;
2969 }
2970
2971 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00002972 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002973}
2974
Dan Gohmandd40e9a2009-05-08 20:38:54 +00002975/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2976/// at the specified scope in the program. The L value specifies a loop
2977/// nest to evaluate the expression at, where null is the top-level or a
2978/// specified loop is immediately inside of the loop.
2979///
2980/// This method can be used to compute the exit value for a variable defined
2981/// in a loop by querying what the value will hold in the parent loop.
2982///
Dan Gohmanaff14d62009-05-24 23:25:42 +00002983/// In the case that a relevant loop exit value cannot be computed, the
2984/// original value V is returned.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002985SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 // FIXME: this should be turned into a virtual method on SCEV!
2987
2988 if (isa<SCEVConstant>(V)) return V;
2989
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002990 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002991 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002992 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002993 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002994 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2996 if (PHINode *PN = dyn_cast<PHINode>(I))
2997 if (PN->getParent() == LI->getHeader()) {
2998 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002999 // to see if the loop that contains it has a known backedge-taken
3000 // count. If so, we may be able to force computation of the exit
3001 // value.
3002 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003003 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003004 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003005 // Okay, we know how many times the containing loop executes. If
3006 // this is a constant evolving PHI node, get the final value at
3007 // the specified iteration number.
3008 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003009 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003011 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003012 }
3013 }
3014
3015 // Okay, this is an expression that we cannot symbolically evaluate
3016 // into a SCEV. Check to see if it's possible to symbolically evaluate
3017 // the arguments into constants, and if so, try to constant propagate the
3018 // result. This is particularly useful for computing loop exit values.
3019 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003020 // Check to see if we've folded this instruction at this loop before.
3021 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3022 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3023 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3024 if (!Pair.second)
3025 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 std::vector<Constant*> Operands;
3028 Operands.reserve(I->getNumOperands());
3029 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3030 Value *Op = I->getOperand(i);
3031 if (Constant *C = dyn_cast<Constant>(Op)) {
3032 Operands.push_back(C);
3033 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003034 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003035 // non-integer and non-pointer, don't even try to analyze them
3036 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003037 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003038 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003039
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003040 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003041 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003042 Constant *C = SC->getValue();
3043 if (C->getType() != Op->getType())
3044 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3045 Op->getType(),
3046 false),
3047 C, Op->getType());
3048 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003049 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003050 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3051 if (C->getType() != Op->getType())
3052 C =
3053 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3054 Op->getType(),
3055 false),
3056 C, Op->getType());
3057 Operands.push_back(C);
3058 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003059 return V;
3060 } else {
3061 return V;
3062 }
3063 }
3064 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00003065
3066 Constant *C;
3067 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3068 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3069 &Operands[0], Operands.size());
3070 else
3071 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3072 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003073 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003074 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 }
3076 }
3077
3078 // This is some other type of SCEVUnknown, just return it.
3079 return V;
3080 }
3081
Dan Gohmanc76b5452009-05-04 22:02:23 +00003082 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003083 // Avoid performing the look-up in the common case where the specified
3084 // expression has no loop-variant portions.
3085 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3086 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3087 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003088 // Okay, at least one of these operands is loop variant but might be
3089 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman02ff9392009-06-14 22:47:23 +00003090 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003091 NewOps.push_back(OpAtScope);
3092
3093 for (++i; i != e; ++i) {
3094 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095 NewOps.push_back(OpAtScope);
3096 }
3097 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003098 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003099 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003100 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003101 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003102 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003103 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003104 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003105 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003106 }
3107 }
3108 // If we got here, all operands are loop invariant.
3109 return Comm;
3110 }
3111
Dan Gohmanc76b5452009-05-04 22:02:23 +00003112 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003113 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003114 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003115 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3116 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003117 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118 }
3119
3120 // If this is a loop recurrence for a loop that does not contain L, then we
3121 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003122 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003123 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3124 // To evaluate this recurrence, we need to know how many times the AddRec
3125 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003126 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003127 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128
Eli Friedman7489ec92008-08-04 23:49:06 +00003129 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003130 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003132 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003133 }
3134
Dan Gohmanc76b5452009-05-04 22:02:23 +00003135 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003136 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003137 if (Op == Cast->getOperand())
3138 return Cast; // must be loop invariant
3139 return getZeroExtendExpr(Op, Cast->getType());
3140 }
3141
Dan Gohmanc76b5452009-05-04 22:02:23 +00003142 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003143 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003144 if (Op == Cast->getOperand())
3145 return Cast; // must be loop invariant
3146 return getSignExtendExpr(Op, Cast->getType());
3147 }
3148
Dan Gohmanc76b5452009-05-04 22:02:23 +00003149 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003150 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003151 if (Op == Cast->getOperand())
3152 return Cast; // must be loop invariant
3153 return getTruncateExpr(Op, Cast->getType());
3154 }
3155
3156 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003157 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003158}
3159
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003160/// getSCEVAtScope - This is a convenience function which does
3161/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003162SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3163 return getSCEVAtScope(getSCEV(V), L);
3164}
3165
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003166/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3167/// following equation:
3168///
3169/// A * X = B (mod N)
3170///
3171/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3172/// A and B isn't important.
3173///
3174/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3175static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3176 ScalarEvolution &SE) {
3177 uint32_t BW = A.getBitWidth();
3178 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3179 assert(A != 0 && "A must be non-zero.");
3180
3181 // 1. D = gcd(A, N)
3182 //
3183 // The gcd of A and N may have only one prime factor: 2. The number of
3184 // trailing zeros in A is its multiplicity
3185 uint32_t Mult2 = A.countTrailingZeros();
3186 // D = 2^Mult2
3187
3188 // 2. Check if B is divisible by D.
3189 //
3190 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3191 // is not less than multiplicity of this prime factor for D.
3192 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003193 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003194
3195 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3196 // modulo (N / D).
3197 //
3198 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3199 // bit width during computations.
3200 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3201 APInt Mod(BW + 1, 0);
3202 Mod.set(BW - Mult2); // Mod = N / D
3203 APInt I = AD.multiplicativeInverse(Mod);
3204
3205 // 4. Compute the minimum unsigned root of the equation:
3206 // I * (B / D) mod (N / D)
3207 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3208
3209 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3210 // bits.
3211 return SE.getConstant(Result.trunc(BW));
3212}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213
3214/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3215/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3216/// might be the same) or two SCEVCouldNotCompute objects.
3217///
3218static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00003219SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003221 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3222 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3223 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224
3225 // We currently can only solve this if the coefficients are constants.
3226 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003227 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003228 return std::make_pair(CNC, CNC);
3229 }
3230
3231 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3232 const APInt &L = LC->getValue()->getValue();
3233 const APInt &M = MC->getValue()->getValue();
3234 const APInt &N = NC->getValue()->getValue();
3235 APInt Two(BitWidth, 2);
3236 APInt Four(BitWidth, 4);
3237
3238 {
3239 using namespace APIntOps;
3240 const APInt& C = L;
3241 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3242 // The B coefficient is M-N/2
3243 APInt B(M);
3244 B -= sdiv(N,Two);
3245
3246 // The A coefficient is N/2
3247 APInt A(N.sdiv(Two));
3248
3249 // Compute the B^2-4ac term.
3250 APInt SqrtTerm(B);
3251 SqrtTerm *= B;
3252 SqrtTerm -= Four * (A * C);
3253
3254 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3255 // integer value or else APInt::sqrt() will assert.
3256 APInt SqrtVal(SqrtTerm.sqrt());
3257
3258 // Compute the two solutions for the quadratic formula.
3259 // The divisions must be performed as signed divisions.
3260 APInt NegB(-B);
3261 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003262 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003263 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003264 return std::make_pair(CNC, CNC);
3265 }
3266
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003267 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3268 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3269
Dan Gohman89f85052007-10-22 18:31:58 +00003270 return std::make_pair(SE.getConstant(Solution1),
3271 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003272 } // end APIntOps namespace
3273}
3274
3275/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003276/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003277SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003279 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003280 // If the value is already zero, the branch will execute zero times.
3281 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003282 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003283 }
3284
Dan Gohmanbff6b582009-05-04 22:30:44 +00003285 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003286 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003287 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003288
3289 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003290 // If this is an affine expression, the execution count of this branch is
3291 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003293 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003294 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003295 // equivalent to:
3296 //
3297 // Step*N = -Start (mod 2^BW)
3298 //
3299 // where BW is the common bit width of Start and Step.
3300
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003301 // Get the initial value for the loop.
3302 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003303 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003304
Dan Gohmanc76b5452009-05-04 22:02:23 +00003305 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003306 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003307
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003308 // First, handle unitary steps.
3309 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003310 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003311 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3312 return Start; // N = Start (as unsigned)
3313
3314 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003315 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003316 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003317 -StartC->getValue()->getValue(),
3318 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003319 }
3320 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3321 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3322 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003323 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3324 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003325 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3326 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003327 if (R1) {
3328#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003329 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3330 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003331#endif
3332 // Pick the smallest positive root value.
3333 if (ConstantInt *CB =
3334 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3335 R1->getValue(), R2->getValue()))) {
3336 if (CB->getZExtValue() == false)
3337 std::swap(R1, R2); // R1 is the minimum root now.
3338
3339 // We can only use this value if the chrec ends up with an exact zero
3340 // value at this index. When solving for "X*X != 5", for example, we
3341 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003342 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003343 if (Val->isZero())
3344 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003345 }
3346 }
3347 }
3348
Dan Gohman0c850912009-06-06 14:37:11 +00003349 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003350}
3351
3352/// HowFarToNonZero - Return the number of times a backedge checking the
3353/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003354/// CouldNotCompute
Dan Gohmanbff6b582009-05-04 22:30:44 +00003355SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356 // Loops that look like: while (X == 0) are very strange indeed. We don't
3357 // handle them yet except for the trivial case. This could be expanded in the
3358 // future as needed.
3359
3360 // If the value is a constant, check to see if it is known to be non-zero
3361 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003362 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003363 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003364 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003365 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003366 }
3367
3368 // We could implement others, but I really doubt anyone writes loops like
3369 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003370 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003371}
3372
Dan Gohmanab157b22009-05-18 15:36:09 +00003373/// getLoopPredecessor - If the given loop's header has exactly one unique
3374/// predecessor outside the loop, return it. Otherwise return null.
3375///
3376BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3377 BasicBlock *Header = L->getHeader();
3378 BasicBlock *Pred = 0;
3379 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3380 PI != E; ++PI)
3381 if (!L->contains(*PI)) {
3382 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3383 Pred = *PI;
3384 }
3385 return Pred;
3386}
3387
Dan Gohman1cddf972008-09-15 22:18:04 +00003388/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3389/// (which may not be an immediate predecessor) which has exactly one
3390/// successor from which BB is reachable, or null if no such block is
3391/// found.
3392///
3393BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003394ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003395 // If the block has a unique predecessor, then there is no path from the
3396 // predecessor to the block that does not go through the direct edge
3397 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003398 if (BasicBlock *Pred = BB->getSinglePredecessor())
3399 return Pred;
3400
3401 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003402 // If the header has a unique predecessor outside the loop, it must be
3403 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003404 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003405 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003406
3407 return 0;
3408}
3409
Dan Gohmancacd2012009-02-12 22:19:27 +00003410/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003411/// a conditional between LHS and RHS. This is used to help avoid max
3412/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003413bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003414 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003415 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003416 // Interpret a null as meaning no loop, where there is obviously no guard
3417 // (interprocedural conditions notwithstanding).
3418 if (!L) return false;
3419
Dan Gohmanab157b22009-05-18 15:36:09 +00003420 BasicBlock *Predecessor = getLoopPredecessor(L);
3421 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003422
Dan Gohmanab157b22009-05-18 15:36:09 +00003423 // Starting at the loop predecessor, climb up the predecessor chain, as long
3424 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003425 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003426 for (; Predecessor;
3427 PredecessorDest = Predecessor,
3428 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003429
3430 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003431 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003432 if (!LoopEntryPredicate ||
3433 LoopEntryPredicate->isUnconditional())
3434 continue;
3435
3436 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3437 if (!ICI) continue;
3438
3439 // Now that we found a conditional branch that dominates the loop, check to
3440 // see if it is the comparison we are looking for.
3441 Value *PreCondLHS = ICI->getOperand(0);
3442 Value *PreCondRHS = ICI->getOperand(1);
3443 ICmpInst::Predicate Cond;
Dan Gohmanab157b22009-05-18 15:36:09 +00003444 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohmanab678fb2008-08-12 20:17:31 +00003445 Cond = ICI->getPredicate();
3446 else
3447 Cond = ICI->getInversePredicate();
3448
Dan Gohmancacd2012009-02-12 22:19:27 +00003449 if (Cond == Pred)
3450 ; // An exact match.
3451 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3452 ; // The actual condition is beyond sufficient.
3453 else
3454 // Check a few special cases.
3455 switch (Cond) {
3456 case ICmpInst::ICMP_UGT:
3457 if (Pred == ICmpInst::ICMP_ULT) {
3458 std::swap(PreCondLHS, PreCondRHS);
3459 Cond = ICmpInst::ICMP_ULT;
3460 break;
3461 }
3462 continue;
3463 case ICmpInst::ICMP_SGT:
3464 if (Pred == ICmpInst::ICMP_SLT) {
3465 std::swap(PreCondLHS, PreCondRHS);
3466 Cond = ICmpInst::ICMP_SLT;
3467 break;
3468 }
3469 continue;
3470 case ICmpInst::ICMP_NE:
3471 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3472 // so check for this case by checking if the NE is comparing against
3473 // a minimum or maximum constant.
3474 if (!ICmpInst::isTrueWhenEqual(Pred))
3475 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3476 const APInt &A = CI->getValue();
3477 switch (Pred) {
3478 case ICmpInst::ICMP_SLT:
3479 if (A.isMaxSignedValue()) break;
3480 continue;
3481 case ICmpInst::ICMP_SGT:
3482 if (A.isMinSignedValue()) break;
3483 continue;
3484 case ICmpInst::ICMP_ULT:
3485 if (A.isMaxValue()) break;
3486 continue;
3487 case ICmpInst::ICMP_UGT:
3488 if (A.isMinValue()) break;
3489 continue;
3490 default:
3491 continue;
3492 }
3493 Cond = ICmpInst::ICMP_NE;
3494 // NE is symmetric but the original comparison may not be. Swap
3495 // the operands if necessary so that they match below.
3496 if (isa<SCEVConstant>(LHS))
3497 std::swap(PreCondLHS, PreCondRHS);
3498 break;
3499 }
3500 continue;
3501 default:
3502 // We weren't able to reconcile the condition.
3503 continue;
3504 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003505
3506 if (!PreCondLHS->getType()->isInteger()) continue;
3507
3508 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3509 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3510 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003511 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3512 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003513 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003514 }
3515
Dan Gohmanab678fb2008-08-12 20:17:31 +00003516 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003517}
3518
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519/// HowManyLessThans - Return the number of times a backedge containing the
3520/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003521/// CouldNotCompute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003522ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003523HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3524 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003525 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00003526 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003527
Dan Gohmanbff6b582009-05-04 22:30:44 +00003528 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003529 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003530 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003531
3532 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003533 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003534 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3535 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3536 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3537
3538 // TODO: handle non-constant strides.
3539 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3540 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00003541 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00003542 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003543 // With unit stride, the iteration never steps past the limit value.
3544 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3545 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3546 // Test whether a positive iteration iteration can step past the limit
3547 // value and past the maximum value for its type in a single step.
3548 if (isSigned) {
3549 APInt Max = APInt::getSignedMaxValue(BitWidth);
3550 if ((Max - CStep->getValue()->getValue())
3551 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003552 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003553 } else {
3554 APInt Max = APInt::getMaxValue(BitWidth);
3555 if ((Max - CStep->getValue()->getValue())
3556 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003557 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003558 }
3559 } else
3560 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00003561 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003562 } else
3563 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00003564 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003565
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003566 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3567 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3568 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003569 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003570
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003571 // First, we get the value of the LHS in the first iteration: n
3572 SCEVHandle Start = AddRec->getOperand(0);
3573
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003574 // Determine the minimum constant start value.
3575 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3576 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3577 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003578
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003579 // If we know that the condition is true in order to enter the loop,
3580 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00003581 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3582 // the division must round up.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003583 SCEVHandle End = RHS;
3584 if (!isLoopGuardedByCond(L,
3585 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3586 getMinusSCEV(Start, Step), RHS))
3587 End = isSigned ? getSMaxExpr(RHS, Start)
3588 : getUMaxExpr(RHS, Start);
3589
3590 // Determine the maximum constant end value.
3591 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3592 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3593 APInt::getMaxValue(BitWidth));
3594
3595 // Finally, we subtract these two values and divide, rounding up, to get
3596 // the number of times the backedge is executed.
3597 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3598 getAddExpr(Step, NegOne)),
3599 Step);
3600
3601 // The maximum backedge count is similar, except using the minimum start
3602 // value and the maximum end value.
3603 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3604 MinStart),
3605 getAddExpr(Step, NegOne)),
3606 Step);
3607
3608 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003609 }
3610
Dan Gohman0c850912009-06-06 14:37:11 +00003611 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003612}
3613
3614/// getNumIterationsInRange - Return the number of iterations of this loop that
3615/// produce values in the specified constant range. Another way of looking at
3616/// this is that it returns the first iteration number where the value is not in
3617/// the condition, thus computing the exit count. If the iteration count can't
3618/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003619SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3620 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003621 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003622 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003623
3624 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003625 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003626 if (!SC->getValue()->isZero()) {
Dan Gohman02ff9392009-06-14 22:47:23 +00003627 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003628 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3629 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003630 if (const SCEVAddRecExpr *ShiftedAddRec =
3631 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003632 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003633 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003634 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003635 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003636 }
3637
3638 // The only time we can solve this is when we have all constant indices.
3639 // Otherwise, we cannot determine the overflow conditions.
3640 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3641 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003642 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003643
3644
3645 // Okay at this point we know that all elements of the chrec are constants and
3646 // that the start element is zero.
3647
3648 // First check to see if the range contains zero. If not, the first
3649 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003650 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003651 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003652 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003653
3654 if (isAffine()) {
3655 // If this is an affine expression then we have this situation:
3656 // Solve {0,+,A} in Range === Ax in Range
3657
3658 // We know that zero is in the range. If A is positive then we know that
3659 // the upper value of the range must be the first possible exit value.
3660 // If A is negative then the lower of the range is the last possible loop
3661 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003662 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003663 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3664 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3665
3666 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003667 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003668 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3669
3670 // Evaluate at the exit value. If we really did fall out of the valid
3671 // range, then we computed our trip count, otherwise wrap around or other
3672 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003673 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003674 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003675 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003676
3677 // Ensure that the previous value is in the range. This is a sanity check.
3678 assert(Range.contains(
3679 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003680 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003681 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003682 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003683 } else if (isQuadratic()) {
3684 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3685 // quadratic equation to solve it. To do this, we must frame our problem in
3686 // terms of figuring out when zero is crossed, instead of when
3687 // Range.getUpper() is crossed.
Dan Gohman02ff9392009-06-14 22:47:23 +00003688 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003689 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3690 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691
3692 // Next, solve the constructed addrec
3693 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003694 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003695 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3696 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003697 if (R1) {
3698 // Pick the smallest positive root value.
3699 if (ConstantInt *CB =
3700 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3701 R1->getValue(), R2->getValue()))) {
3702 if (CB->getZExtValue() == false)
3703 std::swap(R1, R2); // R1 is the minimum root now.
3704
3705 // Make sure the root is not off by one. The returned iteration should
3706 // not be in the range, but the previous one should be. When solving
3707 // for "X*X < 5", for example, we should not return a root of 2.
3708 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003709 R1->getValue(),
3710 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003711 if (Range.contains(R1Val->getValue())) {
3712 // The next iteration must be out of the range...
3713 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3714
Dan Gohman89f85052007-10-22 18:31:58 +00003715 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003716 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003717 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003718 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003719 }
3720
3721 // If R1 was not in the range, then it is a good return value. Make
3722 // sure that R1-1 WAS in the range though, just in case.
3723 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003724 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003725 if (Range.contains(R1Val->getValue()))
3726 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003727 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003728 }
3729 }
3730 }
3731
Dan Gohman0ad08b02009-04-18 17:58:19 +00003732 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003733}
3734
3735
3736
3737//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003738// SCEVCallbackVH Class Implementation
3739//===----------------------------------------------------------------------===//
3740
Dan Gohman999d14e2009-05-19 19:22:47 +00003741void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003742 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3743 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3744 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003745 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3746 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003747 SE->Scalars.erase(getValPtr());
3748 // this now dangles!
3749}
3750
Dan Gohman999d14e2009-05-19 19:22:47 +00003751void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003752 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3753
3754 // Forget all the expressions associated with users of the old value,
3755 // so that future queries will recompute the expressions using the new
3756 // value.
3757 SmallVector<User *, 16> Worklist;
3758 Value *Old = getValPtr();
3759 bool DeleteOld = false;
3760 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3761 UI != UE; ++UI)
3762 Worklist.push_back(*UI);
3763 while (!Worklist.empty()) {
3764 User *U = Worklist.pop_back_val();
3765 // Deleting the Old value will cause this to dangle. Postpone
3766 // that until everything else is done.
3767 if (U == Old) {
3768 DeleteOld = true;
3769 continue;
3770 }
3771 if (PHINode *PN = dyn_cast<PHINode>(U))
3772 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003773 if (Instruction *I = dyn_cast<Instruction>(U))
3774 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003775 if (SE->Scalars.erase(U))
3776 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3777 UI != UE; ++UI)
3778 Worklist.push_back(*UI);
3779 }
3780 if (DeleteOld) {
3781 if (PHINode *PN = dyn_cast<PHINode>(Old))
3782 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003783 if (Instruction *I = dyn_cast<Instruction>(Old))
3784 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003785 SE->Scalars.erase(Old);
3786 // this now dangles!
3787 }
3788 // this may dangle!
3789}
3790
Dan Gohman999d14e2009-05-19 19:22:47 +00003791ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00003792 : CallbackVH(V), SE(se) {}
3793
3794//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003795// ScalarEvolution Class Implementation
3796//===----------------------------------------------------------------------===//
3797
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003798ScalarEvolution::ScalarEvolution()
Dan Gohman0c850912009-06-06 14:37:11 +00003799 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003800}
3801
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003802bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003803 this->F = &F;
3804 LI = &getAnalysis<LoopInfo>();
3805 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003806 return false;
3807}
3808
3809void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003810 Scalars.clear();
3811 BackedgeTakenCounts.clear();
3812 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00003813 ValuesAtScopes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003814}
3815
3816void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3817 AU.setPreservesAll();
3818 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003819}
3820
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003821bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003822 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003823}
3824
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003825static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003826 const Loop *L) {
3827 // Print all inner loops first
3828 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3829 PrintLoopInfo(OS, SE, *I);
3830
Nick Lewyckye5da1912008-01-02 02:49:20 +00003831 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832
Devang Patel02451fa2007-08-21 00:31:24 +00003833 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003834 L->getExitBlocks(ExitBlocks);
3835 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003836 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003837
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003838 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3839 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003840 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003841 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003842 }
3843
Nick Lewyckye5da1912008-01-02 02:49:20 +00003844 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003845}
3846
Dan Gohman13058cc2009-04-21 00:47:46 +00003847void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003848 // ScalarEvolution's implementaiton of the print method is to print
3849 // out SCEV values of all instructions that are interesting. Doing
3850 // this potentially causes it to create new SCEV objects though,
3851 // which technically conflicts with the const qualifier. This isn't
3852 // observable from outside the class though (the hasSCEV function
3853 // notwithstanding), so casting away the const isn't dangerous.
3854 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003855
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003856 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003857 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003858 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003859 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003860 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003861 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003862 SV->print(OS);
3863 OS << "\t\t";
3864
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003865 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003866 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003867 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00003868 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869 OS << "<<Unknown>>";
3870 } else {
3871 OS << *ExitValue;
3872 }
3873 }
3874
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003875 OS << "\n";
3876 }
3877
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003878 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3879 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3880 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003881}
Dan Gohman13058cc2009-04-21 00:47:46 +00003882
3883void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3884 raw_os_ostream OS(o);
3885 print(OS, M);
3886}