blob: 2b5ca520c21df30b7eeb935a79a9cb0b52706851 [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 <ostream>
84#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085using namespace llvm;
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman089efff2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman089efff2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104char ScalarEvolution::ID = 0;
105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122}
123
Dan Gohman7b560c42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130
131SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000132SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
136 return false;
137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
141 return 0;
142}
143
144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000151 const SCEVHandle &Conc,
152 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 return this;
154}
155
Dan Gohman13058cc2009-04-21 00:47:46 +0000156void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 OS << "***COULDNOTCOMPUTE***";
158}
159
160bool SCEVCouldNotCompute::classof(const SCEV *S) {
161 return S->getSCEVType() == scCouldNotCompute;
162}
163
164
165// SCEVConstants - Only allow the creation of one SCEVConstant for any
166// particular value. Don't use a SCEVHandle here, or else the object will
167// never be deleted!
168static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
169
170
171SCEVConstant::~SCEVConstant() {
172 SCEVConstants->erase(V);
173}
174
Dan Gohman89f85052007-10-22 18:31:58 +0000175SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 SCEVConstant *&R = (*SCEVConstants)[V];
177 if (R == 0) R = new SCEVConstant(V);
178 return R;
179}
180
Dan Gohman89f85052007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
182 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183}
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185const Type *SCEVConstant::getType() const { return V->getType(); }
186
Dan Gohman13058cc2009-04-21 00:47:46 +0000187void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 WriteAsOperand(OS, V, false);
189}
190
Dan Gohman2a381532009-04-21 01:25:57 +0000191SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
192 const SCEVHandle &op, const Type *ty)
193 : SCEV(SCEVTy), Op(op), Ty(ty) {}
194
195SCEVCastExpr::~SCEVCastExpr() {}
196
197bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
198 return Op->dominates(BB, DT);
199}
200
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000204static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 SCEVTruncateExpr*> > SCEVTruncates;
206
207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000208 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000209 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
210 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212}
213
214SCEVTruncateExpr::~SCEVTruncateExpr() {
215 SCEVTruncates->erase(std::make_pair(Op, Ty));
216}
217
Dan Gohman13058cc2009-04-21 00:47:46 +0000218void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220}
221
222// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223// particular input. Don't use a SCEVHandle here, or else the object will never
224// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000225static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 SCEVZeroExtendExpr*> > SCEVZeroExtends;
227
228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000229 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000230 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
231 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233}
234
235SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
236 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
237}
238
Dan Gohman13058cc2009-04-21 00:47:46 +0000239void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000240 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241}
242
243// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
244// particular input. Don't use a SCEVHandle here, or else the object will never
245// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000246static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 SCEVSignExtendExpr*> > SCEVSignExtends;
248
249SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000250 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000251 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
252 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254}
255
256SCEVSignExtendExpr::~SCEVSignExtendExpr() {
257 SCEVSignExtends->erase(std::make_pair(Op, Ty));
258}
259
Dan Gohman13058cc2009-04-21 00:47:46 +0000260void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000261 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262}
263
264// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
265// particular input. Don't use a SCEVHandle here, or else the object will never
266// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000267static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 SCEVCommutativeExpr*> > SCEVCommExprs;
269
270SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000271 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
272 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273}
274
Dan Gohman13058cc2009-04-21 00:47:46 +0000275void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
277 const char *OpStr = getOperationStr();
278 OS << "(" << *Operands[0];
279 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
280 OS << OpStr << *Operands[i];
281 OS << ")";
282}
283
284SCEVHandle SCEVCommutativeExpr::
285replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000286 const SCEVHandle &Conc,
287 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000289 SCEVHandle H =
290 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 if (H != getOperand(i)) {
292 std::vector<SCEVHandle> NewOps;
293 NewOps.reserve(getNumOperands());
294 for (unsigned j = 0; j != i; ++j)
295 NewOps.push_back(getOperand(j));
296 NewOps.push_back(H);
297 for (++i; i != e; ++i)
298 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000299 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300
301 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000302 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000304 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000305 else if (isa<SCEVSMaxExpr>(this))
306 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000307 else if (isa<SCEVUMaxExpr>(this))
308 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 else
310 assert(0 && "Unknown commutative expr!");
311 }
312 }
313 return this;
314}
315
Dan Gohman72a8a022009-05-07 14:00:19 +0000316bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000317 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
318 if (!getOperand(i)->dominates(BB, DT))
319 return false;
320 }
321 return true;
322}
323
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000325// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326// input. Don't use a SCEVHandle here, or else the object will never be
327// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000328static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000329 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000331SCEVUDivExpr::~SCEVUDivExpr() {
332 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333}
334
Evan Cheng98c073b2009-02-17 00:13:06 +0000335bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
336 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
337}
338
Dan Gohman13058cc2009-04-21 00:47:46 +0000339void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000340 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341}
342
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000343const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 return LHS->getType();
345}
346
347// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
348// particular input. Don't use a SCEVHandle here, or else the object will never
349// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000350static ManagedStatic<std::map<std::pair<const Loop *,
351 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352 SCEVAddRecExpr*> > SCEVAddRecExprs;
353
354SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000355 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
356 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357}
358
359SCEVHandle SCEVAddRecExpr::
360replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000361 const SCEVHandle &Conc,
362 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000364 SCEVHandle H =
365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 if (H != getOperand(i)) {
367 std::vector<SCEVHandle> NewOps;
368 NewOps.reserve(getNumOperands());
369 for (unsigned j = 0; j != i; ++j)
370 NewOps.push_back(getOperand(j));
371 NewOps.push_back(H);
372 for (++i; i != e; ++i)
373 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375
Dan Gohman89f85052007-10-22 18:31:58 +0000376 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 }
378 }
379 return this;
380}
381
382
383bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
385 // contain L and if the start is invariant.
386 return !QueryLoop->contains(L->getHeader()) &&
387 getOperand(0)->isLoopInvariant(QueryLoop);
388}
389
390
Dan Gohman13058cc2009-04-21 00:47:46 +0000391void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
396}
397
398// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
399// value. Don't use a SCEVHandle here, or else the object will never be
400// deleted!
401static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
402
403SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
404
405bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return !L->contains(I->getParent());
410 return true;
411}
412
Evan Cheng98c073b2009-02-17 00:13:06 +0000413bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
414 if (Instruction *I = dyn_cast<Instruction>(getValue()))
415 return DT->dominates(I->getParent(), BB);
416 return true;
417}
418
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419const Type *SCEVUnknown::getType() const {
420 return V->getType();
421}
422
Dan Gohman13058cc2009-04-21 00:47:46 +0000423void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 WriteAsOperand(OS, V, false);
425}
426
427//===----------------------------------------------------------------------===//
428// SCEV Utilities
429//===----------------------------------------------------------------------===//
430
431namespace {
432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
433 /// than the complexity of the RHS. This comparator is used to canonicalize
434 /// expressions.
435 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000436 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437 return LHS->getSCEVType() < RHS->getSCEVType();
438 }
439 };
440}
441
442/// GroupByComplexity - Given a list of SCEV objects, order them by their
443/// complexity, and group objects of the same complexity together by value.
444/// When this routine is finished, we know that any duplicates in the vector are
445/// consecutive and that complexity is monotonically increasing.
446///
447/// Note that we go take special precautions to ensure that we get determinstic
448/// results from this routine. In other words, we don't want the results of
449/// this to depend on where the addresses of various SCEV objects happened to
450/// land in memory.
451///
452static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
453 if (Ops.size() < 2) return; // Noop
454 if (Ops.size() == 2) {
455 // This is the common case, which also happens to be trivially simple.
456 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000457 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 std::swap(Ops[0], Ops[1]);
459 return;
460 }
461
462 // Do the rough sort by complexity.
Dan Gohman991acef2009-05-06 22:54:33 +0000463 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464
465 // Now that we are sorted by complexity, group elements of the same
466 // complexity. Note that this is, at worst, N^2, but the vector is likely to
467 // be extremely short in practice. Note that we take this approach because we
468 // do not want to depend on the addresses of the objects we are grouping.
469 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000470 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 unsigned Complexity = S->getSCEVType();
472
473 // If there are any objects of the same complexity and same value as this
474 // one, group them.
475 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
476 if (Ops[j] == S) { // Found a duplicate.
477 // Move it to immediately after i'th element.
478 std::swap(Ops[i+1], Ops[j]);
479 ++i; // no need to rescan it.
480 if (i == e-2) return; // Done!
481 }
482 }
483 }
484}
485
486
487
488//===----------------------------------------------------------------------===//
489// Simple SCEV method implementations
490//===----------------------------------------------------------------------===//
491
Eli Friedman7489ec92008-08-04 23:49:06 +0000492/// BinomialCoefficient - Compute BC(It, K). The result has width W.
493// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000494static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000495 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000496 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000497 // Handle the simplest case efficiently.
498 if (K == 1)
499 return SE.getTruncateOrZeroExtend(It, ResultTy);
500
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000501 // We are using the following formula for BC(It, K):
502 //
503 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
504 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000505 // Suppose, W is the bitwidth of the return value. We must be prepared for
506 // overflow. Hence, we must assure that the result of our computation is
507 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
508 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000509 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000510 // However, this code doesn't use exactly that formula; the formula it uses
511 // is something like the following, where T is the number of factors of 2 in
512 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
513 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000514 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000515 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000516 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000517 // This formula is trivially equivalent to the previous formula. However,
518 // this formula can be implemented much more efficiently. The trick is that
519 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
520 // arithmetic. To do exact division in modular arithmetic, all we have
521 // to do is multiply by the inverse. Therefore, this step can be done at
522 // width W.
523 //
524 // The next issue is how to safely do the division by 2^T. The way this
525 // is done is by doing the multiplication step at a width of at least W + T
526 // bits. This way, the bottom W+T bits of the product are accurate. Then,
527 // when we perform the division by 2^T (which is equivalent to a right shift
528 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
529 // truncated out after the division by 2^T.
530 //
531 // In comparison to just directly using the first formula, this technique
532 // is much more efficient; using the first formula requires W * K bits,
533 // but this formula less than W + K bits. Also, the first formula requires
534 // a division step, whereas this formula only requires multiplies and shifts.
535 //
536 // It doesn't matter whether the subtraction step is done in the calculation
537 // width or the input iteration count's width; if the subtraction overflows,
538 // the result must be zero anyway. We prefer here to do it in the width of
539 // the induction variable because it helps a lot for certain cases; CodeGen
540 // isn't smart enough to ignore the overflow, which leads to much less
541 // efficient code if the width of the subtraction is wider than the native
542 // register width.
543 //
544 // (It's possible to not widen at all by pulling out factors of 2 before
545 // the multiplication; for example, K=2 can be calculated as
546 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
547 // extra arithmetic, so it's not an obvious win, and it gets
548 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000549
Eli Friedman7489ec92008-08-04 23:49:06 +0000550 // Protection from insane SCEVs; this bound is conservative,
551 // but it probably doesn't matter.
552 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000553 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000554
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000555 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000556
Eli Friedman7489ec92008-08-04 23:49:06 +0000557 // Calculate K! / 2^T and T; we divide out the factors of two before
558 // multiplying for calculating K! / 2^T to avoid overflow.
559 // Other overflow doesn't matter because we only care about the bottom
560 // W bits of the result.
561 APInt OddFactorial(W, 1);
562 unsigned T = 1;
563 for (unsigned i = 3; i <= K; ++i) {
564 APInt Mult(W, i);
565 unsigned TwoFactors = Mult.countTrailingZeros();
566 T += TwoFactors;
567 Mult = Mult.lshr(TwoFactors);
568 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000570
Eli Friedman7489ec92008-08-04 23:49:06 +0000571 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000572 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000573
574 // Calcuate 2^T, at width T+W.
575 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
576
577 // Calculate the multiplicative inverse of K! / 2^T;
578 // this multiplication factor will perform the exact division by
579 // K! / 2^T.
580 APInt Mod = APInt::getSignedMinValue(W+1);
581 APInt MultiplyFactor = OddFactorial.zext(W+1);
582 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
583 MultiplyFactor = MultiplyFactor.trunc(W);
584
585 // Calculate the product, at width T+W
586 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
587 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
588 for (unsigned i = 1; i != K; ++i) {
589 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
590 Dividend = SE.getMulExpr(Dividend,
591 SE.getTruncateOrZeroExtend(S, CalculationTy));
592 }
593
594 // Divide by 2^T
595 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
596
597 // Truncate the result, and divide by K! / 2^T.
598
599 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
600 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601}
602
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603/// evaluateAtIteration - Return the value of this chain of recurrences at
604/// the specified iteration number. We can evaluate this recurrence by
605/// multiplying each element in the chain by the binomial coefficient
606/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
607///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000608/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000610/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611///
Dan Gohman89f85052007-10-22 18:31:58 +0000612SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
613 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000616 // The computation is correct in the face of overflow provided that the
617 // multiplication is performed _after_ the evaluation of the binomial
618 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000619 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000620 if (isa<SCEVCouldNotCompute>(Coeff))
621 return Coeff;
622
623 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 }
625 return Result;
626}
627
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628//===----------------------------------------------------------------------===//
629// SCEV Expression folder implementations
630//===----------------------------------------------------------------------===//
631
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000632SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
633 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000634 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000635 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000636 assert(isSCEVable(Ty) &&
637 "This is not a conversion to a SCEVable type!");
638 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000639
Dan Gohmanc76b5452009-05-04 22:02:23 +0000640 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000641 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 ConstantExpr::getTrunc(SC->getValue(), Ty));
643
Dan Gohman1a5c4992009-04-22 16:20:48 +0000644 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000645 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000646 return getTruncateExpr(ST->getOperand(), Ty);
647
Nick Lewycky37d04642009-04-23 05:15:08 +0000648 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000649 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000650 return getTruncateOrSignExtend(SS->getOperand(), Ty);
651
652 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000653 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000654 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
655
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 // If the input value is a chrec scev made out of constants, truncate
657 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000658 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 std::vector<SCEVHandle> Operands;
660 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
661 // FIXME: This should allow truncation of other expression types!
662 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000663 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 else
665 break;
666 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000667 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 }
669
670 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
671 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
672 return Result;
673}
674
Dan Gohman36d40922009-04-16 19:25:55 +0000675SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
676 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000677 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000678 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000679 assert(isSCEVable(Ty) &&
680 "This is not a conversion to a SCEVable type!");
681 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000682
Dan Gohmanc76b5452009-05-04 22:02:23 +0000683 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000684 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000685 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
686 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
687 return getUnknown(C);
688 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689
Dan Gohman1a5c4992009-04-22 16:20:48 +0000690 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000691 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000692 return getZeroExtendExpr(SZ->getOperand(), Ty);
693
Dan Gohmana9dba962009-04-27 20:16:15 +0000694 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000696 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000698 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000699 if (AR->isAffine()) {
700 // Check whether the backedge-taken count is SCEVCouldNotCompute.
701 // Note that this serves two purposes: It filters out loops that are
702 // simply not analyzable, and it covers the case where this code is
703 // being called from within backedge-taken count analysis, such that
704 // attempting to ask for the backedge-taken count would likely result
705 // in infinite recursion. In the later case, the analysis code will
706 // cope with a conservative value, and it will take care to purge
707 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000708 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
709 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000710 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000711 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000712 SCEVHandle Start = AR->getStart();
713 SCEVHandle Step = AR->getStepRecurrence(*this);
714
715 // Check whether the backedge-taken count can be losslessly casted to
716 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000717 SCEVHandle CastedMaxBECount =
718 getTruncateOrZeroExtend(MaxBECount, Start->getType());
719 if (MaxBECount ==
720 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000721 const Type *WideTy =
722 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000723 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000724 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000725 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000726 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000727 SCEVHandle Add = getAddExpr(Start, ZMul);
728 if (getZeroExtendExpr(Add, WideTy) ==
729 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000730 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000731 getZeroExtendExpr(Step, WideTy))))
732 // Return the expression with the addrec on the outside.
733 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
734 getZeroExtendExpr(Step, Ty),
735 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000736
737 // Similar to above, only this time treat the step value as signed.
738 // This covers loops that count down.
739 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000740 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000741 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000742 Add = getAddExpr(Start, SMul);
743 if (getZeroExtendExpr(Add, WideTy) ==
744 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000745 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000746 getSignExtendExpr(Step, WideTy))))
747 // Return the expression with the addrec on the outside.
748 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
749 getSignExtendExpr(Step, Ty),
750 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000751 }
752 }
753 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754
755 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
756 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
757 return Result;
758}
759
Dan Gohmana9dba962009-04-27 20:16:15 +0000760SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
761 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000762 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000763 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000764 assert(isSCEVable(Ty) &&
765 "This is not a conversion to a SCEVable type!");
766 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000767
Dan Gohmanc76b5452009-05-04 22:02:23 +0000768 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000769 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000770 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
771 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
772 return getUnknown(C);
773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774
Dan Gohman1a5c4992009-04-22 16:20:48 +0000775 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000776 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000777 return getSignExtendExpr(SS->getOperand(), Ty);
778
Dan Gohmana9dba962009-04-27 20:16:15 +0000779 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000781 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000783 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000784 if (AR->isAffine()) {
785 // Check whether the backedge-taken count is SCEVCouldNotCompute.
786 // Note that this serves two purposes: It filters out loops that are
787 // simply not analyzable, and it covers the case where this code is
788 // being called from within backedge-taken count analysis, such that
789 // attempting to ask for the backedge-taken count would likely result
790 // in infinite recursion. In the later case, the analysis code will
791 // cope with a conservative value, and it will take care to purge
792 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000793 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
794 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000795 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000796 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000797 SCEVHandle Start = AR->getStart();
798 SCEVHandle Step = AR->getStepRecurrence(*this);
799
800 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000801 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000802 SCEVHandle CastedMaxBECount =
803 getTruncateOrZeroExtend(MaxBECount, Start->getType());
804 if (MaxBECount ==
805 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000806 const Type *WideTy =
807 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000808 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000809 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000810 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000811 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000812 SCEVHandle Add = getAddExpr(Start, SMul);
813 if (getSignExtendExpr(Add, WideTy) ==
814 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000815 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000816 getSignExtendExpr(Step, WideTy))))
817 // Return the expression with the addrec on the outside.
818 return getAddRecExpr(getSignExtendExpr(Start, Ty),
819 getSignExtendExpr(Step, Ty),
820 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000821 }
822 }
823 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824
825 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
826 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
827 return Result;
828}
829
830// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000831SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 assert(!Ops.empty() && "Cannot get empty add!");
833 if (Ops.size() == 1) return Ops[0];
834
835 // Sort by complexity, this groups all similar expression types together.
836 GroupByComplexity(Ops);
837
838 // If there are any constants, fold them together.
839 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000840 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 ++Idx;
842 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +0000843 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000845 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
846 RHSC->getValue()->getValue());
847 Ops[0] = getConstant(Fold);
848 Ops.erase(Ops.begin()+1); // Erase the folded element
849 if (Ops.size() == 1) return Ops[0];
850 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 }
852
853 // If we are left with a constant zero being added, strip it off.
854 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
855 Ops.erase(Ops.begin());
856 --Idx;
857 }
858 }
859
860 if (Ops.size() == 1) return Ops[0];
861
862 // Okay, check to see if the same value occurs in the operand list twice. If
863 // so, merge them together into an multiply expression. Since we sorted the
864 // list, these values are required to be adjacent.
865 const Type *Ty = Ops[0]->getType();
866 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
867 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
868 // Found a match, merge the two values into a multiply, and add any
869 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000870 SCEVHandle Two = getIntegerSCEV(2, Ty);
871 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872 if (Ops.size() == 2)
873 return Mul;
874 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
875 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000876 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 }
878
879 // Now we know the first non-constant operand. Skip past any cast SCEVs.
880 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
881 ++Idx;
882
883 // If there are add operands they would be next.
884 if (Idx < Ops.size()) {
885 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000886 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000887 // If we have an add, expand the add operands onto the end of the operands
888 // list.
889 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
890 Ops.erase(Ops.begin()+Idx);
891 DeletedAdd = true;
892 }
893
894 // If we deleted at least one add, we added operands to the end of the list,
895 // and they are not necessarily sorted. Recurse to resort and resimplify
896 // any operands we just aquired.
897 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000898 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 }
900
901 // Skip over the add expression until we get to a multiply.
902 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
903 ++Idx;
904
905 // If we are adding something to a multiply expression, make sure the
906 // something is not already an operand of the multiply. If so, merge it into
907 // the multiply.
908 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000909 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000911 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
913 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
914 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
915 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
916 if (Mul->getNumOperands() != 2) {
917 // If the multiply has more than two operands, we must get the
918 // Y*Z term.
919 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
920 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000921 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 }
Dan Gohman89f85052007-10-22 18:31:58 +0000923 SCEVHandle One = getIntegerSCEV(1, Ty);
924 SCEVHandle AddOne = getAddExpr(InnerMul, One);
925 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 if (Ops.size() == 2) return OuterMul;
927 if (AddOp < Idx) {
928 Ops.erase(Ops.begin()+AddOp);
929 Ops.erase(Ops.begin()+Idx-1);
930 } else {
931 Ops.erase(Ops.begin()+Idx);
932 Ops.erase(Ops.begin()+AddOp-1);
933 }
934 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000935 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000936 }
937
938 // Check this multiply against other multiplies being added together.
939 for (unsigned OtherMulIdx = Idx+1;
940 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
941 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000942 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943 // If MulOp occurs in OtherMul, we can fold the two multiplies
944 // together.
945 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
946 OMulOp != e; ++OMulOp)
947 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
948 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
949 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
950 if (Mul->getNumOperands() != 2) {
951 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
952 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000953 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 }
955 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
956 if (OtherMul->getNumOperands() != 2) {
957 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
958 OtherMul->op_end());
959 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000960 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 }
Dan Gohman89f85052007-10-22 18:31:58 +0000962 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
963 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964 if (Ops.size() == 2) return OuterMul;
965 Ops.erase(Ops.begin()+Idx);
966 Ops.erase(Ops.begin()+OtherMulIdx-1);
967 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000968 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969 }
970 }
971 }
972 }
973
974 // If there are any add recurrences in the operands list, see if any other
975 // added values are loop invariant. If so, we can fold them into the
976 // recurrence.
977 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
978 ++Idx;
979
980 // Scan over all recurrences, trying to fold loop invariants into them.
981 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
982 // Scan all of the other operands to this add and add them to the vector if
983 // they are loop invariant w.r.t. the recurrence.
984 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +0000985 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
987 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
988 LIOps.push_back(Ops[i]);
989 Ops.erase(Ops.begin()+i);
990 --i; --e;
991 }
992
993 // If we found some loop invariants, fold them into the recurrence.
994 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000995 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 LIOps.push_back(AddRec->getStart());
997
998 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000999 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000
Dan Gohman89f85052007-10-22 18:31:58 +00001001 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 // If all of the other operands were loop invariant, we are done.
1003 if (Ops.size() == 1) return NewRec;
1004
1005 // Otherwise, add the folded AddRec by the non-liv parts.
1006 for (unsigned i = 0;; ++i)
1007 if (Ops[i] == AddRec) {
1008 Ops[i] = NewRec;
1009 break;
1010 }
Dan Gohman89f85052007-10-22 18:31:58 +00001011 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 }
1013
1014 // Okay, if there weren't any loop invariants to be folded, check to see if
1015 // there are multiple AddRec's with the same loop induction variable being
1016 // added together. If so, we can fold them.
1017 for (unsigned OtherIdx = Idx+1;
1018 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1019 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001020 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1022 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1023 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1024 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1025 if (i >= NewOps.size()) {
1026 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1027 OtherAddRec->op_end());
1028 break;
1029 }
Dan Gohman89f85052007-10-22 18:31:58 +00001030 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 }
Dan Gohman89f85052007-10-22 18:31:58 +00001032 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033
1034 if (Ops.size() == 2) return NewAddRec;
1035
1036 Ops.erase(Ops.begin()+Idx);
1037 Ops.erase(Ops.begin()+OtherIdx-1);
1038 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001039 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 }
1041 }
1042
1043 // Otherwise couldn't fold anything into this recurrence. Move onto the
1044 // next one.
1045 }
1046
1047 // Okay, it looks like we really DO need an add expr. Check to see if we
1048 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001049 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1051 SCEVOps)];
1052 if (Result == 0) Result = new SCEVAddExpr(Ops);
1053 return Result;
1054}
1055
1056
Dan Gohman89f85052007-10-22 18:31:58 +00001057SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 assert(!Ops.empty() && "Cannot get empty mul!");
1059
1060 // Sort by complexity, this groups all similar expression types together.
1061 GroupByComplexity(Ops);
1062
1063 // If there are any constants, fold them together.
1064 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001065 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066
1067 // C1*(C2+V) -> C1*C2 + C1*V
1068 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001069 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 if (Add->getNumOperands() == 2 &&
1071 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001072 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1073 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074
1075
1076 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001077 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001079 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1080 RHSC->getValue()->getValue());
1081 Ops[0] = getConstant(Fold);
1082 Ops.erase(Ops.begin()+1); // Erase the folded element
1083 if (Ops.size() == 1) return Ops[0];
1084 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 }
1086
1087 // If we are left with a constant one being multiplied, strip it off.
1088 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1089 Ops.erase(Ops.begin());
1090 --Idx;
1091 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1092 // If we have a multiply of zero, it will always be zero.
1093 return Ops[0];
1094 }
1095 }
1096
1097 // Skip over the add expression until we get to a multiply.
1098 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1099 ++Idx;
1100
1101 if (Ops.size() == 1)
1102 return Ops[0];
1103
1104 // If there are mul operands inline them all into this expression.
1105 if (Idx < Ops.size()) {
1106 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001107 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 // If we have an mul, expand the mul operands onto the end of the operands
1109 // list.
1110 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1111 Ops.erase(Ops.begin()+Idx);
1112 DeletedMul = true;
1113 }
1114
1115 // If we deleted at least one mul, we added operands to the end of the list,
1116 // and they are not necessarily sorted. Recurse to resort and resimplify
1117 // any operands we just aquired.
1118 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001119 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 }
1121
1122 // If there are any add recurrences in the operands list, see if any other
1123 // added values are loop invariant. If so, we can fold them into the
1124 // recurrence.
1125 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1126 ++Idx;
1127
1128 // Scan over all recurrences, trying to fold loop invariants into them.
1129 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1130 // Scan all of the other operands to this mul and add them to the vector if
1131 // they are loop invariant w.r.t. the recurrence.
1132 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001133 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1135 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1136 LIOps.push_back(Ops[i]);
1137 Ops.erase(Ops.begin()+i);
1138 --i; --e;
1139 }
1140
1141 // If we found some loop invariants, fold them into the recurrence.
1142 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001143 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 std::vector<SCEVHandle> NewOps;
1145 NewOps.reserve(AddRec->getNumOperands());
1146 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001147 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001149 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150 } else {
1151 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1152 std::vector<SCEVHandle> MulOps(LIOps);
1153 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001154 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155 }
1156 }
1157
Dan Gohman89f85052007-10-22 18:31:58 +00001158 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159
1160 // If all of the other operands were loop invariant, we are done.
1161 if (Ops.size() == 1) return NewRec;
1162
1163 // Otherwise, multiply the folded AddRec by the non-liv parts.
1164 for (unsigned i = 0;; ++i)
1165 if (Ops[i] == AddRec) {
1166 Ops[i] = NewRec;
1167 break;
1168 }
Dan Gohman89f85052007-10-22 18:31:58 +00001169 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 }
1171
1172 // Okay, if there weren't any loop invariants to be folded, check to see if
1173 // there are multiple AddRec's with the same loop induction variable being
1174 // multiplied together. If so, we can fold them.
1175 for (unsigned OtherIdx = Idx+1;
1176 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1177 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001178 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1180 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001181 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001182 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001184 SCEVHandle B = F->getStepRecurrence(*this);
1185 SCEVHandle D = G->getStepRecurrence(*this);
1186 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1187 getMulExpr(G, B),
1188 getMulExpr(B, D));
1189 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1190 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001191 if (Ops.size() == 2) return NewAddRec;
1192
1193 Ops.erase(Ops.begin()+Idx);
1194 Ops.erase(Ops.begin()+OtherIdx-1);
1195 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001196 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001197 }
1198 }
1199
1200 // Otherwise couldn't fold anything into this recurrence. Move onto the
1201 // next one.
1202 }
1203
1204 // Okay, it looks like we really DO need an mul expr. Check to see if we
1205 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001206 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1208 SCEVOps)];
1209 if (Result == 0)
1210 Result = new SCEVMulExpr(Ops);
1211 return Result;
1212}
1213
Dan Gohman77841cd2009-05-04 22:23:18 +00001214SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1215 const SCEVHandle &RHS) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001216 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001218 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219
Dan Gohmanc76b5452009-05-04 22:02:23 +00001220 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221 Constant *LHSCV = LHSC->getValue();
1222 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001223 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 }
1225 }
1226
Nick Lewycky35b56022009-01-13 09:18:58 +00001227 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1228
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001229 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1230 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 return Result;
1232}
1233
1234
1235/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1236/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001237SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 const SCEVHandle &Step, const Loop *L) {
1239 std::vector<SCEVHandle> Operands;
1240 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001241 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 if (StepChrec->getLoop() == L) {
1243 Operands.insert(Operands.end(), StepChrec->op_begin(),
1244 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001245 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 }
1247
1248 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001249 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250}
1251
1252/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1253/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001254SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001255 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 if (Operands.size() == 1) return Operands[0];
1257
Dan Gohman7b560c42008-06-18 16:23:07 +00001258 if (Operands.back()->isZero()) {
1259 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001260 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001261 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262
Dan Gohman42936882008-08-08 18:33:12 +00001263 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001264 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001265 const Loop* NestedLoop = NestedAR->getLoop();
1266 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1267 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1268 NestedAR->op_end());
1269 SCEVHandle NestedARHandle(NestedAR);
1270 Operands[0] = NestedAR->getStart();
1271 NestedOperands[0] = getAddRecExpr(Operands, L);
1272 return getAddRecExpr(NestedOperands, NestedLoop);
1273 }
1274 }
1275
Dan Gohmanbff6b582009-05-04 22:30:44 +00001276 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1277 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1279 return Result;
1280}
1281
Nick Lewycky711640a2007-11-25 22:41:31 +00001282SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1283 const SCEVHandle &RHS) {
1284 std::vector<SCEVHandle> Ops;
1285 Ops.push_back(LHS);
1286 Ops.push_back(RHS);
1287 return getSMaxExpr(Ops);
1288}
1289
1290SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1291 assert(!Ops.empty() && "Cannot get empty smax!");
1292 if (Ops.size() == 1) return Ops[0];
1293
1294 // Sort by complexity, this groups all similar expression types together.
1295 GroupByComplexity(Ops);
1296
1297 // If there are any constants, fold them together.
1298 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001299 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001300 ++Idx;
1301 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001302 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001303 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001304 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001305 APIntOps::smax(LHSC->getValue()->getValue(),
1306 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001307 Ops[0] = getConstant(Fold);
1308 Ops.erase(Ops.begin()+1); // Erase the folded element
1309 if (Ops.size() == 1) return Ops[0];
1310 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001311 }
1312
1313 // If we are left with a constant -inf, strip it off.
1314 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1315 Ops.erase(Ops.begin());
1316 --Idx;
1317 }
1318 }
1319
1320 if (Ops.size() == 1) return Ops[0];
1321
1322 // Find the first SMax
1323 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1324 ++Idx;
1325
1326 // Check to see if one of the operands is an SMax. If so, expand its operands
1327 // onto our operand list, and recurse to simplify.
1328 if (Idx < Ops.size()) {
1329 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001330 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001331 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1332 Ops.erase(Ops.begin()+Idx);
1333 DeletedSMax = true;
1334 }
1335
1336 if (DeletedSMax)
1337 return getSMaxExpr(Ops);
1338 }
1339
1340 // Okay, check to see if the same value occurs in the operand list twice. If
1341 // so, delete one. Since we sorted the list, these values are required to
1342 // be adjacent.
1343 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1344 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1345 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1346 --i; --e;
1347 }
1348
1349 if (Ops.size() == 1) return Ops[0];
1350
1351 assert(!Ops.empty() && "Reduced smax down to nothing!");
1352
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001353 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001354 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001355 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001356 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1357 SCEVOps)];
1358 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1359 return Result;
1360}
1361
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001362SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1363 const SCEVHandle &RHS) {
1364 std::vector<SCEVHandle> Ops;
1365 Ops.push_back(LHS);
1366 Ops.push_back(RHS);
1367 return getUMaxExpr(Ops);
1368}
1369
1370SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1371 assert(!Ops.empty() && "Cannot get empty umax!");
1372 if (Ops.size() == 1) return Ops[0];
1373
1374 // Sort by complexity, this groups all similar expression types together.
1375 GroupByComplexity(Ops);
1376
1377 // If there are any constants, fold them together.
1378 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001379 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001380 ++Idx;
1381 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001382 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001383 // We found two constants, fold them together!
1384 ConstantInt *Fold = ConstantInt::get(
1385 APIntOps::umax(LHSC->getValue()->getValue(),
1386 RHSC->getValue()->getValue()));
1387 Ops[0] = getConstant(Fold);
1388 Ops.erase(Ops.begin()+1); // Erase the folded element
1389 if (Ops.size() == 1) return Ops[0];
1390 LHSC = cast<SCEVConstant>(Ops[0]);
1391 }
1392
1393 // If we are left with a constant zero, strip it off.
1394 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1395 Ops.erase(Ops.begin());
1396 --Idx;
1397 }
1398 }
1399
1400 if (Ops.size() == 1) return Ops[0];
1401
1402 // Find the first UMax
1403 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1404 ++Idx;
1405
1406 // Check to see if one of the operands is a UMax. If so, expand its operands
1407 // onto our operand list, and recurse to simplify.
1408 if (Idx < Ops.size()) {
1409 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001410 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001411 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1412 Ops.erase(Ops.begin()+Idx);
1413 DeletedUMax = true;
1414 }
1415
1416 if (DeletedUMax)
1417 return getUMaxExpr(Ops);
1418 }
1419
1420 // Okay, check to see if the same value occurs in the operand list twice. If
1421 // so, delete one. Since we sorted the list, these values are required to
1422 // be adjacent.
1423 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1424 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1425 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1426 --i; --e;
1427 }
1428
1429 if (Ops.size() == 1) return Ops[0];
1430
1431 assert(!Ops.empty() && "Reduced umax down to nothing!");
1432
1433 // Okay, it looks like we really DO need a umax expr. Check to see if we
1434 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001435 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001436 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1437 SCEVOps)];
1438 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1439 return Result;
1440}
1441
Dan Gohman89f85052007-10-22 18:31:58 +00001442SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001444 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001445 if (isa<ConstantPointerNull>(V))
1446 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1448 if (Result == 0) Result = new SCEVUnknown(V);
1449 return Result;
1450}
1451
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453// Basic SCEV Analysis and PHI Idiom Recognition Code
1454//
1455
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001456/// isSCEVable - Test if values of the given type are analyzable within
1457/// the SCEV framework. This primarily includes integer types, and it
1458/// can optionally include pointer types if the ScalarEvolution class
1459/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001460bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001461 // Integers are always SCEVable.
1462 if (Ty->isInteger())
1463 return true;
1464
1465 // Pointers are SCEVable if TargetData information is available
1466 // to provide pointer size information.
1467 if (isa<PointerType>(Ty))
1468 return TD != NULL;
1469
1470 // Otherwise it's not SCEVable.
1471 return false;
1472}
1473
1474/// getTypeSizeInBits - Return the size in bits of the specified type,
1475/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001476uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001477 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1478
1479 // If we have a TargetData, use it!
1480 if (TD)
1481 return TD->getTypeSizeInBits(Ty);
1482
1483 // Otherwise, we support only integer types.
1484 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1485 return Ty->getPrimitiveSizeInBits();
1486}
1487
1488/// getEffectiveSCEVType - Return a type with the same bitwidth as
1489/// the given type and which represents how SCEV will treat the given
1490/// type, for which isSCEVable must return true. For pointer types,
1491/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001492const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001493 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1494
1495 if (Ty->isInteger())
1496 return Ty;
1497
1498 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1499 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001500}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001502SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001503 return UnknownValue;
1504}
1505
Dan Gohmand83d4af2009-05-04 22:20:30 +00001506/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001507/// computed.
1508bool ScalarEvolution::hasSCEV(Value *V) const {
1509 return Scalars.count(V);
1510}
1511
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1513/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001514SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001515 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516
Dan Gohmanbff6b582009-05-04 22:30:44 +00001517 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518 if (I != Scalars.end()) return I->second;
1519 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001520 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 return S;
1522}
1523
Dan Gohman01c2ee72009-04-16 03:18:22 +00001524/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1525/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001526SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1527 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001528 Constant *C;
1529 if (Val == 0)
1530 C = Constant::getNullValue(Ty);
1531 else if (Ty->isFloatingPoint())
1532 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1533 APFloat::IEEEdouble, Val));
1534 else
1535 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001536 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001537}
1538
1539/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1540///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001541SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001542 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001543 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001544
1545 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001546 Ty = getEffectiveSCEVType(Ty);
1547 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001548}
1549
1550/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001551SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001552 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001553 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001554
1555 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001556 Ty = getEffectiveSCEVType(Ty);
1557 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001558 return getMinusSCEV(AllOnes, V);
1559}
1560
1561/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1562///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001563SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001564 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001565 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001566 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001567}
1568
1569/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1570/// input value to the specified type. If the type must be extended, it is zero
1571/// extended.
1572SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001573ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001574 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001575 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001576 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1577 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001578 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001579 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001580 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001581 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001582 return getTruncateExpr(V, Ty);
1583 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001584}
1585
1586/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1587/// input value to the specified type. If the type must be extended, it is sign
1588/// extended.
1589SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001590ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001591 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001592 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001593 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1594 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001595 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001596 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001597 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001598 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001599 return getTruncateExpr(V, Ty);
1600 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001601}
1602
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001603/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1604/// the specified instruction and replaces any references to the symbolic value
1605/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001606void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1608 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001609 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1610 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001611 if (SI == Scalars.end()) return;
1612
1613 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001614 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001615 if (NV == SI->second) return; // No change.
1616
1617 SI->second = NV; // Update the scalars map!
1618
1619 // Any instruction values that use this instruction might also need to be
1620 // updated!
1621 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1622 UI != E; ++UI)
1623 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1624}
1625
1626/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1627/// a loop header, making it a potential recurrence, or it doesn't.
1628///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001629SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001630 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001631 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001632 if (L->getHeader() == PN->getParent()) {
1633 // If it lives in the loop header, it has two incoming values, one
1634 // from outside the loop, and one from inside.
1635 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1636 unsigned BackEdge = IncomingEdge^1;
1637
1638 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001639 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001640 assert(Scalars.find(PN) == Scalars.end() &&
1641 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00001642 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643
1644 // Using this symbolic name for the PHI, analyze the value coming around
1645 // the back-edge.
1646 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1647
1648 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1649 // has a special value for the first iteration of the loop.
1650
1651 // If the value coming around the backedge is an add with the symbolic
1652 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00001653 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001654 // If there is a single occurrence of the symbolic value, replace it
1655 // with a recurrence.
1656 unsigned FoundIndex = Add->getNumOperands();
1657 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1658 if (Add->getOperand(i) == SymbolicName)
1659 if (FoundIndex == e) {
1660 FoundIndex = i;
1661 break;
1662 }
1663
1664 if (FoundIndex != Add->getNumOperands()) {
1665 // Create an add with everything but the specified operand.
1666 std::vector<SCEVHandle> Ops;
1667 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1668 if (i != FoundIndex)
1669 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001670 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671
1672 // This is not a valid addrec if the step amount is varying each
1673 // loop iteration, but is not itself an addrec in this loop.
1674 if (Accum->isLoopInvariant(L) ||
1675 (isa<SCEVAddRecExpr>(Accum) &&
1676 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1677 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001678 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679
1680 // Okay, for the entire analysis of this edge we assumed the PHI
1681 // to be symbolic. We now need to go back and update all of the
1682 // entries for the scalars that use the PHI (except for the PHI
1683 // itself) to use the new analyzed value instead of the "symbolic"
1684 // value.
1685 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1686 return PHISCEV;
1687 }
1688 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00001689 } else if (const SCEVAddRecExpr *AddRec =
1690 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691 // Otherwise, this could be a loop like this:
1692 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1693 // In this case, j = {1,+,1} and BEValue is j.
1694 // Because the other in-value of i (0) fits the evolution of BEValue
1695 // i really is an addrec evolution.
1696 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1697 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1698
1699 // If StartVal = j.start - j.stride, we can use StartVal as the
1700 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001701 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001702 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001704 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705
1706 // Okay, for the entire analysis of this edge we assumed the PHI
1707 // to be symbolic. We now need to go back and update all of the
1708 // entries for the scalars that use the PHI (except for the PHI
1709 // itself) to use the new analyzed value instead of the "symbolic"
1710 // value.
1711 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1712 return PHISCEV;
1713 }
1714 }
1715 }
1716
1717 return SymbolicName;
1718 }
1719
1720 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001721 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722}
1723
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001724/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1725/// guaranteed to end in (at every loop iteration). It is, at the same time,
1726/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1727/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001728static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001729 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001730 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731
Dan Gohmanc76b5452009-05-04 22:02:23 +00001732 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001733 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1734 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001735
Dan Gohmanc76b5452009-05-04 22:02:23 +00001736 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001737 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1738 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1739 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001740 }
1741
Dan Gohmanc76b5452009-05-04 22:02:23 +00001742 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001743 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1744 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1745 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001746 }
1747
Dan Gohmanc76b5452009-05-04 22:02:23 +00001748 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001749 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001750 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001751 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001752 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001753 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754 }
1755
Dan Gohmanc76b5452009-05-04 22:02:23 +00001756 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001757 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001758 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1759 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001760 for (unsigned i = 1, e = M->getNumOperands();
1761 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001762 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001763 BitWidth);
1764 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001766
Dan Gohmanc76b5452009-05-04 22:02:23 +00001767 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001768 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001769 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001770 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001771 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001772 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001774
Dan Gohmanc76b5452009-05-04 22:02:23 +00001775 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001776 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001777 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001778 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001779 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001780 return MinOpRes;
1781 }
1782
Dan Gohmanc76b5452009-05-04 22:02:23 +00001783 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001784 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001785 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001786 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001787 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001788 return MinOpRes;
1789 }
1790
Nick Lewycky35b56022009-01-13 09:18:58 +00001791 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001792 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793}
1794
1795/// createSCEV - We know that there is no SCEV for the specified value.
1796/// Analyze the expression.
1797///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001798SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001799 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001800 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001801
Dan Gohman3996f472008-06-22 19:56:46 +00001802 unsigned Opcode = Instruction::UserOp1;
1803 if (Instruction *I = dyn_cast<Instruction>(V))
1804 Opcode = I->getOpcode();
1805 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1806 Opcode = CE->getOpcode();
1807 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001808 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001809
Dan Gohman3996f472008-06-22 19:56:46 +00001810 User *U = cast<User>(V);
1811 switch (Opcode) {
1812 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001813 return getAddExpr(getSCEV(U->getOperand(0)),
1814 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001815 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001816 return getMulExpr(getSCEV(U->getOperand(0)),
1817 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001818 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001819 return getUDivExpr(getSCEV(U->getOperand(0)),
1820 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001821 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001822 return getMinusSCEV(getSCEV(U->getOperand(0)),
1823 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001824 case Instruction::And:
1825 // For an expression like x&255 that merely masks off the high bits,
1826 // use zext(trunc(x)) as the SCEV expression.
1827 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001828 if (CI->isNullValue())
1829 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00001830 if (CI->isAllOnesValue())
1831 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001832 const APInt &A = CI->getValue();
1833 unsigned Ones = A.countTrailingOnes();
1834 if (APIntOps::isMask(Ones, A))
1835 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001836 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1837 IntegerType::get(Ones)),
1838 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001839 }
1840 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001841 case Instruction::Or:
1842 // If the RHS of the Or is a constant, we may have something like:
1843 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1844 // optimizations will transparently handle this case.
1845 //
1846 // In order for this transformation to be safe, the LHS must be of the
1847 // form X*(2^n) and the Or constant must be less than 2^n.
1848 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1849 SCEVHandle LHS = getSCEV(U->getOperand(0));
1850 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001851 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001852 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001853 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854 }
Dan Gohman3996f472008-06-22 19:56:46 +00001855 break;
1856 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001857 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001858 // If the RHS of the xor is a signbit, then this is just an add.
1859 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001860 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001861 return getAddExpr(getSCEV(U->getOperand(0)),
1862 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001863
1864 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001865 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001866 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001867 }
1868 break;
1869
1870 case Instruction::Shl:
1871 // Turn shift left of a constant amount into a multiply.
1872 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1873 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1874 Constant *X = ConstantInt::get(
1875 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001876 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001877 }
1878 break;
1879
Nick Lewycky7fd27892008-07-07 06:15:49 +00001880 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001881 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001882 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1883 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1884 Constant *X = ConstantInt::get(
1885 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001886 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001887 }
1888 break;
1889
Dan Gohman53bf64a2009-04-21 02:26:00 +00001890 case Instruction::AShr:
1891 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1892 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1893 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1894 if (L->getOpcode() == Instruction::Shl &&
1895 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001896 unsigned BitWidth = getTypeSizeInBits(U->getType());
1897 uint64_t Amt = BitWidth - CI->getZExtValue();
1898 if (Amt == BitWidth)
1899 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1900 if (Amt > BitWidth)
1901 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001902 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001903 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001904 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001905 U->getType());
1906 }
1907 break;
1908
Dan Gohman3996f472008-06-22 19:56:46 +00001909 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001910 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001911
1912 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001913 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001914
1915 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001916 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001917
1918 case Instruction::BitCast:
1919 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001920 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001921 return getSCEV(U->getOperand(0));
1922 break;
1923
Dan Gohman01c2ee72009-04-16 03:18:22 +00001924 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001925 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001926 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001927 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001928
1929 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001930 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001931 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1932 U->getType());
1933
1934 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001935 if (!TD) break; // Without TD we can't analyze pointers.
1936 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001937 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001938 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001939 gep_type_iterator GTI = gep_type_begin(U);
1940 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1941 E = U->op_end();
1942 I != E; ++I) {
1943 Value *Index = *I;
1944 // Compute the (potentially symbolic) offset in bytes for this index.
1945 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1946 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001947 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001948 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1949 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001950 TotalOffset = getAddExpr(TotalOffset,
1951 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001952 } else {
1953 // For an array, add the element offset, explicitly scaled.
1954 SCEVHandle LocalOffset = getSCEV(Index);
1955 if (!isa<PointerType>(LocalOffset->getType()))
1956 // Getelementptr indicies are signed.
1957 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1958 IntPtrTy);
1959 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001960 getMulExpr(LocalOffset,
1961 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1962 IntPtrTy));
1963 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001964 }
1965 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001966 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001967 }
1968
Dan Gohman3996f472008-06-22 19:56:46 +00001969 case Instruction::PHI:
1970 return createNodeForPHI(cast<PHINode>(U));
1971
1972 case Instruction::Select:
1973 // This could be a smax or umax that was lowered earlier.
1974 // Try to recover it.
1975 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1976 Value *LHS = ICI->getOperand(0);
1977 Value *RHS = ICI->getOperand(1);
1978 switch (ICI->getPredicate()) {
1979 case ICmpInst::ICMP_SLT:
1980 case ICmpInst::ICMP_SLE:
1981 std::swap(LHS, RHS);
1982 // fall through
1983 case ICmpInst::ICMP_SGT:
1984 case ICmpInst::ICMP_SGE:
1985 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001986 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001987 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00001988 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001989 return getNotSCEV(getSMaxExpr(
1990 getNotSCEV(getSCEV(LHS)),
1991 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001992 break;
1993 case ICmpInst::ICMP_ULT:
1994 case ICmpInst::ICMP_ULE:
1995 std::swap(LHS, RHS);
1996 // fall through
1997 case ICmpInst::ICMP_UGT:
1998 case ICmpInst::ICMP_UGE:
1999 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002000 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002001 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2002 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002003 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2004 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002005 break;
2006 default:
2007 break;
2008 }
2009 }
2010
2011 default: // We cannot analyze this expression.
2012 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013 }
2014
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002015 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002016}
2017
2018
2019
2020//===----------------------------------------------------------------------===//
2021// Iteration Count Computation Code
2022//
2023
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002024/// getBackedgeTakenCount - If the specified loop has a predictable
2025/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2026/// object. The backedge-taken count is the number of times the loop header
2027/// will be branched to from within the loop. This is one less than the
2028/// trip count of the loop, since it doesn't count the first iteration,
2029/// when the header is branched to from outside the loop.
2030///
2031/// Note that it is not valid to call this method on a loop without a
2032/// loop-invariant backedge-taken count (see
2033/// hasLoopInvariantBackedgeTakenCount).
2034///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002035SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002036 return getBackedgeTakenInfo(L).Exact;
2037}
2038
2039/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2040/// return the least SCEV value that is known never to be less than the
2041/// actual backedge taken count.
2042SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2043 return getBackedgeTakenInfo(L).Max;
2044}
2045
2046const ScalarEvolution::BackedgeTakenInfo &
2047ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002048 // Initially insert a CouldNotCompute for this loop. If the insertion
2049 // succeeds, procede to actually compute a backedge-taken count and
2050 // update the value. The temporary CouldNotCompute value tells SCEV
2051 // code elsewhere that it shouldn't attempt to request a new
2052 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002053 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002054 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2055 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002056 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2057 if (ItCount.Exact != UnknownValue) {
2058 assert(ItCount.Exact->isLoopInvariant(L) &&
2059 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002060 "Computed trip count isn't loop invariant for loop!");
2061 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002062
Dan Gohmana9dba962009-04-27 20:16:15 +00002063 // Update the value in the map.
2064 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002065 } else if (isa<PHINode>(L->getHeader()->begin())) {
2066 // Only count loops that have phi nodes as not being computable.
2067 ++NumTripCountsNotComputed;
2068 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002069
2070 // Now that we know more about the trip count for this loop, forget any
2071 // existing SCEV values for PHI nodes in this loop since they are only
2072 // conservative estimates made without the benefit
2073 // of trip count information.
2074 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002075 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002076 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002077 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002078}
2079
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002080/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002081/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002082/// ScalarEvolution's ability to compute a trip count, or if the loop
2083/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002084void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002085 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002086 forgetLoopPHIs(L);
2087}
2088
2089/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2090/// PHI nodes in the given loop. This is used when the trip count of
2091/// the loop may have changed.
2092void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002093 BasicBlock *Header = L->getHeader();
2094
2095 SmallVector<Instruction *, 16> Worklist;
2096 for (BasicBlock::iterator I = Header->begin();
Dan Gohman94623022009-05-02 17:43:35 +00002097 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohmanbff6b582009-05-04 22:30:44 +00002098 Worklist.push_back(PN);
2099
2100 while (!Worklist.empty()) {
2101 Instruction *I = Worklist.pop_back_val();
2102 if (Scalars.erase(I))
2103 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2104 UI != UE; ++UI)
2105 Worklist.push_back(cast<Instruction>(UI));
2106 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002107}
2108
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002109/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2110/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002111ScalarEvolution::BackedgeTakenInfo
2112ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002113 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002114 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002115 L->getExitBlocks(ExitBlocks);
2116 if (ExitBlocks.size() != 1) return UnknownValue;
2117
2118 // Okay, there is one exit block. Try to find the condition that causes the
2119 // loop to be exited.
2120 BasicBlock *ExitBlock = ExitBlocks[0];
2121
2122 BasicBlock *ExitingBlock = 0;
2123 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2124 PI != E; ++PI)
2125 if (L->contains(*PI)) {
2126 if (ExitingBlock == 0)
2127 ExitingBlock = *PI;
2128 else
2129 return UnknownValue; // More than one block exiting!
2130 }
2131 assert(ExitingBlock && "No exits from loop, something is broken!");
2132
2133 // Okay, we've computed the exiting block. See what condition causes us to
2134 // exit.
2135 //
2136 // FIXME: we should be able to handle switch instructions (with a single exit)
2137 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2138 if (ExitBr == 0) return UnknownValue;
2139 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2140
2141 // At this point, we know we have a conditional branch that determines whether
2142 // the loop is exited. However, we don't know if the branch is executed each
2143 // time through the loop. If not, then the execution count of the branch will
2144 // not be equal to the trip count of the loop.
2145 //
2146 // Currently we check for this by checking to see if the Exit branch goes to
2147 // the loop header. If so, we know it will always execute the same number of
2148 // times as the loop. We also handle the case where the exit block *is* the
2149 // loop header. This is common for un-rotated loops. More extensive analysis
2150 // could be done to handle more cases here.
2151 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2152 ExitBr->getSuccessor(1) != L->getHeader() &&
2153 ExitBr->getParent() != L->getHeader())
2154 return UnknownValue;
2155
2156 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2157
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002158 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159 // Note that ICmpInst deals with pointer comparisons too so we must check
2160 // the type of the operand.
2161 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002162 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002163 ExitBr->getSuccessor(0) == ExitBlock);
2164
2165 // If the condition was exit on true, convert the condition to exit on false
2166 ICmpInst::Predicate Cond;
2167 if (ExitBr->getSuccessor(1) == ExitBlock)
2168 Cond = ExitCond->getPredicate();
2169 else
2170 Cond = ExitCond->getInversePredicate();
2171
2172 // Handle common loops like: for (X = "string"; *X; ++X)
2173 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2174 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2175 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002176 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2178 }
2179
2180 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2181 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2182
2183 // Try to evaluate any dependencies out of the loop.
2184 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2185 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2186 Tmp = getSCEVAtScope(RHS, L);
2187 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2188
2189 // At this point, we would like to compute how many iterations of the
2190 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002191 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2192 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002193 std::swap(LHS, RHS);
2194 Cond = ICmpInst::getSwappedPredicate(Cond);
2195 }
2196
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002197 // If we have a comparison of a chrec against a constant, try to use value
2198 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002199 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2200 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002201 if (AddRec->getLoop() == L) {
2202 // Form the comparison range using the constant of the correct type so
2203 // that the ConstantRange class knows to do a signed or unsigned
2204 // comparison.
2205 ConstantInt *CompVal = RHSC->getValue();
2206 const Type *RealTy = ExitCond->getOperand(0)->getType();
2207 CompVal = dyn_cast<ConstantInt>(
2208 ConstantExpr::getBitCast(CompVal, RealTy));
2209 if (CompVal) {
2210 // Form the constant range.
2211 ConstantRange CompRange(
2212 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2213
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002214 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002215 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2216 }
2217 }
2218
2219 switch (Cond) {
2220 case ICmpInst::ICMP_NE: { // while (X != Y)
2221 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002222 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002223 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2224 break;
2225 }
2226 case ICmpInst::ICMP_EQ: {
2227 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002228 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002229 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2230 break;
2231 }
2232 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002233 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2234 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 break;
2236 }
2237 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002238 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2239 getNotSCEV(RHS), L, true);
2240 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002241 break;
2242 }
2243 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002244 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2245 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002246 break;
2247 }
2248 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002249 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2250 getNotSCEV(RHS), L, false);
2251 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002252 break;
2253 }
2254 default:
2255#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002256 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002257 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002258 errs() << "[unsigned] ";
2259 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260 << Instruction::getOpcodeName(Instruction::ICmp)
2261 << " " << *RHS << "\n";
2262#endif
2263 break;
2264 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002265 return
2266 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2267 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002268}
2269
2270static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002271EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2272 ScalarEvolution &SE) {
2273 SCEVHandle InVal = SE.getConstant(C);
2274 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002275 assert(isa<SCEVConstant>(Val) &&
2276 "Evaluation of SCEV at constant didn't fold correctly?");
2277 return cast<SCEVConstant>(Val)->getValue();
2278}
2279
2280/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2281/// and a GEP expression (missing the pointer index) indexing into it, return
2282/// the addressed element of the initializer or null if the index expression is
2283/// invalid.
2284static Constant *
2285GetAddressedElementFromGlobal(GlobalVariable *GV,
2286 const std::vector<ConstantInt*> &Indices) {
2287 Constant *Init = GV->getInitializer();
2288 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2289 uint64_t Idx = Indices[i]->getZExtValue();
2290 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2291 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2292 Init = cast<Constant>(CS->getOperand(Idx));
2293 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2294 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2295 Init = cast<Constant>(CA->getOperand(Idx));
2296 } else if (isa<ConstantAggregateZero>(Init)) {
2297 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2298 assert(Idx < STy->getNumElements() && "Bad struct index!");
2299 Init = Constant::getNullValue(STy->getElementType(Idx));
2300 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2301 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2302 Init = Constant::getNullValue(ATy->getElementType());
2303 } else {
2304 assert(0 && "Unknown constant aggregate type!");
2305 }
2306 return 0;
2307 } else {
2308 return 0; // Unknown initializer type
2309 }
2310 }
2311 return Init;
2312}
2313
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002314/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2315/// 'icmp op load X, cst', try to see if we can compute the backedge
2316/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002317SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002318ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2319 const Loop *L,
2320 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321 if (LI->isVolatile()) return UnknownValue;
2322
2323 // Check to see if the loaded pointer is a getelementptr of a global.
2324 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2325 if (!GEP) return UnknownValue;
2326
2327 // Make sure that it is really a constant global we are gepping, with an
2328 // initializer, and make sure the first IDX is really 0.
2329 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2330 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2331 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2332 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2333 return UnknownValue;
2334
2335 // Okay, we allow one non-constant index into the GEP instruction.
2336 Value *VarIdx = 0;
2337 std::vector<ConstantInt*> Indexes;
2338 unsigned VarIdxNum = 0;
2339 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2340 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2341 Indexes.push_back(CI);
2342 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2343 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2344 VarIdx = GEP->getOperand(i);
2345 VarIdxNum = i-2;
2346 Indexes.push_back(0);
2347 }
2348
2349 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2350 // Check to see if X is a loop variant variable value now.
2351 SCEVHandle Idx = getSCEV(VarIdx);
2352 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2353 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2354
2355 // We can only recognize very limited forms of loop index expressions, in
2356 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002357 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002358 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2359 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2360 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2361 return UnknownValue;
2362
2363 unsigned MaxSteps = MaxBruteForceIterations;
2364 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2365 ConstantInt *ItCst =
2366 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002367 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002368
2369 // Form the GEP offset.
2370 Indexes[VarIdxNum] = Val;
2371
2372 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2373 if (Result == 0) break; // Cannot compute!
2374
2375 // Evaluate the condition for this iteration.
2376 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2377 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2378 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2379#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002380 errs() << "\n***\n*** Computed loop count " << *ItCst
2381 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2382 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002383#endif
2384 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002385 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386 }
2387 }
2388 return UnknownValue;
2389}
2390
2391
2392/// CanConstantFold - Return true if we can constant fold an instruction of the
2393/// specified type, assuming that all operands were constants.
2394static bool CanConstantFold(const Instruction *I) {
2395 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2396 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2397 return true;
2398
2399 if (const CallInst *CI = dyn_cast<CallInst>(I))
2400 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002401 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002402 return false;
2403}
2404
2405/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2406/// in the loop that V is derived from. We allow arbitrary operations along the
2407/// way, but the operands of an operation must either be constants or a value
2408/// derived from a constant PHI. If this expression does not fit with these
2409/// constraints, return null.
2410static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2411 // If this is not an instruction, or if this is an instruction outside of the
2412 // loop, it can't be derived from a loop PHI.
2413 Instruction *I = dyn_cast<Instruction>(V);
2414 if (I == 0 || !L->contains(I->getParent())) return 0;
2415
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002416 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417 if (L->getHeader() == I->getParent())
2418 return PN;
2419 else
2420 // We don't currently keep track of the control flow needed to evaluate
2421 // PHIs, so we cannot handle PHIs inside of loops.
2422 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002423 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002424
2425 // If we won't be able to constant fold this expression even if the operands
2426 // are constants, return early.
2427 if (!CanConstantFold(I)) return 0;
2428
2429 // Otherwise, we can evaluate this instruction if all of its operands are
2430 // constant or derived from a PHI node themselves.
2431 PHINode *PHI = 0;
2432 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2433 if (!(isa<Constant>(I->getOperand(Op)) ||
2434 isa<GlobalValue>(I->getOperand(Op)))) {
2435 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2436 if (P == 0) return 0; // Not evolving from PHI
2437 if (PHI == 0)
2438 PHI = P;
2439 else if (PHI != P)
2440 return 0; // Evolving from multiple different PHIs.
2441 }
2442
2443 // This is a expression evolving from a constant PHI!
2444 return PHI;
2445}
2446
2447/// EvaluateExpression - Given an expression that passes the
2448/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2449/// in the loop has the value PHIVal. If we can't fold this expression for some
2450/// reason, return null.
2451static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2452 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002453 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002454 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455 Instruction *I = cast<Instruction>(V);
2456
2457 std::vector<Constant*> Operands;
2458 Operands.resize(I->getNumOperands());
2459
2460 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2461 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2462 if (Operands[i] == 0) return 0;
2463 }
2464
Chris Lattnerd6e56912007-12-10 22:53:04 +00002465 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2466 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2467 &Operands[0], Operands.size());
2468 else
2469 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2470 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002471}
2472
2473/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2474/// in the header of its containing loop, we know the loop executes a
2475/// constant number of times, and the PHI node is just a recurrence
2476/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002477Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002478getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002479 std::map<PHINode*, Constant*>::iterator I =
2480 ConstantEvolutionLoopExitValue.find(PN);
2481 if (I != ConstantEvolutionLoopExitValue.end())
2482 return I->second;
2483
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002484 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002485 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2486
2487 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2488
2489 // Since the loop is canonicalized, the PHI node must have two entries. One
2490 // entry must be a constant (coming in from outside of the loop), and the
2491 // second must be derived from the same PHI.
2492 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2493 Constant *StartCST =
2494 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2495 if (StartCST == 0)
2496 return RetVal = 0; // Must be a constant.
2497
2498 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2499 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2500 if (PN2 != PN)
2501 return RetVal = 0; // Not derived from same PHI.
2502
2503 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002504 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2506
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002507 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002508 unsigned IterationNum = 0;
2509 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2510 if (IterationNum == NumIterations)
2511 return RetVal = PHIVal; // Got exit value!
2512
2513 // Compute the value of the PHI node for the next iteration.
2514 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2515 if (NextPHI == PHIVal)
2516 return RetVal = NextPHI; // Stopped evolving!
2517 if (NextPHI == 0)
2518 return 0; // Couldn't evaluate!
2519 PHIVal = NextPHI;
2520 }
2521}
2522
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002523/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002524/// constant number of times (the condition evolves only from constants),
2525/// try to evaluate a few iterations of the loop until we get the exit
2526/// condition gets a value of ExitWhen (true or false). If we cannot
2527/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002528SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002529ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2531 if (PN == 0) return UnknownValue;
2532
2533 // Since the loop is canonicalized, the PHI node must have two entries. One
2534 // entry must be a constant (coming in from outside of the loop), and the
2535 // second must be derived from the same PHI.
2536 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2537 Constant *StartCST =
2538 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2539 if (StartCST == 0) return UnknownValue; // Must be a constant.
2540
2541 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2542 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2543 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2544
2545 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2546 // the loop symbolically to determine when the condition gets a value of
2547 // "ExitWhen".
2548 unsigned IterationNum = 0;
2549 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2550 for (Constant *PHIVal = StartCST;
2551 IterationNum != MaxIterations; ++IterationNum) {
2552 ConstantInt *CondVal =
2553 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2554
2555 // Couldn't symbolically evaluate.
2556 if (!CondVal) return UnknownValue;
2557
2558 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2559 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2560 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002561 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002562 }
2563
2564 // Compute the value of the PHI node for the next iteration.
2565 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2566 if (NextPHI == 0 || NextPHI == PHIVal)
2567 return UnknownValue; // Couldn't evaluate or not making progress...
2568 PHIVal = NextPHI;
2569 }
2570
2571 // Too many iterations were needed to evaluate.
2572 return UnknownValue;
2573}
2574
2575/// getSCEVAtScope - Compute the value of the specified expression within the
2576/// indicated loop (which may be null to indicate in no loop). If the
2577/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002578SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002579 // FIXME: this should be turned into a virtual method on SCEV!
2580
2581 if (isa<SCEVConstant>(V)) return V;
2582
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002583 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002584 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002585 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002587 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002588 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2589 if (PHINode *PN = dyn_cast<PHINode>(I))
2590 if (PN->getParent() == LI->getHeader()) {
2591 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002592 // to see if the loop that contains it has a known backedge-taken
2593 // count. If so, we may be able to force computation of the exit
2594 // value.
2595 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002596 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002597 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598 // Okay, we know how many times the containing loop executes. If
2599 // this is a constant evolving PHI node, get the final value at
2600 // the specified iteration number.
2601 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002602 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002603 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002604 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002605 }
2606 }
2607
2608 // Okay, this is an expression that we cannot symbolically evaluate
2609 // into a SCEV. Check to see if it's possible to symbolically evaluate
2610 // the arguments into constants, and if so, try to constant propagate the
2611 // result. This is particularly useful for computing loop exit values.
2612 if (CanConstantFold(I)) {
2613 std::vector<Constant*> Operands;
2614 Operands.reserve(I->getNumOperands());
2615 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2616 Value *Op = I->getOperand(i);
2617 if (Constant *C = dyn_cast<Constant>(Op)) {
2618 Operands.push_back(C);
2619 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002620 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002621 // non-integer and non-pointer, don't even try to analyze them
2622 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002623 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002624 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002625
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002626 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002627 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002628 Constant *C = SC->getValue();
2629 if (C->getType() != Op->getType())
2630 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2631 Op->getType(),
2632 false),
2633 C, Op->getType());
2634 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002635 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002636 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2637 if (C->getType() != Op->getType())
2638 C =
2639 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2640 Op->getType(),
2641 false),
2642 C, Op->getType());
2643 Operands.push_back(C);
2644 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645 return V;
2646 } else {
2647 return V;
2648 }
2649 }
2650 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002651
2652 Constant *C;
2653 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2654 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2655 &Operands[0], Operands.size());
2656 else
2657 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2658 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002659 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002660 }
2661 }
2662
2663 // This is some other type of SCEVUnknown, just return it.
2664 return V;
2665 }
2666
Dan Gohmanc76b5452009-05-04 22:02:23 +00002667 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002668 // Avoid performing the look-up in the common case where the specified
2669 // expression has no loop-variant portions.
2670 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2671 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2672 if (OpAtScope != Comm->getOperand(i)) {
2673 if (OpAtScope == UnknownValue) return UnknownValue;
2674 // Okay, at least one of these operands is loop variant but might be
2675 // foldable. Build a new instance of the folded commutative expression.
2676 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2677 NewOps.push_back(OpAtScope);
2678
2679 for (++i; i != e; ++i) {
2680 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2681 if (OpAtScope == UnknownValue) return UnknownValue;
2682 NewOps.push_back(OpAtScope);
2683 }
2684 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002685 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002686 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002687 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002688 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002689 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002690 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002691 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002692 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002693 }
2694 }
2695 // If we got here, all operands are loop invariant.
2696 return Comm;
2697 }
2698
Dan Gohmanc76b5452009-05-04 22:02:23 +00002699 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002700 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002701 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002702 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002704 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2705 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002706 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002707 }
2708
2709 // If this is a loop recurrence for a loop that does not contain L, then we
2710 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002711 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002712 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2713 // To evaluate this recurrence, we need to know how many times the AddRec
2714 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002715 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2716 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002717
Eli Friedman7489ec92008-08-04 23:49:06 +00002718 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002719 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002720 }
2721 return UnknownValue;
2722 }
2723
Dan Gohmanc76b5452009-05-04 22:02:23 +00002724 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002725 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2726 if (Op == UnknownValue) return Op;
2727 if (Op == Cast->getOperand())
2728 return Cast; // must be loop invariant
2729 return getZeroExtendExpr(Op, Cast->getType());
2730 }
2731
Dan Gohmanc76b5452009-05-04 22:02:23 +00002732 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002733 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2734 if (Op == UnknownValue) return Op;
2735 if (Op == Cast->getOperand())
2736 return Cast; // must be loop invariant
2737 return getSignExtendExpr(Op, Cast->getType());
2738 }
2739
Dan Gohmanc76b5452009-05-04 22:02:23 +00002740 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002741 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2742 if (Op == UnknownValue) return Op;
2743 if (Op == Cast->getOperand())
2744 return Cast; // must be loop invariant
2745 return getTruncateExpr(Op, Cast->getType());
2746 }
2747
2748 assert(0 && "Unknown SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002749}
2750
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002751/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2752/// at the specified scope in the program. The L value specifies a loop
2753/// nest to evaluate the expression at, where null is the top-level or a
2754/// specified loop is immediately inside of the loop.
2755///
2756/// This method can be used to compute the exit value for a variable defined
2757/// in a loop by querying what the value will hold in the parent loop.
2758///
2759/// If this value is not computable at this scope, a SCEVCouldNotCompute
2760/// object is returned.
2761SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2762 return getSCEVAtScope(getSCEV(V), L);
2763}
2764
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002765/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2766/// following equation:
2767///
2768/// A * X = B (mod N)
2769///
2770/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2771/// A and B isn't important.
2772///
2773/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2774static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2775 ScalarEvolution &SE) {
2776 uint32_t BW = A.getBitWidth();
2777 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2778 assert(A != 0 && "A must be non-zero.");
2779
2780 // 1. D = gcd(A, N)
2781 //
2782 // The gcd of A and N may have only one prime factor: 2. The number of
2783 // trailing zeros in A is its multiplicity
2784 uint32_t Mult2 = A.countTrailingZeros();
2785 // D = 2^Mult2
2786
2787 // 2. Check if B is divisible by D.
2788 //
2789 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2790 // is not less than multiplicity of this prime factor for D.
2791 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002792 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002793
2794 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2795 // modulo (N / D).
2796 //
2797 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2798 // bit width during computations.
2799 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2800 APInt Mod(BW + 1, 0);
2801 Mod.set(BW - Mult2); // Mod = N / D
2802 APInt I = AD.multiplicativeInverse(Mod);
2803
2804 // 4. Compute the minimum unsigned root of the equation:
2805 // I * (B / D) mod (N / D)
2806 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2807
2808 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2809 // bits.
2810 return SE.getConstant(Result.trunc(BW));
2811}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002812
2813/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2814/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2815/// might be the same) or two SCEVCouldNotCompute objects.
2816///
2817static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002818SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002819 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002820 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2821 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2822 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002823
2824 // We currently can only solve this if the coefficients are constants.
2825 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002826 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002827 return std::make_pair(CNC, CNC);
2828 }
2829
2830 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2831 const APInt &L = LC->getValue()->getValue();
2832 const APInt &M = MC->getValue()->getValue();
2833 const APInt &N = NC->getValue()->getValue();
2834 APInt Two(BitWidth, 2);
2835 APInt Four(BitWidth, 4);
2836
2837 {
2838 using namespace APIntOps;
2839 const APInt& C = L;
2840 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2841 // The B coefficient is M-N/2
2842 APInt B(M);
2843 B -= sdiv(N,Two);
2844
2845 // The A coefficient is N/2
2846 APInt A(N.sdiv(Two));
2847
2848 // Compute the B^2-4ac term.
2849 APInt SqrtTerm(B);
2850 SqrtTerm *= B;
2851 SqrtTerm -= Four * (A * C);
2852
2853 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2854 // integer value or else APInt::sqrt() will assert.
2855 APInt SqrtVal(SqrtTerm.sqrt());
2856
2857 // Compute the two solutions for the quadratic formula.
2858 // The divisions must be performed as signed divisions.
2859 APInt NegB(-B);
2860 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002861 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002862 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002863 return std::make_pair(CNC, CNC);
2864 }
2865
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2867 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2868
Dan Gohman89f85052007-10-22 18:31:58 +00002869 return std::make_pair(SE.getConstant(Solution1),
2870 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871 } // end APIntOps namespace
2872}
2873
2874/// HowFarToZero - Return the number of times a backedge comparing the specified
2875/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00002876SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002877 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00002878 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 // If the value is already zero, the branch will execute zero times.
2880 if (C->getValue()->isZero()) return C;
2881 return UnknownValue; // Otherwise it will loop infinitely.
2882 }
2883
Dan Gohmanbff6b582009-05-04 22:30:44 +00002884 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002885 if (!AddRec || AddRec->getLoop() != L)
2886 return UnknownValue;
2887
2888 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002889 // If this is an affine expression, the execution count of this branch is
2890 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002892 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002893 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002894 // equivalent to:
2895 //
2896 // Step*N = -Start (mod 2^BW)
2897 //
2898 // where BW is the common bit width of Start and Step.
2899
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002900 // Get the initial value for the loop.
2901 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2902 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002904 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905
Dan Gohmanc76b5452009-05-04 22:02:23 +00002906 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002907 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002908
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002909 // First, handle unitary steps.
2910 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002911 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002912 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2913 return Start; // N = Start (as unsigned)
2914
2915 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002916 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002917 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002918 -StartC->getValue()->getValue(),
2919 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002920 }
2921 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2922 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2923 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002924 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2925 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002926 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2927 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002928 if (R1) {
2929#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002930 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2931 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932#endif
2933 // Pick the smallest positive root value.
2934 if (ConstantInt *CB =
2935 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2936 R1->getValue(), R2->getValue()))) {
2937 if (CB->getZExtValue() == false)
2938 std::swap(R1, R2); // R1 is the minimum root now.
2939
2940 // We can only use this value if the chrec ends up with an exact zero
2941 // value at this index. When solving for "X*X != 5", for example, we
2942 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002943 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002944 if (Val->isZero())
2945 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002946 }
2947 }
2948 }
2949
2950 return UnknownValue;
2951}
2952
2953/// HowFarToNonZero - Return the number of times a backedge checking the
2954/// specified value for nonzero will execute. If not computable, return
2955/// UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00002956SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002957 // Loops that look like: while (X == 0) are very strange indeed. We don't
2958 // handle them yet except for the trivial case. This could be expanded in the
2959 // future as needed.
2960
2961 // If the value is a constant, check to see if it is known to be non-zero
2962 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002963 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002964 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002965 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 return UnknownValue; // Otherwise it will loop infinitely.
2967 }
2968
2969 // We could implement others, but I really doubt anyone writes loops like
2970 // this, and if they did, they would already be constant folded.
2971 return UnknownValue;
2972}
2973
Dan Gohman1cddf972008-09-15 22:18:04 +00002974/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2975/// (which may not be an immediate predecessor) which has exactly one
2976/// successor from which BB is reachable, or null if no such block is
2977/// found.
2978///
2979BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002980ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00002981 // If the block has a unique predecessor, then there is no path from the
2982 // predecessor to the block that does not go through the direct edge
2983 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00002984 if (BasicBlock *Pred = BB->getSinglePredecessor())
2985 return Pred;
2986
2987 // A loop's header is defined to be a block that dominates the loop.
2988 // If the loop has a preheader, it must be a block that has exactly
2989 // one successor that can reach BB. This is slightly more strict
2990 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002991 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00002992 return L->getLoopPreheader();
2993
2994 return 0;
2995}
2996
Dan Gohmancacd2012009-02-12 22:19:27 +00002997/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00002998/// a conditional between LHS and RHS. This is used to help avoid max
2999/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003000bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003001 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003002 const SCEV *LHS, const SCEV *RHS) {
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003003 BasicBlock *Preheader = L->getLoopPreheader();
3004 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003005
Dan Gohmanab678fb2008-08-12 20:17:31 +00003006 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003007 // there are predecessors that can be found that have unique successors
3008 // leading to the original header.
3009 for (; Preheader;
3010 PreheaderDest = Preheader,
3011 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003012
3013 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003014 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003015 if (!LoopEntryPredicate ||
3016 LoopEntryPredicate->isUnconditional())
3017 continue;
3018
3019 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3020 if (!ICI) continue;
3021
3022 // Now that we found a conditional branch that dominates the loop, check to
3023 // see if it is the comparison we are looking for.
3024 Value *PreCondLHS = ICI->getOperand(0);
3025 Value *PreCondRHS = ICI->getOperand(1);
3026 ICmpInst::Predicate Cond;
3027 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3028 Cond = ICI->getPredicate();
3029 else
3030 Cond = ICI->getInversePredicate();
3031
Dan Gohmancacd2012009-02-12 22:19:27 +00003032 if (Cond == Pred)
3033 ; // An exact match.
3034 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3035 ; // The actual condition is beyond sufficient.
3036 else
3037 // Check a few special cases.
3038 switch (Cond) {
3039 case ICmpInst::ICMP_UGT:
3040 if (Pred == ICmpInst::ICMP_ULT) {
3041 std::swap(PreCondLHS, PreCondRHS);
3042 Cond = ICmpInst::ICMP_ULT;
3043 break;
3044 }
3045 continue;
3046 case ICmpInst::ICMP_SGT:
3047 if (Pred == ICmpInst::ICMP_SLT) {
3048 std::swap(PreCondLHS, PreCondRHS);
3049 Cond = ICmpInst::ICMP_SLT;
3050 break;
3051 }
3052 continue;
3053 case ICmpInst::ICMP_NE:
3054 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3055 // so check for this case by checking if the NE is comparing against
3056 // a minimum or maximum constant.
3057 if (!ICmpInst::isTrueWhenEqual(Pred))
3058 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3059 const APInt &A = CI->getValue();
3060 switch (Pred) {
3061 case ICmpInst::ICMP_SLT:
3062 if (A.isMaxSignedValue()) break;
3063 continue;
3064 case ICmpInst::ICMP_SGT:
3065 if (A.isMinSignedValue()) break;
3066 continue;
3067 case ICmpInst::ICMP_ULT:
3068 if (A.isMaxValue()) break;
3069 continue;
3070 case ICmpInst::ICMP_UGT:
3071 if (A.isMinValue()) break;
3072 continue;
3073 default:
3074 continue;
3075 }
3076 Cond = ICmpInst::ICMP_NE;
3077 // NE is symmetric but the original comparison may not be. Swap
3078 // the operands if necessary so that they match below.
3079 if (isa<SCEVConstant>(LHS))
3080 std::swap(PreCondLHS, PreCondRHS);
3081 break;
3082 }
3083 continue;
3084 default:
3085 // We weren't able to reconcile the condition.
3086 continue;
3087 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003088
3089 if (!PreCondLHS->getType()->isInteger()) continue;
3090
3091 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3092 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3093 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003094 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3095 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003096 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003097 }
3098
Dan Gohmanab678fb2008-08-12 20:17:31 +00003099 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003100}
3101
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003102/// HowManyLessThans - Return the number of times a backedge containing the
3103/// specified less-than comparison will execute. If not computable, return
3104/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003105ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003106HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3107 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003108 // Only handle: "ADDREC < LoopInvariant".
3109 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3110
Dan Gohmanbff6b582009-05-04 22:30:44 +00003111 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003112 if (!AddRec || AddRec->getLoop() != L)
3113 return UnknownValue;
3114
3115 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003116 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003117 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3118 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3119 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3120
3121 // TODO: handle non-constant strides.
3122 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3123 if (!CStep || CStep->isZero())
3124 return UnknownValue;
3125 if (CStep->getValue()->getValue() == 1) {
3126 // With unit stride, the iteration never steps past the limit value.
3127 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3128 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3129 // Test whether a positive iteration iteration can step past the limit
3130 // value and past the maximum value for its type in a single step.
3131 if (isSigned) {
3132 APInt Max = APInt::getSignedMaxValue(BitWidth);
3133 if ((Max - CStep->getValue()->getValue())
3134 .slt(CLimit->getValue()->getValue()))
3135 return UnknownValue;
3136 } else {
3137 APInt Max = APInt::getMaxValue(BitWidth);
3138 if ((Max - CStep->getValue()->getValue())
3139 .ult(CLimit->getValue()->getValue()))
3140 return UnknownValue;
3141 }
3142 } else
3143 // TODO: handle non-constant limit values below.
3144 return UnknownValue;
3145 } else
3146 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 return UnknownValue;
3148
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003149 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3150 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3151 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003152 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003153
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003154 // First, we get the value of the LHS in the first iteration: n
3155 SCEVHandle Start = AddRec->getOperand(0);
3156
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003157 // Determine the minimum constant start value.
3158 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3159 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3160 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003161
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003162 // If we know that the condition is true in order to enter the loop,
3163 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3164 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3165 // division must round up.
3166 SCEVHandle End = RHS;
3167 if (!isLoopGuardedByCond(L,
3168 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3169 getMinusSCEV(Start, Step), RHS))
3170 End = isSigned ? getSMaxExpr(RHS, Start)
3171 : getUMaxExpr(RHS, Start);
3172
3173 // Determine the maximum constant end value.
3174 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3175 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3176 APInt::getMaxValue(BitWidth));
3177
3178 // Finally, we subtract these two values and divide, rounding up, to get
3179 // the number of times the backedge is executed.
3180 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3181 getAddExpr(Step, NegOne)),
3182 Step);
3183
3184 // The maximum backedge count is similar, except using the minimum start
3185 // value and the maximum end value.
3186 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3187 MinStart),
3188 getAddExpr(Step, NegOne)),
3189 Step);
3190
3191 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003192 }
3193
3194 return UnknownValue;
3195}
3196
3197/// getNumIterationsInRange - Return the number of iterations of this loop that
3198/// produce values in the specified constant range. Another way of looking at
3199/// this is that it returns the first iteration number where the value is not in
3200/// the condition, thus computing the exit count. If the iteration count can't
3201/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003202SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3203 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003205 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003206
3207 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003208 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003209 if (!SC->getValue()->isZero()) {
3210 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003211 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3212 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003213 if (const SCEVAddRecExpr *ShiftedAddRec =
3214 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003216 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003217 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003218 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 }
3220
3221 // The only time we can solve this is when we have all constant indices.
3222 // Otherwise, we cannot determine the overflow conditions.
3223 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3224 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003225 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226
3227
3228 // Okay at this point we know that all elements of the chrec are constants and
3229 // that the start element is zero.
3230
3231 // First check to see if the range contains zero. If not, the first
3232 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003233 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003234 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003235 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003236
3237 if (isAffine()) {
3238 // If this is an affine expression then we have this situation:
3239 // Solve {0,+,A} in Range === Ax in Range
3240
3241 // We know that zero is in the range. If A is positive then we know that
3242 // the upper value of the range must be the first possible exit value.
3243 // If A is negative then the lower of the range is the last possible loop
3244 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003245 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003246 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3247 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3248
3249 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003250 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003251 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3252
3253 // Evaluate at the exit value. If we really did fall out of the valid
3254 // range, then we computed our trip count, otherwise wrap around or other
3255 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003256 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003257 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003258 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259
3260 // Ensure that the previous value is in the range. This is a sanity check.
3261 assert(Range.contains(
3262 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003263 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003264 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003265 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003266 } else if (isQuadratic()) {
3267 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3268 // quadratic equation to solve it. To do this, we must frame our problem in
3269 // terms of figuring out when zero is crossed, instead of when
3270 // Range.getUpper() is crossed.
3271 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003272 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3273 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003274
3275 // Next, solve the constructed addrec
3276 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003277 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003278 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3279 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003280 if (R1) {
3281 // Pick the smallest positive root value.
3282 if (ConstantInt *CB =
3283 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3284 R1->getValue(), R2->getValue()))) {
3285 if (CB->getZExtValue() == false)
3286 std::swap(R1, R2); // R1 is the minimum root now.
3287
3288 // Make sure the root is not off by one. The returned iteration should
3289 // not be in the range, but the previous one should be. When solving
3290 // for "X*X < 5", for example, we should not return a root of 2.
3291 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003292 R1->getValue(),
3293 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003294 if (Range.contains(R1Val->getValue())) {
3295 // The next iteration must be out of the range...
3296 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3297
Dan Gohman89f85052007-10-22 18:31:58 +00003298 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003299 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003300 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003301 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003302 }
3303
3304 // If R1 was not in the range, then it is a good return value. Make
3305 // sure that R1-1 WAS in the range though, just in case.
3306 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003307 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308 if (Range.contains(R1Val->getValue()))
3309 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003310 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003311 }
3312 }
3313 }
3314
Dan Gohman0ad08b02009-04-18 17:58:19 +00003315 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003316}
3317
3318
3319
3320//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003321// SCEVCallbackVH Class Implementation
3322//===----------------------------------------------------------------------===//
3323
3324void SCEVCallbackVH::deleted() {
3325 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3326 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3327 SE->ConstantEvolutionLoopExitValue.erase(PN);
3328 SE->Scalars.erase(getValPtr());
3329 // this now dangles!
3330}
3331
3332void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3333 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3334
3335 // Forget all the expressions associated with users of the old value,
3336 // so that future queries will recompute the expressions using the new
3337 // value.
3338 SmallVector<User *, 16> Worklist;
3339 Value *Old = getValPtr();
3340 bool DeleteOld = false;
3341 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3342 UI != UE; ++UI)
3343 Worklist.push_back(*UI);
3344 while (!Worklist.empty()) {
3345 User *U = Worklist.pop_back_val();
3346 // Deleting the Old value will cause this to dangle. Postpone
3347 // that until everything else is done.
3348 if (U == Old) {
3349 DeleteOld = true;
3350 continue;
3351 }
3352 if (PHINode *PN = dyn_cast<PHINode>(U))
3353 SE->ConstantEvolutionLoopExitValue.erase(PN);
3354 if (SE->Scalars.erase(U))
3355 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3356 UI != UE; ++UI)
3357 Worklist.push_back(*UI);
3358 }
3359 if (DeleteOld) {
3360 if (PHINode *PN = dyn_cast<PHINode>(Old))
3361 SE->ConstantEvolutionLoopExitValue.erase(PN);
3362 SE->Scalars.erase(Old);
3363 // this now dangles!
3364 }
3365 // this may dangle!
3366}
3367
3368SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3369 : CallbackVH(V), SE(se) {}
3370
3371//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003372// ScalarEvolution Class Implementation
3373//===----------------------------------------------------------------------===//
3374
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003375ScalarEvolution::ScalarEvolution()
3376 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3377}
3378
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003379bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003380 this->F = &F;
3381 LI = &getAnalysis<LoopInfo>();
3382 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003383 return false;
3384}
3385
3386void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003387 Scalars.clear();
3388 BackedgeTakenCounts.clear();
3389 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003390}
3391
3392void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3393 AU.setPreservesAll();
3394 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003395}
3396
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003397bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003398 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399}
3400
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003401static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 const Loop *L) {
3403 // Print all inner loops first
3404 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3405 PrintLoopInfo(OS, SE, *I);
3406
Nick Lewyckye5da1912008-01-02 02:49:20 +00003407 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003408
Devang Patel02451fa2007-08-21 00:31:24 +00003409 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003410 L->getExitBlocks(ExitBlocks);
3411 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003412 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003413
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003414 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3415 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003416 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003417 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003418 }
3419
Nick Lewyckye5da1912008-01-02 02:49:20 +00003420 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421}
3422
Dan Gohman13058cc2009-04-21 00:47:46 +00003423void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003424 // ScalarEvolution's implementaiton of the print method is to print
3425 // out SCEV values of all instructions that are interesting. Doing
3426 // this potentially causes it to create new SCEV objects though,
3427 // which technically conflicts with the const qualifier. This isn't
3428 // observable from outside the class though (the hasSCEV function
3429 // notwithstanding), so casting away the const isn't dangerous.
3430 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003431
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003432 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003433 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003434 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003435 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003436 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003437 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003438 SV->print(OS);
3439 OS << "\t\t";
3440
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003441 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003443 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3445 OS << "<<Unknown>>";
3446 } else {
3447 OS << *ExitValue;
3448 }
3449 }
3450
3451
3452 OS << "\n";
3453 }
3454
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003455 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3456 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3457 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003458}
Dan Gohman13058cc2009-04-21 00:47:46 +00003459
3460void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3461 raw_os_ostream OS(o);
3462 print(OS, M);
3463}