blob: 77a807063147e9d0e899dc3093d2f786449d37aa [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.
Dan Gohman5d486452009-05-07 14:39:04 +0000435 class VISIBILITY_HIDDEN SCEVComplexityCompare {
436 LoopInfo *LI;
437 public:
438 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
439
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000440 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000441 // Primarily, sort the SCEVs by their getSCEVType().
442 if (LHS->getSCEVType() != RHS->getSCEVType())
443 return LHS->getSCEVType() < RHS->getSCEVType();
444
445 // Aside from the getSCEVType() ordering, the particular ordering
446 // isn't very important except that it's beneficial to be consistent,
447 // so that (a + b) and (b + a) don't end up as different expressions.
448
449 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
450 // not as complete as it could be.
451 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
452 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
453
454 // Compare getValueID values.
455 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
456 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
457
458 // Sort arguments by their position.
459 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
460 const Argument *RA = cast<Argument>(RU->getValue());
461 return LA->getArgNo() < RA->getArgNo();
462 }
463
464 // For instructions, compare their loop depth, and their opcode.
465 // This is pretty loose.
466 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
467 Instruction *RV = cast<Instruction>(RU->getValue());
468
469 // Compare loop depths.
470 if (LI->getLoopDepth(LV->getParent()) !=
471 LI->getLoopDepth(RV->getParent()))
472 return LI->getLoopDepth(LV->getParent()) <
473 LI->getLoopDepth(RV->getParent());
474
475 // Compare opcodes.
476 if (LV->getOpcode() != RV->getOpcode())
477 return LV->getOpcode() < RV->getOpcode();
478
479 // Compare the number of operands.
480 if (LV->getNumOperands() != RV->getNumOperands())
481 return LV->getNumOperands() < RV->getNumOperands();
482 }
483
484 return false;
485 }
486
487 // Constant sorting doesn't matter since they'll be folded.
488 if (isa<SCEVConstant>(LHS))
489 return false;
490
491 // Lexicographically compare n-ary expressions.
492 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
493 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
494 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
495 if (i >= RC->getNumOperands())
496 return false;
497 if (operator()(LC->getOperand(i), RC->getOperand(i)))
498 return true;
499 if (operator()(RC->getOperand(i), LC->getOperand(i)))
500 return false;
501 }
502 return LC->getNumOperands() < RC->getNumOperands();
503 }
504
Dan Gohman6e10db12009-05-07 19:23:21 +0000505 // Lexicographically compare udiv expressions.
506 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
507 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
508 if (operator()(LC->getLHS(), RC->getLHS()))
509 return true;
510 if (operator()(RC->getLHS(), LC->getLHS()))
511 return false;
512 if (operator()(LC->getRHS(), RC->getRHS()))
513 return true;
514 if (operator()(RC->getRHS(), LC->getRHS()))
515 return false;
516 return false;
517 }
518
Dan Gohman5d486452009-05-07 14:39:04 +0000519 // Compare cast expressions by operand.
520 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
521 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
522 return operator()(LC->getOperand(), RC->getOperand());
523 }
524
525 assert(0 && "Unknown SCEV kind!");
526 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 }
528 };
529}
530
531/// GroupByComplexity - Given a list of SCEV objects, order them by their
532/// complexity, and group objects of the same complexity together by value.
533/// When this routine is finished, we know that any duplicates in the vector are
534/// consecutive and that complexity is monotonically increasing.
535///
536/// Note that we go take special precautions to ensure that we get determinstic
537/// results from this routine. In other words, we don't want the results of
538/// this to depend on where the addresses of various SCEV objects happened to
539/// land in memory.
540///
Dan Gohman5d486452009-05-07 14:39:04 +0000541static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
542 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 if (Ops.size() < 2) return; // Noop
544 if (Ops.size() == 2) {
545 // This is the common case, which also happens to be trivially simple.
546 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000547 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 std::swap(Ops[0], Ops[1]);
549 return;
550 }
551
552 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000553 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554
555 // Now that we are sorted by complexity, group elements of the same
556 // complexity. Note that this is, at worst, N^2, but the vector is likely to
557 // be extremely short in practice. Note that we take this approach because we
558 // do not want to depend on the addresses of the objects we are grouping.
559 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000560 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 unsigned Complexity = S->getSCEVType();
562
563 // If there are any objects of the same complexity and same value as this
564 // one, group them.
565 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
566 if (Ops[j] == S) { // Found a duplicate.
567 // Move it to immediately after i'th element.
568 std::swap(Ops[i+1], Ops[j]);
569 ++i; // no need to rescan it.
570 if (i == e-2) return; // Done!
571 }
572 }
573 }
574}
575
576
577
578//===----------------------------------------------------------------------===//
579// Simple SCEV method implementations
580//===----------------------------------------------------------------------===//
581
Eli Friedman7489ec92008-08-04 23:49:06 +0000582/// BinomialCoefficient - Compute BC(It, K). The result has width W.
583// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000584static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000585 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000586 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000587 // Handle the simplest case efficiently.
588 if (K == 1)
589 return SE.getTruncateOrZeroExtend(It, ResultTy);
590
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000591 // We are using the following formula for BC(It, K):
592 //
593 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
594 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000595 // Suppose, W is the bitwidth of the return value. We must be prepared for
596 // overflow. Hence, we must assure that the result of our computation is
597 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
598 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000599 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000600 // However, this code doesn't use exactly that formula; the formula it uses
601 // is something like the following, where T is the number of factors of 2 in
602 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
603 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000604 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000605 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000606 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000607 // This formula is trivially equivalent to the previous formula. However,
608 // this formula can be implemented much more efficiently. The trick is that
609 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
610 // arithmetic. To do exact division in modular arithmetic, all we have
611 // to do is multiply by the inverse. Therefore, this step can be done at
612 // width W.
613 //
614 // The next issue is how to safely do the division by 2^T. The way this
615 // is done is by doing the multiplication step at a width of at least W + T
616 // bits. This way, the bottom W+T bits of the product are accurate. Then,
617 // when we perform the division by 2^T (which is equivalent to a right shift
618 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
619 // truncated out after the division by 2^T.
620 //
621 // In comparison to just directly using the first formula, this technique
622 // is much more efficient; using the first formula requires W * K bits,
623 // but this formula less than W + K bits. Also, the first formula requires
624 // a division step, whereas this formula only requires multiplies and shifts.
625 //
626 // It doesn't matter whether the subtraction step is done in the calculation
627 // width or the input iteration count's width; if the subtraction overflows,
628 // the result must be zero anyway. We prefer here to do it in the width of
629 // the induction variable because it helps a lot for certain cases; CodeGen
630 // isn't smart enough to ignore the overflow, which leads to much less
631 // efficient code if the width of the subtraction is wider than the native
632 // register width.
633 //
634 // (It's possible to not widen at all by pulling out factors of 2 before
635 // the multiplication; for example, K=2 can be calculated as
636 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
637 // extra arithmetic, so it's not an obvious win, and it gets
638 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000639
Eli Friedman7489ec92008-08-04 23:49:06 +0000640 // Protection from insane SCEVs; this bound is conservative,
641 // but it probably doesn't matter.
642 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000643 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000644
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000645 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000646
Eli Friedman7489ec92008-08-04 23:49:06 +0000647 // Calculate K! / 2^T and T; we divide out the factors of two before
648 // multiplying for calculating K! / 2^T to avoid overflow.
649 // Other overflow doesn't matter because we only care about the bottom
650 // W bits of the result.
651 APInt OddFactorial(W, 1);
652 unsigned T = 1;
653 for (unsigned i = 3; i <= K; ++i) {
654 APInt Mult(W, i);
655 unsigned TwoFactors = Mult.countTrailingZeros();
656 T += TwoFactors;
657 Mult = Mult.lshr(TwoFactors);
658 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000660
Eli Friedman7489ec92008-08-04 23:49:06 +0000661 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000662 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000663
664 // Calcuate 2^T, at width T+W.
665 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
666
667 // Calculate the multiplicative inverse of K! / 2^T;
668 // this multiplication factor will perform the exact division by
669 // K! / 2^T.
670 APInt Mod = APInt::getSignedMinValue(W+1);
671 APInt MultiplyFactor = OddFactorial.zext(W+1);
672 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
673 MultiplyFactor = MultiplyFactor.trunc(W);
674
675 // Calculate the product, at width T+W
676 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
677 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
678 for (unsigned i = 1; i != K; ++i) {
679 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
680 Dividend = SE.getMulExpr(Dividend,
681 SE.getTruncateOrZeroExtend(S, CalculationTy));
682 }
683
684 // Divide by 2^T
685 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
686
687 // Truncate the result, and divide by K! / 2^T.
688
689 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
690 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691}
692
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693/// evaluateAtIteration - Return the value of this chain of recurrences at
694/// the specified iteration number. We can evaluate this recurrence by
695/// multiplying each element in the chain by the binomial coefficient
696/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
697///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000698/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000700/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701///
Dan Gohman89f85052007-10-22 18:31:58 +0000702SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
703 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000706 // The computation is correct in the face of overflow provided that the
707 // multiplication is performed _after_ the evaluation of the binomial
708 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000709 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000710 if (isa<SCEVCouldNotCompute>(Coeff))
711 return Coeff;
712
713 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 }
715 return Result;
716}
717
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718//===----------------------------------------------------------------------===//
719// SCEV Expression folder implementations
720//===----------------------------------------------------------------------===//
721
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000722SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
723 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000724 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000725 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000726 assert(isSCEVable(Ty) &&
727 "This is not a conversion to a SCEVable type!");
728 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000729
Dan Gohmanc76b5452009-05-04 22:02:23 +0000730 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000731 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 ConstantExpr::getTrunc(SC->getValue(), Ty));
733
Dan Gohman1a5c4992009-04-22 16:20:48 +0000734 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000735 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000736 return getTruncateExpr(ST->getOperand(), Ty);
737
Nick Lewycky37d04642009-04-23 05:15:08 +0000738 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000739 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000740 return getTruncateOrSignExtend(SS->getOperand(), Ty);
741
742 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000743 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000744 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
745
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 // If the input value is a chrec scev made out of constants, truncate
747 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000748 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 std::vector<SCEVHandle> Operands;
750 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000751 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
752 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753 }
754
755 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
756 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
757 return Result;
758}
759
Dan Gohman36d40922009-04-16 19:25:55 +0000760SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
761 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000762 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +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 Gohman36d40922009-04-16 19:25:55 +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::getZExt(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 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000776 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000777 return getZeroExtendExpr(SZ->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 zero 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 (unsigned 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
801 // 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 unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000809 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000810 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000811 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000812 SCEVHandle Add = getAddExpr(Start, ZMul);
813 if (getZeroExtendExpr(Add, WideTy) ==
814 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000815 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000816 getZeroExtendExpr(Step, WideTy))))
817 // Return the expression with the addrec on the outside.
818 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
819 getZeroExtendExpr(Step, Ty),
820 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000821
822 // Similar to above, only this time treat the step value as signed.
823 // This covers loops that count down.
824 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000825 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000826 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000827 Add = getAddExpr(Start, SMul);
828 if (getZeroExtendExpr(Add, WideTy) ==
829 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000830 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000831 getSignExtendExpr(Step, WideTy))))
832 // Return the expression with the addrec on the outside.
833 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
834 getSignExtendExpr(Step, Ty),
835 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000836 }
837 }
838 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839
840 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
841 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
842 return Result;
843}
844
Dan Gohmana9dba962009-04-27 20:16:15 +0000845SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
846 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000847 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000848 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000849 assert(isSCEVable(Ty) &&
850 "This is not a conversion to a SCEVable type!");
851 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000852
Dan Gohmanc76b5452009-05-04 22:02:23 +0000853 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000854 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000855 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
856 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
857 return getUnknown(C);
858 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859
Dan Gohman1a5c4992009-04-22 16:20:48 +0000860 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000861 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000862 return getSignExtendExpr(SS->getOperand(), Ty);
863
Dan Gohmana9dba962009-04-27 20:16:15 +0000864 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000866 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000868 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000869 if (AR->isAffine()) {
870 // Check whether the backedge-taken count is SCEVCouldNotCompute.
871 // Note that this serves two purposes: It filters out loops that are
872 // simply not analyzable, and it covers the case where this code is
873 // being called from within backedge-taken count analysis, such that
874 // attempting to ask for the backedge-taken count would likely result
875 // in infinite recursion. In the later case, the analysis code will
876 // cope with a conservative value, and it will take care to purge
877 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000878 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
879 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000880 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000881 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000882 SCEVHandle Start = AR->getStart();
883 SCEVHandle Step = AR->getStepRecurrence(*this);
884
885 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000886 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000887 SCEVHandle CastedMaxBECount =
888 getTruncateOrZeroExtend(MaxBECount, Start->getType());
889 if (MaxBECount ==
890 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000891 const Type *WideTy =
892 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000893 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000894 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000895 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000896 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000897 SCEVHandle Add = getAddExpr(Start, SMul);
898 if (getSignExtendExpr(Add, WideTy) ==
899 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000900 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000901 getSignExtendExpr(Step, WideTy))))
902 // Return the expression with the addrec on the outside.
903 return getAddRecExpr(getSignExtendExpr(Start, Ty),
904 getSignExtendExpr(Step, Ty),
905 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000906 }
907 }
908 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909
910 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
911 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
912 return Result;
913}
914
915// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000916SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 assert(!Ops.empty() && "Cannot get empty add!");
918 if (Ops.size() == 1) return Ops[0];
919
920 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +0000921 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922
923 // If there are any constants, fold them together.
924 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000925 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 ++Idx;
927 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +0000928 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000930 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
931 RHSC->getValue()->getValue());
932 Ops[0] = getConstant(Fold);
933 Ops.erase(Ops.begin()+1); // Erase the folded element
934 if (Ops.size() == 1) return Ops[0];
935 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000936 }
937
938 // If we are left with a constant zero being added, strip it off.
939 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
940 Ops.erase(Ops.begin());
941 --Idx;
942 }
943 }
944
945 if (Ops.size() == 1) return Ops[0];
946
947 // Okay, check to see if the same value occurs in the operand list twice. If
948 // so, merge them together into an multiply expression. Since we sorted the
949 // list, these values are required to be adjacent.
950 const Type *Ty = Ops[0]->getType();
951 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
952 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
953 // Found a match, merge the two values into a multiply, and add any
954 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000955 SCEVHandle Two = getIntegerSCEV(2, Ty);
956 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957 if (Ops.size() == 2)
958 return Mul;
959 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
960 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000961 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 }
963
Dan Gohman45b3b542009-05-08 21:03:19 +0000964 // Check for truncates. If all the operands are truncated from the same
965 // type, see if factoring out the truncate would permit the result to be
966 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
967 // if the contents of the resulting outer trunc fold to something simple.
968 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
969 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
970 const Type *DstType = Trunc->getType();
971 const Type *SrcType = Trunc->getOperand()->getType();
972 std::vector<SCEVHandle> LargeOps;
973 bool Ok = true;
974 // Check all the operands to see if they can be represented in the
975 // source type of the truncate.
976 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
977 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
978 if (T->getOperand()->getType() != SrcType) {
979 Ok = false;
980 break;
981 }
982 LargeOps.push_back(T->getOperand());
983 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
984 // This could be either sign or zero extension, but sign extension
985 // is much more likely to be foldable here.
986 LargeOps.push_back(getSignExtendExpr(C, SrcType));
987 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
988 std::vector<SCEVHandle> LargeMulOps;
989 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
990 if (const SCEVTruncateExpr *T =
991 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
992 if (T->getOperand()->getType() != SrcType) {
993 Ok = false;
994 break;
995 }
996 LargeMulOps.push_back(T->getOperand());
997 } else if (const SCEVConstant *C =
998 dyn_cast<SCEVConstant>(M->getOperand(j))) {
999 // This could be either sign or zero extension, but sign extension
1000 // is much more likely to be foldable here.
1001 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1002 } else {
1003 Ok = false;
1004 break;
1005 }
1006 }
1007 if (Ok)
1008 LargeOps.push_back(getMulExpr(LargeMulOps));
1009 } else {
1010 Ok = false;
1011 break;
1012 }
1013 }
1014 if (Ok) {
1015 // Evaluate the expression in the larger type.
1016 SCEVHandle Fold = getAddExpr(LargeOps);
1017 // If it folds to something simple, use it. Otherwise, don't.
1018 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1019 return getTruncateExpr(Fold, DstType);
1020 }
1021 }
1022
1023 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1025 ++Idx;
1026
1027 // If there are add operands they would be next.
1028 if (Idx < Ops.size()) {
1029 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001030 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 // If we have an add, expand the add operands onto the end of the operands
1032 // list.
1033 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1034 Ops.erase(Ops.begin()+Idx);
1035 DeletedAdd = true;
1036 }
1037
1038 // If we deleted at least one add, we added operands to the end of the list,
1039 // and they are not necessarily sorted. Recurse to resort and resimplify
1040 // any operands we just aquired.
1041 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001042 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044
1045 // Skip over the add expression until we get to a multiply.
1046 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1047 ++Idx;
1048
1049 // If we are adding something to a multiply expression, make sure the
1050 // something is not already an operand of the multiply. If so, merge it into
1051 // the multiply.
1052 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001053 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001055 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1057 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
1058 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1059 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1060 if (Mul->getNumOperands() != 2) {
1061 // If the multiply has more than two operands, we must get the
1062 // Y*Z term.
1063 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1064 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001065 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 }
Dan Gohman89f85052007-10-22 18:31:58 +00001067 SCEVHandle One = getIntegerSCEV(1, Ty);
1068 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1069 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 if (Ops.size() == 2) return OuterMul;
1071 if (AddOp < Idx) {
1072 Ops.erase(Ops.begin()+AddOp);
1073 Ops.erase(Ops.begin()+Idx-1);
1074 } else {
1075 Ops.erase(Ops.begin()+Idx);
1076 Ops.erase(Ops.begin()+AddOp-1);
1077 }
1078 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001079 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 }
1081
1082 // Check this multiply against other multiplies being added together.
1083 for (unsigned OtherMulIdx = Idx+1;
1084 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1085 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001086 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 // If MulOp occurs in OtherMul, we can fold the two multiplies
1088 // together.
1089 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1090 OMulOp != e; ++OMulOp)
1091 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1092 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1093 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1094 if (Mul->getNumOperands() != 2) {
1095 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1096 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001097 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 }
1099 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1100 if (OtherMul->getNumOperands() != 2) {
1101 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1102 OtherMul->op_end());
1103 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001104 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 }
Dan Gohman89f85052007-10-22 18:31:58 +00001106 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1107 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 if (Ops.size() == 2) return OuterMul;
1109 Ops.erase(Ops.begin()+Idx);
1110 Ops.erase(Ops.begin()+OtherMulIdx-1);
1111 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001112 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 }
1114 }
1115 }
1116 }
1117
1118 // If there are any add recurrences in the operands list, see if any other
1119 // added values are loop invariant. If so, we can fold them into the
1120 // recurrence.
1121 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1122 ++Idx;
1123
1124 // Scan over all recurrences, trying to fold loop invariants into them.
1125 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1126 // Scan all of the other operands to this add and add them to the vector if
1127 // they are loop invariant w.r.t. the recurrence.
1128 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001129 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1131 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1132 LIOps.push_back(Ops[i]);
1133 Ops.erase(Ops.begin()+i);
1134 --i; --e;
1135 }
1136
1137 // If we found some loop invariants, fold them into the recurrence.
1138 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001139 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 LIOps.push_back(AddRec->getStart());
1141
1142 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001143 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144
Dan Gohman89f85052007-10-22 18:31:58 +00001145 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 // If all of the other operands were loop invariant, we are done.
1147 if (Ops.size() == 1) return NewRec;
1148
1149 // Otherwise, add the folded AddRec by the non-liv parts.
1150 for (unsigned i = 0;; ++i)
1151 if (Ops[i] == AddRec) {
1152 Ops[i] = NewRec;
1153 break;
1154 }
Dan Gohman89f85052007-10-22 18:31:58 +00001155 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 }
1157
1158 // Okay, if there weren't any loop invariants to be folded, check to see if
1159 // there are multiple AddRec's with the same loop induction variable being
1160 // added together. If so, we can fold them.
1161 for (unsigned OtherIdx = Idx+1;
1162 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1163 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001164 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1166 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1167 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1168 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1169 if (i >= NewOps.size()) {
1170 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1171 OtherAddRec->op_end());
1172 break;
1173 }
Dan Gohman89f85052007-10-22 18:31:58 +00001174 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 }
Dan Gohman89f85052007-10-22 18:31:58 +00001176 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001177
1178 if (Ops.size() == 2) return NewAddRec;
1179
1180 Ops.erase(Ops.begin()+Idx);
1181 Ops.erase(Ops.begin()+OtherIdx-1);
1182 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001183 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 }
1185 }
1186
1187 // Otherwise couldn't fold anything into this recurrence. Move onto the
1188 // next one.
1189 }
1190
1191 // Okay, it looks like we really DO need an add expr. Check to see if we
1192 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001193 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1195 SCEVOps)];
1196 if (Result == 0) Result = new SCEVAddExpr(Ops);
1197 return Result;
1198}
1199
1200
Dan Gohman89f85052007-10-22 18:31:58 +00001201SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 assert(!Ops.empty() && "Cannot get empty mul!");
1203
1204 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001205 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206
1207 // If there are any constants, fold them together.
1208 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001209 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210
1211 // C1*(C2+V) -> C1*C2 + C1*V
1212 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001213 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 if (Add->getNumOperands() == 2 &&
1215 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001216 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1217 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218
1219
1220 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001221 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001222 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001223 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1224 RHSC->getValue()->getValue());
1225 Ops[0] = getConstant(Fold);
1226 Ops.erase(Ops.begin()+1); // Erase the folded element
1227 if (Ops.size() == 1) return Ops[0];
1228 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 }
1230
1231 // If we are left with a constant one being multiplied, strip it off.
1232 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1233 Ops.erase(Ops.begin());
1234 --Idx;
1235 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1236 // If we have a multiply of zero, it will always be zero.
1237 return Ops[0];
1238 }
1239 }
1240
1241 // Skip over the add expression until we get to a multiply.
1242 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1243 ++Idx;
1244
1245 if (Ops.size() == 1)
1246 return Ops[0];
1247
1248 // If there are mul operands inline them all into this expression.
1249 if (Idx < Ops.size()) {
1250 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001251 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 // If we have an mul, expand the mul operands onto the end of the operands
1253 // list.
1254 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1255 Ops.erase(Ops.begin()+Idx);
1256 DeletedMul = true;
1257 }
1258
1259 // If we deleted at least one mul, we added operands to the end of the list,
1260 // and they are not necessarily sorted. Recurse to resort and resimplify
1261 // any operands we just aquired.
1262 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001263 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 }
1265
1266 // If there are any add recurrences in the operands list, see if any other
1267 // added values are loop invariant. If so, we can fold them into the
1268 // recurrence.
1269 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1270 ++Idx;
1271
1272 // Scan over all recurrences, trying to fold loop invariants into them.
1273 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1274 // Scan all of the other operands to this mul and add them to the vector if
1275 // they are loop invariant w.r.t. the recurrence.
1276 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001277 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1279 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1280 LIOps.push_back(Ops[i]);
1281 Ops.erase(Ops.begin()+i);
1282 --i; --e;
1283 }
1284
1285 // If we found some loop invariants, fold them into the recurrence.
1286 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001287 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 std::vector<SCEVHandle> NewOps;
1289 NewOps.reserve(AddRec->getNumOperands());
1290 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001291 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001293 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 } else {
1295 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1296 std::vector<SCEVHandle> MulOps(LIOps);
1297 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001298 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 }
1300 }
1301
Dan Gohman89f85052007-10-22 18:31:58 +00001302 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303
1304 // If all of the other operands were loop invariant, we are done.
1305 if (Ops.size() == 1) return NewRec;
1306
1307 // Otherwise, multiply the folded AddRec by the non-liv parts.
1308 for (unsigned i = 0;; ++i)
1309 if (Ops[i] == AddRec) {
1310 Ops[i] = NewRec;
1311 break;
1312 }
Dan Gohman89f85052007-10-22 18:31:58 +00001313 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 }
1315
1316 // Okay, if there weren't any loop invariants to be folded, check to see if
1317 // there are multiple AddRec's with the same loop induction variable being
1318 // multiplied together. If so, we can fold them.
1319 for (unsigned OtherIdx = Idx+1;
1320 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1321 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001322 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1324 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001325 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001326 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001328 SCEVHandle B = F->getStepRecurrence(*this);
1329 SCEVHandle D = G->getStepRecurrence(*this);
1330 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1331 getMulExpr(G, B),
1332 getMulExpr(B, D));
1333 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1334 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 if (Ops.size() == 2) return NewAddRec;
1336
1337 Ops.erase(Ops.begin()+Idx);
1338 Ops.erase(Ops.begin()+OtherIdx-1);
1339 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001340 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 }
1342 }
1343
1344 // Otherwise couldn't fold anything into this recurrence. Move onto the
1345 // next one.
1346 }
1347
1348 // Okay, it looks like we really DO need an mul expr. Check to see if we
1349 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001350 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1352 SCEVOps)];
1353 if (Result == 0)
1354 Result = new SCEVMulExpr(Ops);
1355 return Result;
1356}
1357
Dan Gohman77841cd2009-05-04 22:23:18 +00001358SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1359 const SCEVHandle &RHS) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001360 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001362 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001363 if (RHSC->isZero())
1364 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001366 // Determine if the division can be folded into the operands of
1367 // its operands.
1368 // TODO: Generalize this to non-constants by using known-bits information.
1369 const Type *Ty = LHS->getType();
1370 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1371 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1372 // For non-power-of-two values, effectively round the value up to the
1373 // nearest power of two.
1374 if (!RHSC->getValue()->getValue().isPowerOf2())
1375 ++MaxShiftAmt;
1376 const IntegerType *ExtTy =
1377 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1378 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1379 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1380 if (const SCEVConstant *Step =
1381 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1382 if (!Step->getValue()->getValue()
1383 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001384 getZeroExtendExpr(AR, ExtTy) ==
1385 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1386 getZeroExtendExpr(Step, ExtTy),
1387 AR->getLoop())) {
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001388 std::vector<SCEVHandle> Operands;
1389 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1390 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1391 return getAddRecExpr(Operands, AR->getLoop());
1392 }
1393 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001394 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1395 std::vector<SCEVHandle> Operands;
1396 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1397 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1398 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001399 // Find an operand that's safely divisible.
1400 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1401 SCEVHandle Op = M->getOperand(i);
1402 SCEVHandle Div = getUDivExpr(Op, RHSC);
1403 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman14374d32009-05-08 23:11:16 +00001404 Operands = M->getOperands();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001405 Operands[i] = Div;
1406 return getMulExpr(Operands);
1407 }
1408 }
Dan Gohman14374d32009-05-08 23:11:16 +00001409 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001410 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001411 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1412 std::vector<SCEVHandle> Operands;
1413 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1414 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1415 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1416 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001417 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1418 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1419 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1420 break;
1421 Operands.push_back(Op);
1422 }
1423 if (Operands.size() == A->getNumOperands())
1424 return getAddExpr(Operands);
1425 }
Dan Gohman14374d32009-05-08 23:11:16 +00001426 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001427
1428 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001429 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430 Constant *LHSCV = LHSC->getValue();
1431 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001432 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 }
1434 }
1435
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001436 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1437 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 return Result;
1439}
1440
1441
1442/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1443/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001444SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445 const SCEVHandle &Step, const Loop *L) {
1446 std::vector<SCEVHandle> Operands;
1447 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001448 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 if (StepChrec->getLoop() == L) {
1450 Operands.insert(Operands.end(), StepChrec->op_begin(),
1451 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001452 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 }
1454
1455 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001456 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457}
1458
1459/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1460/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001461SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001462 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 if (Operands.size() == 1) return Operands[0];
1464
Dan Gohman7b560c42008-06-18 16:23:07 +00001465 if (Operands.back()->isZero()) {
1466 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001467 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001468 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469
Dan Gohman42936882008-08-08 18:33:12 +00001470 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001471 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001472 const Loop* NestedLoop = NestedAR->getLoop();
1473 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1474 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1475 NestedAR->op_end());
1476 SCEVHandle NestedARHandle(NestedAR);
1477 Operands[0] = NestedAR->getStart();
1478 NestedOperands[0] = getAddRecExpr(Operands, L);
1479 return getAddRecExpr(NestedOperands, NestedLoop);
1480 }
1481 }
1482
Dan Gohmanbff6b582009-05-04 22:30:44 +00001483 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1484 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001485 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1486 return Result;
1487}
1488
Nick Lewycky711640a2007-11-25 22:41:31 +00001489SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1490 const SCEVHandle &RHS) {
1491 std::vector<SCEVHandle> Ops;
1492 Ops.push_back(LHS);
1493 Ops.push_back(RHS);
1494 return getSMaxExpr(Ops);
1495}
1496
1497SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1498 assert(!Ops.empty() && "Cannot get empty smax!");
1499 if (Ops.size() == 1) return Ops[0];
1500
1501 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001502 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001503
1504 // If there are any constants, fold them together.
1505 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001506 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001507 ++Idx;
1508 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001509 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001510 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001511 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001512 APIntOps::smax(LHSC->getValue()->getValue(),
1513 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001514 Ops[0] = getConstant(Fold);
1515 Ops.erase(Ops.begin()+1); // Erase the folded element
1516 if (Ops.size() == 1) return Ops[0];
1517 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001518 }
1519
1520 // If we are left with a constant -inf, strip it off.
1521 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1522 Ops.erase(Ops.begin());
1523 --Idx;
1524 }
1525 }
1526
1527 if (Ops.size() == 1) return Ops[0];
1528
1529 // Find the first SMax
1530 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1531 ++Idx;
1532
1533 // Check to see if one of the operands is an SMax. If so, expand its operands
1534 // onto our operand list, and recurse to simplify.
1535 if (Idx < Ops.size()) {
1536 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001537 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001538 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1539 Ops.erase(Ops.begin()+Idx);
1540 DeletedSMax = true;
1541 }
1542
1543 if (DeletedSMax)
1544 return getSMaxExpr(Ops);
1545 }
1546
1547 // Okay, check to see if the same value occurs in the operand list twice. If
1548 // so, delete one. Since we sorted the list, these values are required to
1549 // be adjacent.
1550 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1551 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1552 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1553 --i; --e;
1554 }
1555
1556 if (Ops.size() == 1) return Ops[0];
1557
1558 assert(!Ops.empty() && "Reduced smax down to nothing!");
1559
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001560 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001561 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001562 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001563 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1564 SCEVOps)];
1565 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1566 return Result;
1567}
1568
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001569SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1570 const SCEVHandle &RHS) {
1571 std::vector<SCEVHandle> Ops;
1572 Ops.push_back(LHS);
1573 Ops.push_back(RHS);
1574 return getUMaxExpr(Ops);
1575}
1576
1577SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1578 assert(!Ops.empty() && "Cannot get empty umax!");
1579 if (Ops.size() == 1) return Ops[0];
1580
1581 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001582 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001583
1584 // If there are any constants, fold them together.
1585 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001586 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001587 ++Idx;
1588 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001589 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001590 // We found two constants, fold them together!
1591 ConstantInt *Fold = ConstantInt::get(
1592 APIntOps::umax(LHSC->getValue()->getValue(),
1593 RHSC->getValue()->getValue()));
1594 Ops[0] = getConstant(Fold);
1595 Ops.erase(Ops.begin()+1); // Erase the folded element
1596 if (Ops.size() == 1) return Ops[0];
1597 LHSC = cast<SCEVConstant>(Ops[0]);
1598 }
1599
1600 // If we are left with a constant zero, strip it off.
1601 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1602 Ops.erase(Ops.begin());
1603 --Idx;
1604 }
1605 }
1606
1607 if (Ops.size() == 1) return Ops[0];
1608
1609 // Find the first UMax
1610 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1611 ++Idx;
1612
1613 // Check to see if one of the operands is a UMax. If so, expand its operands
1614 // onto our operand list, and recurse to simplify.
1615 if (Idx < Ops.size()) {
1616 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001617 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001618 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1619 Ops.erase(Ops.begin()+Idx);
1620 DeletedUMax = true;
1621 }
1622
1623 if (DeletedUMax)
1624 return getUMaxExpr(Ops);
1625 }
1626
1627 // Okay, check to see if the same value occurs in the operand list twice. If
1628 // so, delete one. Since we sorted the list, these values are required to
1629 // be adjacent.
1630 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1631 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1632 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1633 --i; --e;
1634 }
1635
1636 if (Ops.size() == 1) return Ops[0];
1637
1638 assert(!Ops.empty() && "Reduced umax down to nothing!");
1639
1640 // Okay, it looks like we really DO need a umax expr. Check to see if we
1641 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001642 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001643 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1644 SCEVOps)];
1645 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1646 return Result;
1647}
1648
Dan Gohman89f85052007-10-22 18:31:58 +00001649SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001650 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001651 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001652 if (isa<ConstantPointerNull>(V))
1653 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001654 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1655 if (Result == 0) Result = new SCEVUnknown(V);
1656 return Result;
1657}
1658
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001659//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660// Basic SCEV Analysis and PHI Idiom Recognition Code
1661//
1662
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001663/// isSCEVable - Test if values of the given type are analyzable within
1664/// the SCEV framework. This primarily includes integer types, and it
1665/// can optionally include pointer types if the ScalarEvolution class
1666/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001667bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001668 // Integers are always SCEVable.
1669 if (Ty->isInteger())
1670 return true;
1671
1672 // Pointers are SCEVable if TargetData information is available
1673 // to provide pointer size information.
1674 if (isa<PointerType>(Ty))
1675 return TD != NULL;
1676
1677 // Otherwise it's not SCEVable.
1678 return false;
1679}
1680
1681/// getTypeSizeInBits - Return the size in bits of the specified type,
1682/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001683uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001684 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1685
1686 // If we have a TargetData, use it!
1687 if (TD)
1688 return TD->getTypeSizeInBits(Ty);
1689
1690 // Otherwise, we support only integer types.
1691 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1692 return Ty->getPrimitiveSizeInBits();
1693}
1694
1695/// getEffectiveSCEVType - Return a type with the same bitwidth as
1696/// the given type and which represents how SCEV will treat the given
1697/// type, for which isSCEVable must return true. For pointer types,
1698/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001699const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001700 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1701
1702 if (Ty->isInteger())
1703 return Ty;
1704
1705 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1706 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001707}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001709SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001710 return UnknownValue;
1711}
1712
Dan Gohmand83d4af2009-05-04 22:20:30 +00001713/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001714/// computed.
1715bool ScalarEvolution::hasSCEV(Value *V) const {
1716 return Scalars.count(V);
1717}
1718
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1720/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001721SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001722 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723
Dan Gohmanbff6b582009-05-04 22:30:44 +00001724 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001725 if (I != Scalars.end()) return I->second;
1726 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001727 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001728 return S;
1729}
1730
Dan Gohman01c2ee72009-04-16 03:18:22 +00001731/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1732/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001733SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1734 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001735 Constant *C;
1736 if (Val == 0)
1737 C = Constant::getNullValue(Ty);
1738 else if (Ty->isFloatingPoint())
1739 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1740 APFloat::IEEEdouble, Val));
1741 else
1742 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001743 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001744}
1745
1746/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1747///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001748SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001749 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001750 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001751
1752 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001753 Ty = getEffectiveSCEVType(Ty);
1754 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001755}
1756
1757/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001758SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001759 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001760 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001761
1762 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001763 Ty = getEffectiveSCEVType(Ty);
1764 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001765 return getMinusSCEV(AllOnes, V);
1766}
1767
1768/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1769///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001770SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001771 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001772 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001773 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001774}
1775
1776/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1777/// input value to the specified type. If the type must be extended, it is zero
1778/// extended.
1779SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001780ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001781 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001782 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001783 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1784 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001785 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001786 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001787 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001788 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001789 return getTruncateExpr(V, Ty);
1790 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001791}
1792
1793/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1794/// input value to the specified type. If the type must be extended, it is sign
1795/// extended.
1796SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001797ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001798 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001799 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001800 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1801 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001802 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001803 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001804 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001805 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001806 return getTruncateExpr(V, Ty);
1807 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001808}
1809
Dan Gohmanac959332009-05-13 03:46:30 +00001810/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
1811/// input value to the specified type. If the type must be extended, it is zero
1812/// extended. The conversion must not be narrowing.
1813SCEVHandle
1814ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
1815 const Type *SrcTy = V->getType();
1816 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1817 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1818 "Cannot noop or zero extend with non-integer arguments!");
1819 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1820 "getNoopOrZeroExtend cannot truncate!");
1821 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1822 return V; // No conversion
1823 return getZeroExtendExpr(V, Ty);
1824}
1825
1826/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
1827/// input value to the specified type. If the type must be extended, it is sign
1828/// extended. The conversion must not be narrowing.
1829SCEVHandle
1830ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
1831 const Type *SrcTy = V->getType();
1832 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1833 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1834 "Cannot noop or sign extend with non-integer arguments!");
1835 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1836 "getNoopOrSignExtend cannot truncate!");
1837 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1838 return V; // No conversion
1839 return getSignExtendExpr(V, Ty);
1840}
1841
1842/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
1843/// input value to the specified type. The conversion must not be widening.
1844SCEVHandle
1845ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
1846 const Type *SrcTy = V->getType();
1847 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1848 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1849 "Cannot truncate or noop with non-integer arguments!");
1850 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
1851 "getTruncateOrNoop cannot extend!");
1852 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1853 return V; // No conversion
1854 return getTruncateExpr(V, Ty);
1855}
1856
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1858/// the specified instruction and replaces any references to the symbolic value
1859/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001860void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1862 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001863 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1864 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001865 if (SI == Scalars.end()) return;
1866
1867 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001868 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001869 if (NV == SI->second) return; // No change.
1870
1871 SI->second = NV; // Update the scalars map!
1872
1873 // Any instruction values that use this instruction might also need to be
1874 // updated!
1875 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1876 UI != E; ++UI)
1877 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1878}
1879
1880/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1881/// a loop header, making it a potential recurrence, or it doesn't.
1882///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001883SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001884 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001885 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001886 if (L->getHeader() == PN->getParent()) {
1887 // If it lives in the loop header, it has two incoming values, one
1888 // from outside the loop, and one from inside.
1889 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1890 unsigned BackEdge = IncomingEdge^1;
1891
1892 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001893 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001894 assert(Scalars.find(PN) == Scalars.end() &&
1895 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00001896 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001897
1898 // Using this symbolic name for the PHI, analyze the value coming around
1899 // the back-edge.
1900 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1901
1902 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1903 // has a special value for the first iteration of the loop.
1904
1905 // If the value coming around the backedge is an add with the symbolic
1906 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00001907 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001908 // If there is a single occurrence of the symbolic value, replace it
1909 // with a recurrence.
1910 unsigned FoundIndex = Add->getNumOperands();
1911 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1912 if (Add->getOperand(i) == SymbolicName)
1913 if (FoundIndex == e) {
1914 FoundIndex = i;
1915 break;
1916 }
1917
1918 if (FoundIndex != Add->getNumOperands()) {
1919 // Create an add with everything but the specified operand.
1920 std::vector<SCEVHandle> Ops;
1921 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1922 if (i != FoundIndex)
1923 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001924 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001925
1926 // This is not a valid addrec if the step amount is varying each
1927 // loop iteration, but is not itself an addrec in this loop.
1928 if (Accum->isLoopInvariant(L) ||
1929 (isa<SCEVAddRecExpr>(Accum) &&
1930 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1931 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001932 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001933
1934 // Okay, for the entire analysis of this edge we assumed the PHI
1935 // to be symbolic. We now need to go back and update all of the
1936 // entries for the scalars that use the PHI (except for the PHI
1937 // itself) to use the new analyzed value instead of the "symbolic"
1938 // value.
1939 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1940 return PHISCEV;
1941 }
1942 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00001943 } else if (const SCEVAddRecExpr *AddRec =
1944 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001945 // Otherwise, this could be a loop like this:
1946 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1947 // In this case, j = {1,+,1} and BEValue is j.
1948 // Because the other in-value of i (0) fits the evolution of BEValue
1949 // i really is an addrec evolution.
1950 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1951 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1952
1953 // If StartVal = j.start - j.stride, we can use StartVal as the
1954 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001955 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001956 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001957 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001958 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001959
1960 // Okay, for the entire analysis of this edge we assumed the PHI
1961 // to be symbolic. We now need to go back and update all of the
1962 // entries for the scalars that use the PHI (except for the PHI
1963 // itself) to use the new analyzed value instead of the "symbolic"
1964 // value.
1965 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1966 return PHISCEV;
1967 }
1968 }
1969 }
1970
1971 return SymbolicName;
1972 }
1973
1974 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001975 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976}
1977
Dan Gohman509cf4d2009-05-08 20:26:55 +00001978/// createNodeForGEP - Expand GEP instructions into add and multiply
1979/// operations. This allows them to be analyzed by regular SCEV code.
1980///
Dan Gohmanca5a39e2009-05-08 20:58:38 +00001981SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00001982
1983 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00001984 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00001985 // Don't attempt to analyze GEPs over unsized objects.
1986 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
1987 return getUnknown(GEP);
Dan Gohman509cf4d2009-05-08 20:26:55 +00001988 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00001989 gep_type_iterator GTI = gep_type_begin(GEP);
1990 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
1991 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00001992 I != E; ++I) {
1993 Value *Index = *I;
1994 // Compute the (potentially symbolic) offset in bytes for this index.
1995 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1996 // For a struct, add the member offset.
1997 const StructLayout &SL = *TD->getStructLayout(STy);
1998 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1999 uint64_t Offset = SL.getElementOffset(FieldNo);
2000 TotalOffset = getAddExpr(TotalOffset,
2001 getIntegerSCEV(Offset, IntPtrTy));
2002 } else {
2003 // For an array, add the element offset, explicitly scaled.
2004 SCEVHandle LocalOffset = getSCEV(Index);
2005 if (!isa<PointerType>(LocalOffset->getType()))
2006 // Getelementptr indicies are signed.
2007 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2008 IntPtrTy);
2009 LocalOffset =
2010 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002011 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002012 IntPtrTy));
2013 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2014 }
2015 }
2016 return getAddExpr(getSCEV(Base), TotalOffset);
2017}
2018
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002019/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2020/// guaranteed to end in (at every loop iteration). It is, at the same time,
2021/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2022/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002023static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002024 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002025 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002026
Dan Gohmanc76b5452009-05-04 22:02:23 +00002027 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002028 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2029 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002030
Dan Gohmanc76b5452009-05-04 22:02:23 +00002031 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002032 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2033 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002034 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002035 }
2036
Dan Gohmanc76b5452009-05-04 22:02:23 +00002037 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002038 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2039 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002040 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002041 }
2042
Dan Gohmanc76b5452009-05-04 22:02:23 +00002043 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002044 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002045 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002046 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002047 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002048 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002049 }
2050
Dan Gohmanc76b5452009-05-04 22:02:23 +00002051 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002052 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002053 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2054 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002055 for (unsigned i = 1, e = M->getNumOperands();
2056 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002057 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002058 BitWidth);
2059 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002060 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002061
Dan Gohmanc76b5452009-05-04 22:02:23 +00002062 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002063 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002064 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002065 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002066 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002067 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002068 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002069
Dan Gohmanc76b5452009-05-04 22:02:23 +00002070 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002071 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002072 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00002073 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002074 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00002075 return MinOpRes;
2076 }
2077
Dan Gohmanc76b5452009-05-04 22:02:23 +00002078 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002079 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002080 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002081 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002082 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002083 return MinOpRes;
2084 }
2085
Nick Lewycky35b56022009-01-13 09:18:58 +00002086 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002087 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088}
2089
2090/// createSCEV - We know that there is no SCEV for the specified value.
2091/// Analyze the expression.
2092///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002093SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002094 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002095 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002096
Dan Gohman3996f472008-06-22 19:56:46 +00002097 unsigned Opcode = Instruction::UserOp1;
2098 if (Instruction *I = dyn_cast<Instruction>(V))
2099 Opcode = I->getOpcode();
2100 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2101 Opcode = CE->getOpcode();
2102 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002103 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104
Dan Gohman3996f472008-06-22 19:56:46 +00002105 User *U = cast<User>(V);
2106 switch (Opcode) {
2107 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002108 return getAddExpr(getSCEV(U->getOperand(0)),
2109 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002110 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002111 return getMulExpr(getSCEV(U->getOperand(0)),
2112 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002113 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002114 return getUDivExpr(getSCEV(U->getOperand(0)),
2115 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002116 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002117 return getMinusSCEV(getSCEV(U->getOperand(0)),
2118 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002119 case Instruction::And:
2120 // For an expression like x&255 that merely masks off the high bits,
2121 // use zext(trunc(x)) as the SCEV expression.
2122 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002123 if (CI->isNullValue())
2124 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002125 if (CI->isAllOnesValue())
2126 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002127 const APInt &A = CI->getValue();
2128 unsigned Ones = A.countTrailingOnes();
2129 if (APIntOps::isMask(Ones, A))
2130 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002131 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2132 IntegerType::get(Ones)),
2133 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002134 }
2135 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002136 case Instruction::Or:
2137 // If the RHS of the Or is a constant, we may have something like:
2138 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2139 // optimizations will transparently handle this case.
2140 //
2141 // In order for this transformation to be safe, the LHS must be of the
2142 // form X*(2^n) and the Or constant must be less than 2^n.
2143 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2144 SCEVHandle LHS = getSCEV(U->getOperand(0));
2145 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002146 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002147 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002148 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002149 }
Dan Gohman3996f472008-06-22 19:56:46 +00002150 break;
2151 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002152 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002153 // If the RHS of the xor is a signbit, then this is just an add.
2154 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002155 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002156 return getAddExpr(getSCEV(U->getOperand(0)),
2157 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002158
2159 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00002160 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002161 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00002162 }
2163 break;
2164
2165 case Instruction::Shl:
2166 // Turn shift left of a constant amount into a multiply.
2167 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2168 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2169 Constant *X = ConstantInt::get(
2170 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002171 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002172 }
2173 break;
2174
Nick Lewycky7fd27892008-07-07 06:15:49 +00002175 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002176 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002177 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2178 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2179 Constant *X = ConstantInt::get(
2180 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002181 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002182 }
2183 break;
2184
Dan Gohman53bf64a2009-04-21 02:26:00 +00002185 case Instruction::AShr:
2186 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2187 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2188 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2189 if (L->getOpcode() == Instruction::Shl &&
2190 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002191 unsigned BitWidth = getTypeSizeInBits(U->getType());
2192 uint64_t Amt = BitWidth - CI->getZExtValue();
2193 if (Amt == BitWidth)
2194 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2195 if (Amt > BitWidth)
2196 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002197 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002198 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002199 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002200 U->getType());
2201 }
2202 break;
2203
Dan Gohman3996f472008-06-22 19:56:46 +00002204 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002205 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002206
2207 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002208 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002209
2210 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002211 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002212
2213 case Instruction::BitCast:
2214 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002215 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002216 return getSCEV(U->getOperand(0));
2217 break;
2218
Dan Gohman01c2ee72009-04-16 03:18:22 +00002219 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002220 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002221 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002222 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002223
2224 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002225 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002226 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2227 U->getType());
2228
Dan Gohman509cf4d2009-05-08 20:26:55 +00002229 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002230 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002231 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002232
Dan Gohman3996f472008-06-22 19:56:46 +00002233 case Instruction::PHI:
2234 return createNodeForPHI(cast<PHINode>(U));
2235
2236 case Instruction::Select:
2237 // This could be a smax or umax that was lowered earlier.
2238 // Try to recover it.
2239 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2240 Value *LHS = ICI->getOperand(0);
2241 Value *RHS = ICI->getOperand(1);
2242 switch (ICI->getPredicate()) {
2243 case ICmpInst::ICMP_SLT:
2244 case ICmpInst::ICMP_SLE:
2245 std::swap(LHS, RHS);
2246 // fall through
2247 case ICmpInst::ICMP_SGT:
2248 case ICmpInst::ICMP_SGE:
2249 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002250 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002251 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002252 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002253 return getNotSCEV(getSMaxExpr(
2254 getNotSCEV(getSCEV(LHS)),
2255 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002256 break;
2257 case ICmpInst::ICMP_ULT:
2258 case ICmpInst::ICMP_ULE:
2259 std::swap(LHS, RHS);
2260 // fall through
2261 case ICmpInst::ICMP_UGT:
2262 case ICmpInst::ICMP_UGE:
2263 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002264 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002265 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2266 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002267 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2268 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002269 break;
2270 default:
2271 break;
2272 }
2273 }
2274
2275 default: // We cannot analyze this expression.
2276 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277 }
2278
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002279 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002280}
2281
2282
2283
2284//===----------------------------------------------------------------------===//
2285// Iteration Count Computation Code
2286//
2287
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002288/// getBackedgeTakenCount - If the specified loop has a predictable
2289/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2290/// object. The backedge-taken count is the number of times the loop header
2291/// will be branched to from within the loop. This is one less than the
2292/// trip count of the loop, since it doesn't count the first iteration,
2293/// when the header is branched to from outside the loop.
2294///
2295/// Note that it is not valid to call this method on a loop without a
2296/// loop-invariant backedge-taken count (see
2297/// hasLoopInvariantBackedgeTakenCount).
2298///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002299SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002300 return getBackedgeTakenInfo(L).Exact;
2301}
2302
2303/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2304/// return the least SCEV value that is known never to be less than the
2305/// actual backedge taken count.
2306SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2307 return getBackedgeTakenInfo(L).Max;
2308}
2309
2310const ScalarEvolution::BackedgeTakenInfo &
2311ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002312 // Initially insert a CouldNotCompute for this loop. If the insertion
2313 // succeeds, procede to actually compute a backedge-taken count and
2314 // update the value. The temporary CouldNotCompute value tells SCEV
2315 // code elsewhere that it shouldn't attempt to request a new
2316 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002317 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002318 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2319 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002320 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2321 if (ItCount.Exact != UnknownValue) {
2322 assert(ItCount.Exact->isLoopInvariant(L) &&
2323 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 "Computed trip count isn't loop invariant for loop!");
2325 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002326
Dan Gohmana9dba962009-04-27 20:16:15 +00002327 // Update the value in the map.
2328 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002329 } else if (isa<PHINode>(L->getHeader()->begin())) {
2330 // Only count loops that have phi nodes as not being computable.
2331 ++NumTripCountsNotComputed;
2332 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002333
2334 // Now that we know more about the trip count for this loop, forget any
2335 // existing SCEV values for PHI nodes in this loop since they are only
2336 // conservative estimates made without the benefit
2337 // of trip count information.
2338 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002339 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002340 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002341 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002342}
2343
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002344/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002345/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002346/// ScalarEvolution's ability to compute a trip count, or if the loop
2347/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002348void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002349 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002350 forgetLoopPHIs(L);
2351}
2352
2353/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2354/// PHI nodes in the given loop. This is used when the trip count of
2355/// the loop may have changed.
2356void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002357 BasicBlock *Header = L->getHeader();
2358
Dan Gohman9fd4a002009-05-12 01:27:58 +00002359 // Push all Loop-header PHIs onto the Worklist stack, except those
2360 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2361 // a PHI either means that it has an unrecognized structure, or it's
2362 // a PHI that's in the progress of being computed by createNodeForPHI.
2363 // In the former case, additional loop trip count information isn't
2364 // going to change anything. In the later case, createNodeForPHI will
2365 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002366 SmallVector<Instruction *, 16> Worklist;
2367 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002368 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2369 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2370 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2371 Worklist.push_back(PN);
2372 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002373
2374 while (!Worklist.empty()) {
2375 Instruction *I = Worklist.pop_back_val();
2376 if (Scalars.erase(I))
2377 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2378 UI != UE; ++UI)
2379 Worklist.push_back(cast<Instruction>(UI));
2380 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002381}
2382
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002383/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2384/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002385ScalarEvolution::BackedgeTakenInfo
2386ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002387 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002388 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002389 L->getExitBlocks(ExitBlocks);
2390 if (ExitBlocks.size() != 1) return UnknownValue;
2391
2392 // Okay, there is one exit block. Try to find the condition that causes the
2393 // loop to be exited.
2394 BasicBlock *ExitBlock = ExitBlocks[0];
2395
2396 BasicBlock *ExitingBlock = 0;
2397 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2398 PI != E; ++PI)
2399 if (L->contains(*PI)) {
2400 if (ExitingBlock == 0)
2401 ExitingBlock = *PI;
2402 else
2403 return UnknownValue; // More than one block exiting!
2404 }
2405 assert(ExitingBlock && "No exits from loop, something is broken!");
2406
2407 // Okay, we've computed the exiting block. See what condition causes us to
2408 // exit.
2409 //
2410 // FIXME: we should be able to handle switch instructions (with a single exit)
2411 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2412 if (ExitBr == 0) return UnknownValue;
2413 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2414
2415 // At this point, we know we have a conditional branch that determines whether
2416 // the loop is exited. However, we don't know if the branch is executed each
2417 // time through the loop. If not, then the execution count of the branch will
2418 // not be equal to the trip count of the loop.
2419 //
2420 // Currently we check for this by checking to see if the Exit branch goes to
2421 // the loop header. If so, we know it will always execute the same number of
2422 // times as the loop. We also handle the case where the exit block *is* the
2423 // loop header. This is common for un-rotated loops. More extensive analysis
2424 // could be done to handle more cases here.
2425 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2426 ExitBr->getSuccessor(1) != L->getHeader() &&
2427 ExitBr->getParent() != L->getHeader())
2428 return UnknownValue;
2429
2430 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2431
Eli Friedman459d7292009-05-09 12:32:42 +00002432 // If it's not an integer or pointer comparison then compute it the hard way.
2433 if (ExitCond == 0)
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002434 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002435 ExitBr->getSuccessor(0) == ExitBlock);
2436
2437 // If the condition was exit on true, convert the condition to exit on false
2438 ICmpInst::Predicate Cond;
2439 if (ExitBr->getSuccessor(1) == ExitBlock)
2440 Cond = ExitCond->getPredicate();
2441 else
2442 Cond = ExitCond->getInversePredicate();
2443
2444 // Handle common loops like: for (X = "string"; *X; ++X)
2445 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2446 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2447 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002448 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002449 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2450 }
2451
2452 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2453 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2454
2455 // Try to evaluate any dependencies out of the loop.
2456 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2457 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2458 Tmp = getSCEVAtScope(RHS, L);
2459 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2460
2461 // At this point, we would like to compute how many iterations of the
2462 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002463 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2464 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 std::swap(LHS, RHS);
2466 Cond = ICmpInst::getSwappedPredicate(Cond);
2467 }
2468
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002469 // If we have a comparison of a chrec against a constant, try to use value
2470 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002471 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2472 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00002474 // Form the constant range.
2475 ConstantRange CompRange(
2476 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002477
Eli Friedman459d7292009-05-09 12:32:42 +00002478 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2479 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002480 }
2481
2482 switch (Cond) {
2483 case ICmpInst::ICMP_NE: { // while (X != Y)
2484 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002485 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2487 break;
2488 }
2489 case ICmpInst::ICMP_EQ: {
2490 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002491 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002492 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2493 break;
2494 }
2495 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002496 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2497 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002498 break;
2499 }
2500 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002501 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2502 getNotSCEV(RHS), L, true);
2503 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002504 break;
2505 }
2506 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002507 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2508 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002509 break;
2510 }
2511 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002512 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2513 getNotSCEV(RHS), L, false);
2514 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 break;
2516 }
2517 default:
2518#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002519 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002520 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002521 errs() << "[unsigned] ";
2522 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002523 << Instruction::getOpcodeName(Instruction::ICmp)
2524 << " " << *RHS << "\n";
2525#endif
2526 break;
2527 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002528 return
2529 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2530 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002531}
2532
2533static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002534EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2535 ScalarEvolution &SE) {
2536 SCEVHandle InVal = SE.getConstant(C);
2537 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002538 assert(isa<SCEVConstant>(Val) &&
2539 "Evaluation of SCEV at constant didn't fold correctly?");
2540 return cast<SCEVConstant>(Val)->getValue();
2541}
2542
2543/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2544/// and a GEP expression (missing the pointer index) indexing into it, return
2545/// the addressed element of the initializer or null if the index expression is
2546/// invalid.
2547static Constant *
2548GetAddressedElementFromGlobal(GlobalVariable *GV,
2549 const std::vector<ConstantInt*> &Indices) {
2550 Constant *Init = GV->getInitializer();
2551 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2552 uint64_t Idx = Indices[i]->getZExtValue();
2553 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2554 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2555 Init = cast<Constant>(CS->getOperand(Idx));
2556 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2557 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2558 Init = cast<Constant>(CA->getOperand(Idx));
2559 } else if (isa<ConstantAggregateZero>(Init)) {
2560 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2561 assert(Idx < STy->getNumElements() && "Bad struct index!");
2562 Init = Constant::getNullValue(STy->getElementType(Idx));
2563 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2564 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2565 Init = Constant::getNullValue(ATy->getElementType());
2566 } else {
2567 assert(0 && "Unknown constant aggregate type!");
2568 }
2569 return 0;
2570 } else {
2571 return 0; // Unknown initializer type
2572 }
2573 }
2574 return Init;
2575}
2576
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002577/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2578/// 'icmp op load X, cst', try to see if we can compute the backedge
2579/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002580SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002581ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2582 const Loop *L,
2583 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002584 if (LI->isVolatile()) return UnknownValue;
2585
2586 // Check to see if the loaded pointer is a getelementptr of a global.
2587 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2588 if (!GEP) return UnknownValue;
2589
2590 // Make sure that it is really a constant global we are gepping, with an
2591 // initializer, and make sure the first IDX is really 0.
2592 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2593 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2594 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2595 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2596 return UnknownValue;
2597
2598 // Okay, we allow one non-constant index into the GEP instruction.
2599 Value *VarIdx = 0;
2600 std::vector<ConstantInt*> Indexes;
2601 unsigned VarIdxNum = 0;
2602 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2603 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2604 Indexes.push_back(CI);
2605 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2606 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2607 VarIdx = GEP->getOperand(i);
2608 VarIdxNum = i-2;
2609 Indexes.push_back(0);
2610 }
2611
2612 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2613 // Check to see if X is a loop variant variable value now.
2614 SCEVHandle Idx = getSCEV(VarIdx);
2615 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2616 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2617
2618 // We can only recognize very limited forms of loop index expressions, in
2619 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002620 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002621 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2622 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2623 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2624 return UnknownValue;
2625
2626 unsigned MaxSteps = MaxBruteForceIterations;
2627 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2628 ConstantInt *ItCst =
2629 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002630 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002631
2632 // Form the GEP offset.
2633 Indexes[VarIdxNum] = Val;
2634
2635 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2636 if (Result == 0) break; // Cannot compute!
2637
2638 // Evaluate the condition for this iteration.
2639 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2640 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2641 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2642#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002643 errs() << "\n***\n*** Computed loop count " << *ItCst
2644 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2645 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002646#endif
2647 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002648 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002649 }
2650 }
2651 return UnknownValue;
2652}
2653
2654
2655/// CanConstantFold - Return true if we can constant fold an instruction of the
2656/// specified type, assuming that all operands were constants.
2657static bool CanConstantFold(const Instruction *I) {
2658 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2659 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2660 return true;
2661
2662 if (const CallInst *CI = dyn_cast<CallInst>(I))
2663 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002664 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002665 return false;
2666}
2667
2668/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2669/// in the loop that V is derived from. We allow arbitrary operations along the
2670/// way, but the operands of an operation must either be constants or a value
2671/// derived from a constant PHI. If this expression does not fit with these
2672/// constraints, return null.
2673static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2674 // If this is not an instruction, or if this is an instruction outside of the
2675 // loop, it can't be derived from a loop PHI.
2676 Instruction *I = dyn_cast<Instruction>(V);
2677 if (I == 0 || !L->contains(I->getParent())) return 0;
2678
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002679 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002680 if (L->getHeader() == I->getParent())
2681 return PN;
2682 else
2683 // We don't currently keep track of the control flow needed to evaluate
2684 // PHIs, so we cannot handle PHIs inside of loops.
2685 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002686 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002687
2688 // If we won't be able to constant fold this expression even if the operands
2689 // are constants, return early.
2690 if (!CanConstantFold(I)) return 0;
2691
2692 // Otherwise, we can evaluate this instruction if all of its operands are
2693 // constant or derived from a PHI node themselves.
2694 PHINode *PHI = 0;
2695 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2696 if (!(isa<Constant>(I->getOperand(Op)) ||
2697 isa<GlobalValue>(I->getOperand(Op)))) {
2698 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2699 if (P == 0) return 0; // Not evolving from PHI
2700 if (PHI == 0)
2701 PHI = P;
2702 else if (PHI != P)
2703 return 0; // Evolving from multiple different PHIs.
2704 }
2705
2706 // This is a expression evolving from a constant PHI!
2707 return PHI;
2708}
2709
2710/// EvaluateExpression - Given an expression that passes the
2711/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2712/// in the loop has the value PHIVal. If we can't fold this expression for some
2713/// reason, return null.
2714static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2715 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002716 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002717 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002718 Instruction *I = cast<Instruction>(V);
2719
2720 std::vector<Constant*> Operands;
2721 Operands.resize(I->getNumOperands());
2722
2723 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2724 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2725 if (Operands[i] == 0) return 0;
2726 }
2727
Chris Lattnerd6e56912007-12-10 22:53:04 +00002728 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2729 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2730 &Operands[0], Operands.size());
2731 else
2732 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2733 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002734}
2735
2736/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2737/// in the header of its containing loop, we know the loop executes a
2738/// constant number of times, and the PHI node is just a recurrence
2739/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002740Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002741getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002742 std::map<PHINode*, Constant*>::iterator I =
2743 ConstantEvolutionLoopExitValue.find(PN);
2744 if (I != ConstantEvolutionLoopExitValue.end())
2745 return I->second;
2746
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002747 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002748 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2749
2750 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2751
2752 // Since the loop is canonicalized, the PHI node must have two entries. One
2753 // entry must be a constant (coming in from outside of the loop), and the
2754 // second must be derived from the same PHI.
2755 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2756 Constant *StartCST =
2757 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2758 if (StartCST == 0)
2759 return RetVal = 0; // Must be a constant.
2760
2761 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2762 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2763 if (PN2 != PN)
2764 return RetVal = 0; // Not derived from same PHI.
2765
2766 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002767 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2769
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002770 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 unsigned IterationNum = 0;
2772 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2773 if (IterationNum == NumIterations)
2774 return RetVal = PHIVal; // Got exit value!
2775
2776 // Compute the value of the PHI node for the next iteration.
2777 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2778 if (NextPHI == PHIVal)
2779 return RetVal = NextPHI; // Stopped evolving!
2780 if (NextPHI == 0)
2781 return 0; // Couldn't evaluate!
2782 PHIVal = NextPHI;
2783 }
2784}
2785
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002786/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002787/// constant number of times (the condition evolves only from constants),
2788/// try to evaluate a few iterations of the loop until we get the exit
2789/// condition gets a value of ExitWhen (true or false). If we cannot
2790/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002791SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002792ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002793 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2794 if (PN == 0) return UnknownValue;
2795
2796 // Since the loop is canonicalized, the PHI node must have two entries. One
2797 // entry must be a constant (coming in from outside of the loop), and the
2798 // second must be derived from the same PHI.
2799 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2800 Constant *StartCST =
2801 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2802 if (StartCST == 0) return UnknownValue; // Must be a constant.
2803
2804 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2805 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2806 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2807
2808 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2809 // the loop symbolically to determine when the condition gets a value of
2810 // "ExitWhen".
2811 unsigned IterationNum = 0;
2812 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2813 for (Constant *PHIVal = StartCST;
2814 IterationNum != MaxIterations; ++IterationNum) {
2815 ConstantInt *CondVal =
2816 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2817
2818 // Couldn't symbolically evaluate.
2819 if (!CondVal) return UnknownValue;
2820
2821 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2822 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2823 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002824 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002825 }
2826
2827 // Compute the value of the PHI node for the next iteration.
2828 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2829 if (NextPHI == 0 || NextPHI == PHIVal)
2830 return UnknownValue; // Couldn't evaluate or not making progress...
2831 PHIVal = NextPHI;
2832 }
2833
2834 // Too many iterations were needed to evaluate.
2835 return UnknownValue;
2836}
2837
Dan Gohmandd40e9a2009-05-08 20:38:54 +00002838/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2839/// at the specified scope in the program. The L value specifies a loop
2840/// nest to evaluate the expression at, where null is the top-level or a
2841/// specified loop is immediately inside of the loop.
2842///
2843/// This method can be used to compute the exit value for a variable defined
2844/// in a loop by querying what the value will hold in the parent loop.
2845///
2846/// If this value is not computable at this scope, a SCEVCouldNotCompute
2847/// object is returned.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002848SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002849 // FIXME: this should be turned into a virtual method on SCEV!
2850
2851 if (isa<SCEVConstant>(V)) return V;
2852
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002853 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002854 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002855 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002856 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002857 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2859 if (PHINode *PN = dyn_cast<PHINode>(I))
2860 if (PN->getParent() == LI->getHeader()) {
2861 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002862 // to see if the loop that contains it has a known backedge-taken
2863 // count. If so, we may be able to force computation of the exit
2864 // value.
2865 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002866 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002867 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002868 // Okay, we know how many times the containing loop executes. If
2869 // this is a constant evolving PHI node, get the final value at
2870 // the specified iteration number.
2871 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002872 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002874 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002875 }
2876 }
2877
2878 // Okay, this is an expression that we cannot symbolically evaluate
2879 // into a SCEV. Check to see if it's possible to symbolically evaluate
2880 // the arguments into constants, and if so, try to constant propagate the
2881 // result. This is particularly useful for computing loop exit values.
2882 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00002883 // Check to see if we've folded this instruction at this loop before.
2884 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
2885 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
2886 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
2887 if (!Pair.second)
2888 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
2889
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002890 std::vector<Constant*> Operands;
2891 Operands.reserve(I->getNumOperands());
2892 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2893 Value *Op = I->getOperand(i);
2894 if (Constant *C = dyn_cast<Constant>(Op)) {
2895 Operands.push_back(C);
2896 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002897 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002898 // non-integer and non-pointer, don't even try to analyze them
2899 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002900 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002901 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002902
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002904 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002905 Constant *C = SC->getValue();
2906 if (C->getType() != Op->getType())
2907 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2908 Op->getType(),
2909 false),
2910 C, Op->getType());
2911 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002912 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002913 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2914 if (C->getType() != Op->getType())
2915 C =
2916 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2917 Op->getType(),
2918 false),
2919 C, Op->getType());
2920 Operands.push_back(C);
2921 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002922 return V;
2923 } else {
2924 return V;
2925 }
2926 }
2927 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002928
2929 Constant *C;
2930 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2931 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2932 &Operands[0], Operands.size());
2933 else
2934 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2935 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00002936 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002937 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002938 }
2939 }
2940
2941 // This is some other type of SCEVUnknown, just return it.
2942 return V;
2943 }
2944
Dan Gohmanc76b5452009-05-04 22:02:23 +00002945 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002946 // Avoid performing the look-up in the common case where the specified
2947 // expression has no loop-variant portions.
2948 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2949 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2950 if (OpAtScope != Comm->getOperand(i)) {
2951 if (OpAtScope == UnknownValue) return UnknownValue;
2952 // Okay, at least one of these operands is loop variant but might be
2953 // foldable. Build a new instance of the folded commutative expression.
2954 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2955 NewOps.push_back(OpAtScope);
2956
2957 for (++i; i != e; ++i) {
2958 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2959 if (OpAtScope == UnknownValue) return UnknownValue;
2960 NewOps.push_back(OpAtScope);
2961 }
2962 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002963 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002964 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002965 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002966 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002967 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002968 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002969 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002970 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971 }
2972 }
2973 // If we got here, all operands are loop invariant.
2974 return Comm;
2975 }
2976
Dan Gohmanc76b5452009-05-04 22:02:23 +00002977 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002978 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002980 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002982 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2983 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002984 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002985 }
2986
2987 // If this is a loop recurrence for a loop that does not contain L, then we
2988 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002989 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002990 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2991 // To evaluate this recurrence, we need to know how many times the AddRec
2992 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002993 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2994 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995
Eli Friedman7489ec92008-08-04 23:49:06 +00002996 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002997 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998 }
2999 return UnknownValue;
3000 }
3001
Dan Gohmanc76b5452009-05-04 22:02:23 +00003002 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003003 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3004 if (Op == UnknownValue) return Op;
3005 if (Op == Cast->getOperand())
3006 return Cast; // must be loop invariant
3007 return getZeroExtendExpr(Op, Cast->getType());
3008 }
3009
Dan Gohmanc76b5452009-05-04 22:02:23 +00003010 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003011 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3012 if (Op == UnknownValue) return Op;
3013 if (Op == Cast->getOperand())
3014 return Cast; // must be loop invariant
3015 return getSignExtendExpr(Op, Cast->getType());
3016 }
3017
Dan Gohmanc76b5452009-05-04 22:02:23 +00003018 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003019 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3020 if (Op == UnknownValue) return Op;
3021 if (Op == Cast->getOperand())
3022 return Cast; // must be loop invariant
3023 return getTruncateExpr(Op, Cast->getType());
3024 }
3025
3026 assert(0 && "Unknown SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027}
3028
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003029/// getSCEVAtScope - This is a convenience function which does
3030/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003031SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3032 return getSCEVAtScope(getSCEV(V), L);
3033}
3034
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003035/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3036/// following equation:
3037///
3038/// A * X = B (mod N)
3039///
3040/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3041/// A and B isn't important.
3042///
3043/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3044static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3045 ScalarEvolution &SE) {
3046 uint32_t BW = A.getBitWidth();
3047 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3048 assert(A != 0 && "A must be non-zero.");
3049
3050 // 1. D = gcd(A, N)
3051 //
3052 // The gcd of A and N may have only one prime factor: 2. The number of
3053 // trailing zeros in A is its multiplicity
3054 uint32_t Mult2 = A.countTrailingZeros();
3055 // D = 2^Mult2
3056
3057 // 2. Check if B is divisible by D.
3058 //
3059 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3060 // is not less than multiplicity of this prime factor for D.
3061 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003062 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003063
3064 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3065 // modulo (N / D).
3066 //
3067 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3068 // bit width during computations.
3069 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3070 APInt Mod(BW + 1, 0);
3071 Mod.set(BW - Mult2); // Mod = N / D
3072 APInt I = AD.multiplicativeInverse(Mod);
3073
3074 // 4. Compute the minimum unsigned root of the equation:
3075 // I * (B / D) mod (N / D)
3076 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3077
3078 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3079 // bits.
3080 return SE.getConstant(Result.trunc(BW));
3081}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003082
3083/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3084/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3085/// might be the same) or two SCEVCouldNotCompute objects.
3086///
3087static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00003088SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003090 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3091 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3092 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003093
3094 // We currently can only solve this if the coefficients are constants.
3095 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003096 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097 return std::make_pair(CNC, CNC);
3098 }
3099
3100 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3101 const APInt &L = LC->getValue()->getValue();
3102 const APInt &M = MC->getValue()->getValue();
3103 const APInt &N = NC->getValue()->getValue();
3104 APInt Two(BitWidth, 2);
3105 APInt Four(BitWidth, 4);
3106
3107 {
3108 using namespace APIntOps;
3109 const APInt& C = L;
3110 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3111 // The B coefficient is M-N/2
3112 APInt B(M);
3113 B -= sdiv(N,Two);
3114
3115 // The A coefficient is N/2
3116 APInt A(N.sdiv(Two));
3117
3118 // Compute the B^2-4ac term.
3119 APInt SqrtTerm(B);
3120 SqrtTerm *= B;
3121 SqrtTerm -= Four * (A * C);
3122
3123 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3124 // integer value or else APInt::sqrt() will assert.
3125 APInt SqrtVal(SqrtTerm.sqrt());
3126
3127 // Compute the two solutions for the quadratic formula.
3128 // The divisions must be performed as signed divisions.
3129 APInt NegB(-B);
3130 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003131 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003132 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003133 return std::make_pair(CNC, CNC);
3134 }
3135
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003136 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3137 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3138
Dan Gohman89f85052007-10-22 18:31:58 +00003139 return std::make_pair(SE.getConstant(Solution1),
3140 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003141 } // end APIntOps namespace
3142}
3143
3144/// HowFarToZero - Return the number of times a backedge comparing the specified
3145/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00003146SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003148 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003149 // If the value is already zero, the branch will execute zero times.
3150 if (C->getValue()->isZero()) return C;
3151 return UnknownValue; // Otherwise it will loop infinitely.
3152 }
3153
Dan Gohmanbff6b582009-05-04 22:30:44 +00003154 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 if (!AddRec || AddRec->getLoop() != L)
3156 return UnknownValue;
3157
3158 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003159 // If this is an affine expression, the execution count of this branch is
3160 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003162 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003163 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003164 // equivalent to:
3165 //
3166 // Step*N = -Start (mod 2^BW)
3167 //
3168 // where BW is the common bit width of Start and Step.
3169
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003170 // Get the initial value for the loop.
3171 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3172 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003174 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175
Dan Gohmanc76b5452009-05-04 22:02:23 +00003176 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003177 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003178
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003179 // First, handle unitary steps.
3180 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003181 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003182 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3183 return Start; // N = Start (as unsigned)
3184
3185 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003186 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003187 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003188 -StartC->getValue()->getValue(),
3189 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003190 }
3191 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3192 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3193 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003194 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3195 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003196 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3197 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 if (R1) {
3199#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003200 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3201 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003202#endif
3203 // Pick the smallest positive root value.
3204 if (ConstantInt *CB =
3205 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3206 R1->getValue(), R2->getValue()))) {
3207 if (CB->getZExtValue() == false)
3208 std::swap(R1, R2); // R1 is the minimum root now.
3209
3210 // We can only use this value if the chrec ends up with an exact zero
3211 // value at this index. When solving for "X*X != 5", for example, we
3212 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003213 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003214 if (Val->isZero())
3215 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216 }
3217 }
3218 }
3219
3220 return UnknownValue;
3221}
3222
3223/// HowFarToNonZero - Return the number of times a backedge checking the
3224/// specified value for nonzero will execute. If not computable, return
3225/// UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00003226SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003227 // Loops that look like: while (X == 0) are very strange indeed. We don't
3228 // handle them yet except for the trivial case. This could be expanded in the
3229 // future as needed.
3230
3231 // If the value is a constant, check to see if it is known to be non-zero
3232 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003233 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003234 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003235 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003236 return UnknownValue; // Otherwise it will loop infinitely.
3237 }
3238
3239 // We could implement others, but I really doubt anyone writes loops like
3240 // this, and if they did, they would already be constant folded.
3241 return UnknownValue;
3242}
3243
Dan Gohman1cddf972008-09-15 22:18:04 +00003244/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3245/// (which may not be an immediate predecessor) which has exactly one
3246/// successor from which BB is reachable, or null if no such block is
3247/// found.
3248///
3249BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003250ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003251 // If the block has a unique predecessor, then there is no path from the
3252 // predecessor to the block that does not go through the direct edge
3253 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003254 if (BasicBlock *Pred = BB->getSinglePredecessor())
3255 return Pred;
3256
3257 // A loop's header is defined to be a block that dominates the loop.
3258 // If the loop has a preheader, it must be a block that has exactly
3259 // one successor that can reach BB. This is slightly more strict
3260 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003261 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00003262 return L->getLoopPreheader();
3263
3264 return 0;
3265}
3266
Dan Gohmancacd2012009-02-12 22:19:27 +00003267/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003268/// a conditional between LHS and RHS. This is used to help avoid max
3269/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003270bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003271 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003272 const SCEV *LHS, const SCEV *RHS) {
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003273 BasicBlock *Preheader = L->getLoopPreheader();
3274 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003275
Dan Gohmanab678fb2008-08-12 20:17:31 +00003276 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003277 // there are predecessors that can be found that have unique successors
3278 // leading to the original header.
3279 for (; Preheader;
3280 PreheaderDest = Preheader,
3281 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003282
3283 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003284 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003285 if (!LoopEntryPredicate ||
3286 LoopEntryPredicate->isUnconditional())
3287 continue;
3288
3289 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3290 if (!ICI) continue;
3291
3292 // Now that we found a conditional branch that dominates the loop, check to
3293 // see if it is the comparison we are looking for.
3294 Value *PreCondLHS = ICI->getOperand(0);
3295 Value *PreCondRHS = ICI->getOperand(1);
3296 ICmpInst::Predicate Cond;
3297 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3298 Cond = ICI->getPredicate();
3299 else
3300 Cond = ICI->getInversePredicate();
3301
Dan Gohmancacd2012009-02-12 22:19:27 +00003302 if (Cond == Pred)
3303 ; // An exact match.
3304 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3305 ; // The actual condition is beyond sufficient.
3306 else
3307 // Check a few special cases.
3308 switch (Cond) {
3309 case ICmpInst::ICMP_UGT:
3310 if (Pred == ICmpInst::ICMP_ULT) {
3311 std::swap(PreCondLHS, PreCondRHS);
3312 Cond = ICmpInst::ICMP_ULT;
3313 break;
3314 }
3315 continue;
3316 case ICmpInst::ICMP_SGT:
3317 if (Pred == ICmpInst::ICMP_SLT) {
3318 std::swap(PreCondLHS, PreCondRHS);
3319 Cond = ICmpInst::ICMP_SLT;
3320 break;
3321 }
3322 continue;
3323 case ICmpInst::ICMP_NE:
3324 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3325 // so check for this case by checking if the NE is comparing against
3326 // a minimum or maximum constant.
3327 if (!ICmpInst::isTrueWhenEqual(Pred))
3328 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3329 const APInt &A = CI->getValue();
3330 switch (Pred) {
3331 case ICmpInst::ICMP_SLT:
3332 if (A.isMaxSignedValue()) break;
3333 continue;
3334 case ICmpInst::ICMP_SGT:
3335 if (A.isMinSignedValue()) break;
3336 continue;
3337 case ICmpInst::ICMP_ULT:
3338 if (A.isMaxValue()) break;
3339 continue;
3340 case ICmpInst::ICMP_UGT:
3341 if (A.isMinValue()) break;
3342 continue;
3343 default:
3344 continue;
3345 }
3346 Cond = ICmpInst::ICMP_NE;
3347 // NE is symmetric but the original comparison may not be. Swap
3348 // the operands if necessary so that they match below.
3349 if (isa<SCEVConstant>(LHS))
3350 std::swap(PreCondLHS, PreCondRHS);
3351 break;
3352 }
3353 continue;
3354 default:
3355 // We weren't able to reconcile the condition.
3356 continue;
3357 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003358
3359 if (!PreCondLHS->getType()->isInteger()) continue;
3360
3361 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3362 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3363 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003364 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3365 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003366 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003367 }
3368
Dan Gohmanab678fb2008-08-12 20:17:31 +00003369 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003370}
3371
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003372/// HowManyLessThans - Return the number of times a backedge containing the
3373/// specified less-than comparison will execute. If not computable, return
3374/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003375ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003376HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3377 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378 // Only handle: "ADDREC < LoopInvariant".
3379 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3380
Dan Gohmanbff6b582009-05-04 22:30:44 +00003381 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003382 if (!AddRec || AddRec->getLoop() != L)
3383 return UnknownValue;
3384
3385 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003386 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003387 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3388 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3389 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3390
3391 // TODO: handle non-constant strides.
3392 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3393 if (!CStep || CStep->isZero())
3394 return UnknownValue;
3395 if (CStep->getValue()->getValue() == 1) {
3396 // With unit stride, the iteration never steps past the limit value.
3397 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3398 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3399 // Test whether a positive iteration iteration can step past the limit
3400 // value and past the maximum value for its type in a single step.
3401 if (isSigned) {
3402 APInt Max = APInt::getSignedMaxValue(BitWidth);
3403 if ((Max - CStep->getValue()->getValue())
3404 .slt(CLimit->getValue()->getValue()))
3405 return UnknownValue;
3406 } else {
3407 APInt Max = APInt::getMaxValue(BitWidth);
3408 if ((Max - CStep->getValue()->getValue())
3409 .ult(CLimit->getValue()->getValue()))
3410 return UnknownValue;
3411 }
3412 } else
3413 // TODO: handle non-constant limit values below.
3414 return UnknownValue;
3415 } else
3416 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 return UnknownValue;
3418
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003419 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3420 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3421 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003422 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003424 // First, we get the value of the LHS in the first iteration: n
3425 SCEVHandle Start = AddRec->getOperand(0);
3426
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003427 // Determine the minimum constant start value.
3428 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3429 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3430 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003431
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003432 // If we know that the condition is true in order to enter the loop,
3433 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3434 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3435 // division must round up.
3436 SCEVHandle End = RHS;
3437 if (!isLoopGuardedByCond(L,
3438 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3439 getMinusSCEV(Start, Step), RHS))
3440 End = isSigned ? getSMaxExpr(RHS, Start)
3441 : getUMaxExpr(RHS, Start);
3442
3443 // Determine the maximum constant end value.
3444 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3445 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3446 APInt::getMaxValue(BitWidth));
3447
3448 // Finally, we subtract these two values and divide, rounding up, to get
3449 // the number of times the backedge is executed.
3450 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3451 getAddExpr(Step, NegOne)),
3452 Step);
3453
3454 // The maximum backedge count is similar, except using the minimum start
3455 // value and the maximum end value.
3456 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3457 MinStart),
3458 getAddExpr(Step, NegOne)),
3459 Step);
3460
3461 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003462 }
3463
3464 return UnknownValue;
3465}
3466
3467/// getNumIterationsInRange - Return the number of iterations of this loop that
3468/// produce values in the specified constant range. Another way of looking at
3469/// this is that it returns the first iteration number where the value is not in
3470/// the condition, thus computing the exit count. If the iteration count can't
3471/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003472SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3473 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003474 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003475 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003476
3477 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003478 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003479 if (!SC->getValue()->isZero()) {
3480 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003481 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3482 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003483 if (const SCEVAddRecExpr *ShiftedAddRec =
3484 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003485 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003486 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003487 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003488 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003489 }
3490
3491 // The only time we can solve this is when we have all constant indices.
3492 // Otherwise, we cannot determine the overflow conditions.
3493 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3494 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003495 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003496
3497
3498 // Okay at this point we know that all elements of the chrec are constants and
3499 // that the start element is zero.
3500
3501 // First check to see if the range contains zero. If not, the first
3502 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003503 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003504 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003505 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506
3507 if (isAffine()) {
3508 // If this is an affine expression then we have this situation:
3509 // Solve {0,+,A} in Range === Ax in Range
3510
3511 // We know that zero is in the range. If A is positive then we know that
3512 // the upper value of the range must be the first possible exit value.
3513 // If A is negative then the lower of the range is the last possible loop
3514 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003515 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3517 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3518
3519 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003520 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3522
3523 // Evaluate at the exit value. If we really did fall out of the valid
3524 // range, then we computed our trip count, otherwise wrap around or other
3525 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003526 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003527 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003528 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003529
3530 // Ensure that the previous value is in the range. This is a sanity check.
3531 assert(Range.contains(
3532 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003533 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003535 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003536 } else if (isQuadratic()) {
3537 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3538 // quadratic equation to solve it. To do this, we must frame our problem in
3539 // terms of figuring out when zero is crossed, instead of when
3540 // Range.getUpper() is crossed.
3541 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003542 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3543 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003544
3545 // Next, solve the constructed addrec
3546 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003547 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003548 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3549 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 if (R1) {
3551 // Pick the smallest positive root value.
3552 if (ConstantInt *CB =
3553 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3554 R1->getValue(), R2->getValue()))) {
3555 if (CB->getZExtValue() == false)
3556 std::swap(R1, R2); // R1 is the minimum root now.
3557
3558 // Make sure the root is not off by one. The returned iteration should
3559 // not be in the range, but the previous one should be. When solving
3560 // for "X*X < 5", for example, we should not return a root of 2.
3561 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003562 R1->getValue(),
3563 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003564 if (Range.contains(R1Val->getValue())) {
3565 // The next iteration must be out of the range...
3566 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3567
Dan Gohman89f85052007-10-22 18:31:58 +00003568 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003569 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003570 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003571 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003572 }
3573
3574 // If R1 was not in the range, then it is a good return value. Make
3575 // sure that R1-1 WAS in the range though, just in case.
3576 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003577 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578 if (Range.contains(R1Val->getValue()))
3579 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003580 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003581 }
3582 }
3583 }
3584
Dan Gohman0ad08b02009-04-18 17:58:19 +00003585 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003586}
3587
3588
3589
3590//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003591// SCEVCallbackVH Class Implementation
3592//===----------------------------------------------------------------------===//
3593
3594void SCEVCallbackVH::deleted() {
3595 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3596 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3597 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003598 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3599 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003600 SE->Scalars.erase(getValPtr());
3601 // this now dangles!
3602}
3603
3604void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3605 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3606
3607 // Forget all the expressions associated with users of the old value,
3608 // so that future queries will recompute the expressions using the new
3609 // value.
3610 SmallVector<User *, 16> Worklist;
3611 Value *Old = getValPtr();
3612 bool DeleteOld = false;
3613 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3614 UI != UE; ++UI)
3615 Worklist.push_back(*UI);
3616 while (!Worklist.empty()) {
3617 User *U = Worklist.pop_back_val();
3618 // Deleting the Old value will cause this to dangle. Postpone
3619 // that until everything else is done.
3620 if (U == Old) {
3621 DeleteOld = true;
3622 continue;
3623 }
3624 if (PHINode *PN = dyn_cast<PHINode>(U))
3625 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003626 if (Instruction *I = dyn_cast<Instruction>(U))
3627 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003628 if (SE->Scalars.erase(U))
3629 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3630 UI != UE; ++UI)
3631 Worklist.push_back(*UI);
3632 }
3633 if (DeleteOld) {
3634 if (PHINode *PN = dyn_cast<PHINode>(Old))
3635 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003636 if (Instruction *I = dyn_cast<Instruction>(Old))
3637 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003638 SE->Scalars.erase(Old);
3639 // this now dangles!
3640 }
3641 // this may dangle!
3642}
3643
3644SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3645 : CallbackVH(V), SE(se) {}
3646
3647//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003648// ScalarEvolution Class Implementation
3649//===----------------------------------------------------------------------===//
3650
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003651ScalarEvolution::ScalarEvolution()
3652 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3653}
3654
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003656 this->F = &F;
3657 LI = &getAnalysis<LoopInfo>();
3658 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003659 return false;
3660}
3661
3662void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003663 Scalars.clear();
3664 BackedgeTakenCounts.clear();
3665 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00003666 ValuesAtScopes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003667}
3668
3669void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3670 AU.setPreservesAll();
3671 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003672}
3673
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003674bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003675 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003676}
3677
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003678static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003679 const Loop *L) {
3680 // Print all inner loops first
3681 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3682 PrintLoopInfo(OS, SE, *I);
3683
Nick Lewyckye5da1912008-01-02 02:49:20 +00003684 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003685
Devang Patel02451fa2007-08-21 00:31:24 +00003686 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003687 L->getExitBlocks(ExitBlocks);
3688 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003689 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003690
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003691 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3692 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003694 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003695 }
3696
Nick Lewyckye5da1912008-01-02 02:49:20 +00003697 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698}
3699
Dan Gohman13058cc2009-04-21 00:47:46 +00003700void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003701 // ScalarEvolution's implementaiton of the print method is to print
3702 // out SCEV values of all instructions that are interesting. Doing
3703 // this potentially causes it to create new SCEV objects though,
3704 // which technically conflicts with the const qualifier. This isn't
3705 // observable from outside the class though (the hasSCEV function
3706 // notwithstanding), so casting away the const isn't dangerous.
3707 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003708
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003709 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003710 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003711 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003712 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003713 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003714 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003715 SV->print(OS);
3716 OS << "\t\t";
3717
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003718 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003719 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003720 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003721 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3722 OS << "<<Unknown>>";
3723 } else {
3724 OS << *ExitValue;
3725 }
3726 }
3727
3728
3729 OS << "\n";
3730 }
3731
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003732 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3733 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3734 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003735}
Dan Gohman13058cc2009-04-21 00:47:46 +00003736
3737void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3738 raw_os_ostream OS(o);
3739 print(OS, M);
3740}