blob: ca16a755dcab5f024fceaa522a4943c1fbe03650 [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"
69#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
73#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
77#include "llvm/Support/ManagedStatic.h"
78#include "llvm/Support/MathExtras.h"
79#include "llvm/Support/Streams.h"
80#include "llvm/ADT/Statistic.h"
81#include <ostream>
82#include <algorithm>
83#include <cmath>
84using namespace llvm;
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman089efff2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman089efff2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103char ScalarEvolution::ID = 0;
104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
112SCEV::~SCEV() {}
113void SCEV::dump() const {
114 print(cerr);
Nick Lewycky41153462009-01-16 17:07:22 +0000115 cerr << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116}
117
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118uint32_t SCEV::getBitWidth() const {
119 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
120 return ITy->getBitWidth();
121 return 0;
122}
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) {}
132
133bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
135 return false;
136}
137
138const Type *SCEVCouldNotCompute::getType() const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 return 0;
141}
142
143bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 return false;
146}
147
148SCEVHandle SCEVCouldNotCompute::
149replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000150 const SCEVHandle &Conc,
151 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 return this;
153}
154
155void SCEVCouldNotCompute::print(std::ostream &OS) const {
156 OS << "***COULDNOTCOMPUTE***";
157}
158
159bool SCEVCouldNotCompute::classof(const SCEV *S) {
160 return S->getSCEVType() == scCouldNotCompute;
161}
162
163
164// SCEVConstants - Only allow the creation of one SCEVConstant for any
165// particular value. Don't use a SCEVHandle here, or else the object will
166// never be deleted!
167static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
168
169
170SCEVConstant::~SCEVConstant() {
171 SCEVConstants->erase(V);
172}
173
Dan Gohman89f85052007-10-22 18:31:58 +0000174SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 SCEVConstant *&R = (*SCEVConstants)[V];
176 if (R == 0) R = new SCEVConstant(V);
177 return R;
178}
179
Dan Gohman89f85052007-10-22 18:31:58 +0000180SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
181 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182}
183
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184const Type *SCEVConstant::getType() const { return V->getType(); }
185
186void SCEVConstant::print(std::ostream &OS) const {
187 WriteAsOperand(OS, V, false);
188}
189
190// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
191// particular input. Don't use a SCEVHandle here, or else the object will
192// never be deleted!
193static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
194 SCEVTruncateExpr*> > SCEVTruncates;
195
196SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
197 : SCEV(scTruncate), Op(op), Ty(ty) {
198 assert(Op->getType()->isInteger() && Ty->isInteger() &&
199 "Cannot truncate non-integer value!");
200 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
201 && "This is not a truncating conversion!");
202}
203
204SCEVTruncateExpr::~SCEVTruncateExpr() {
205 SCEVTruncates->erase(std::make_pair(Op, Ty));
206}
207
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208void SCEVTruncateExpr::print(std::ostream &OS) const {
209 OS << "(truncate " << *Op << " to " << *Ty << ")";
210}
211
212// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
213// particular input. Don't use a SCEVHandle here, or else the object will never
214// be deleted!
215static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
216 SCEVZeroExtendExpr*> > SCEVZeroExtends;
217
218SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
219 : SCEV(scZeroExtend), Op(op), Ty(ty) {
220 assert(Op->getType()->isInteger() && Ty->isInteger() &&
221 "Cannot zero extend non-integer value!");
222 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
223 && "This is not an extending conversion!");
224}
225
226SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
227 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
228}
229
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230void SCEVZeroExtendExpr::print(std::ostream &OS) const {
231 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
232}
233
234// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
235// particular input. Don't use a SCEVHandle here, or else the object will never
236// be deleted!
237static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
238 SCEVSignExtendExpr*> > SCEVSignExtends;
239
240SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
241 : SCEV(scSignExtend), Op(op), Ty(ty) {
242 assert(Op->getType()->isInteger() && Ty->isInteger() &&
243 "Cannot sign extend non-integer value!");
244 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
245 && "This is not an extending conversion!");
246}
247
248SCEVSignExtendExpr::~SCEVSignExtendExpr() {
249 SCEVSignExtends->erase(std::make_pair(Op, Ty));
250}
251
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252void SCEVSignExtendExpr::print(std::ostream &OS) const {
253 OS << "(signextend " << *Op << " to " << *Ty << ")";
254}
255
256// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
257// particular input. Don't use a SCEVHandle here, or else the object will never
258// be deleted!
259static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
260 SCEVCommutativeExpr*> > SCEVCommExprs;
261
262SCEVCommutativeExpr::~SCEVCommutativeExpr() {
263 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
264 std::vector<SCEV*>(Operands.begin(),
265 Operands.end())));
266}
267
268void SCEVCommutativeExpr::print(std::ostream &OS) const {
269 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
270 const char *OpStr = getOperationStr();
271 OS << "(" << *Operands[0];
272 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
273 OS << OpStr << *Operands[i];
274 OS << ")";
275}
276
277SCEVHandle SCEVCommutativeExpr::
278replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000279 const SCEVHandle &Conc,
280 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000282 SCEVHandle H =
283 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 if (H != getOperand(i)) {
285 std::vector<SCEVHandle> NewOps;
286 NewOps.reserve(getNumOperands());
287 for (unsigned j = 0; j != i; ++j)
288 NewOps.push_back(getOperand(j));
289 NewOps.push_back(H);
290 for (++i; i != e; ++i)
291 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000292 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293
294 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000295 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000297 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000298 else if (isa<SCEVSMaxExpr>(this))
299 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000300 else if (isa<SCEVUMaxExpr>(this))
301 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 else
303 assert(0 && "Unknown commutative expr!");
304 }
305 }
306 return this;
307}
308
309
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000310// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311// input. Don't use a SCEVHandle here, or else the object will never be
312// deleted!
313static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000314 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000316SCEVUDivExpr::~SCEVUDivExpr() {
317 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318}
319
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000320void SCEVUDivExpr::print(std::ostream &OS) const {
321 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322}
323
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000324const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 return LHS->getType();
326}
327
328// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
329// particular input. Don't use a SCEVHandle here, or else the object will never
330// be deleted!
331static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
332 SCEVAddRecExpr*> > SCEVAddRecExprs;
333
334SCEVAddRecExpr::~SCEVAddRecExpr() {
335 SCEVAddRecExprs->erase(std::make_pair(L,
336 std::vector<SCEV*>(Operands.begin(),
337 Operands.end())));
338}
339
340SCEVHandle SCEVAddRecExpr::
341replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000342 const SCEVHandle &Conc,
343 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000345 SCEVHandle H =
346 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 if (H != getOperand(i)) {
348 std::vector<SCEVHandle> NewOps;
349 NewOps.reserve(getNumOperands());
350 for (unsigned j = 0; j != i; ++j)
351 NewOps.push_back(getOperand(j));
352 NewOps.push_back(H);
353 for (++i; i != e; ++i)
354 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000355 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356
Dan Gohman89f85052007-10-22 18:31:58 +0000357 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 }
359 }
360 return this;
361}
362
363
364bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
365 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
366 // contain L and if the start is invariant.
367 return !QueryLoop->contains(L->getHeader()) &&
368 getOperand(0)->isLoopInvariant(QueryLoop);
369}
370
371
372void SCEVAddRecExpr::print(std::ostream &OS) const {
373 OS << "{" << *Operands[0];
374 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
375 OS << ",+," << *Operands[i];
376 OS << "}<" << L->getHeader()->getName() + ">";
377}
378
379// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
380// value. Don't use a SCEVHandle here, or else the object will never be
381// deleted!
382static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
383
384SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
385
386bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
387 // All non-instruction values are loop invariant. All instructions are loop
388 // invariant if they are not contained in the specified loop.
389 if (Instruction *I = dyn_cast<Instruction>(V))
390 return !L->contains(I->getParent());
391 return true;
392}
393
394const Type *SCEVUnknown::getType() const {
395 return V->getType();
396}
397
398void SCEVUnknown::print(std::ostream &OS) const {
399 WriteAsOperand(OS, V, false);
400}
401
402//===----------------------------------------------------------------------===//
403// SCEV Utilities
404//===----------------------------------------------------------------------===//
405
406namespace {
407 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
408 /// than the complexity of the RHS. This comparator is used to canonicalize
409 /// expressions.
410 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000411 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000412 return LHS->getSCEVType() < RHS->getSCEVType();
413 }
414 };
415}
416
417/// GroupByComplexity - Given a list of SCEV objects, order them by their
418/// complexity, and group objects of the same complexity together by value.
419/// When this routine is finished, we know that any duplicates in the vector are
420/// consecutive and that complexity is monotonically increasing.
421///
422/// Note that we go take special precautions to ensure that we get determinstic
423/// results from this routine. In other words, we don't want the results of
424/// this to depend on where the addresses of various SCEV objects happened to
425/// land in memory.
426///
427static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
428 if (Ops.size() < 2) return; // Noop
429 if (Ops.size() == 2) {
430 // This is the common case, which also happens to be trivially simple.
431 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000432 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 std::swap(Ops[0], Ops[1]);
434 return;
435 }
436
437 // Do the rough sort by complexity.
438 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
439
440 // Now that we are sorted by complexity, group elements of the same
441 // complexity. Note that this is, at worst, N^2, but the vector is likely to
442 // be extremely short in practice. Note that we take this approach because we
443 // do not want to depend on the addresses of the objects we are grouping.
444 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
445 SCEV *S = Ops[i];
446 unsigned Complexity = S->getSCEVType();
447
448 // If there are any objects of the same complexity and same value as this
449 // one, group them.
450 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
451 if (Ops[j] == S) { // Found a duplicate.
452 // Move it to immediately after i'th element.
453 std::swap(Ops[i+1], Ops[j]);
454 ++i; // no need to rescan it.
455 if (i == e-2) return; // Done!
456 }
457 }
458 }
459}
460
461
462
463//===----------------------------------------------------------------------===//
464// Simple SCEV method implementations
465//===----------------------------------------------------------------------===//
466
467/// getIntegerSCEV - Given an integer or FP type, create a constant for the
468/// specified signed integer value and return a SCEV for the constant.
Dan Gohman89f85052007-10-22 18:31:58 +0000469SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 Constant *C;
471 if (Val == 0)
472 C = Constant::getNullValue(Ty);
473 else if (Ty->isFloatingPoint())
Chris Lattner5e0610f2008-04-20 00:41:09 +0000474 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
475 APFloat::IEEEdouble, Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 else
477 C = ConstantInt::get(Ty, Val);
Dan Gohman89f85052007-10-22 18:31:58 +0000478 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000479}
480
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
482///
Dan Gohman89f85052007-10-22 18:31:58 +0000483SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman89f85052007-10-22 18:31:58 +0000485 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486
Nick Lewycky0cf58682008-02-20 06:58:55 +0000487 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000488}
489
490/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
491SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
492 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
493 return getUnknown(ConstantExpr::getNot(VC->getValue()));
494
Nick Lewycky0cf58682008-02-20 06:58:55 +0000495 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000496 return getMinusSCEV(AllOnes, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497}
498
499/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
500///
Dan Gohman89f85052007-10-22 18:31:58 +0000501SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
502 const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 // X - Y --> X + -Y
Dan Gohman89f85052007-10-22 18:31:58 +0000504 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505}
506
507
Eli Friedman7489ec92008-08-04 23:49:06 +0000508/// BinomialCoefficient - Compute BC(It, K). The result has width W.
509// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000510static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000511 ScalarEvolution &SE,
512 const IntegerType* ResultTy) {
513 // Handle the simplest case efficiently.
514 if (K == 1)
515 return SE.getTruncateOrZeroExtend(It, ResultTy);
516
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000517 // We are using the following formula for BC(It, K):
518 //
519 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
520 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000521 // Suppose, W is the bitwidth of the return value. We must be prepared for
522 // overflow. Hence, we must assure that the result of our computation is
523 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
524 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000525 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000526 // However, this code doesn't use exactly that formula; the formula it uses
527 // is something like the following, where T is the number of factors of 2 in
528 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
529 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000530 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000531 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000532 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000533 // This formula is trivially equivalent to the previous formula. However,
534 // this formula can be implemented much more efficiently. The trick is that
535 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
536 // arithmetic. To do exact division in modular arithmetic, all we have
537 // to do is multiply by the inverse. Therefore, this step can be done at
538 // width W.
539 //
540 // The next issue is how to safely do the division by 2^T. The way this
541 // is done is by doing the multiplication step at a width of at least W + T
542 // bits. This way, the bottom W+T bits of the product are accurate. Then,
543 // when we perform the division by 2^T (which is equivalent to a right shift
544 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
545 // truncated out after the division by 2^T.
546 //
547 // In comparison to just directly using the first formula, this technique
548 // is much more efficient; using the first formula requires W * K bits,
549 // but this formula less than W + K bits. Also, the first formula requires
550 // a division step, whereas this formula only requires multiplies and shifts.
551 //
552 // It doesn't matter whether the subtraction step is done in the calculation
553 // width or the input iteration count's width; if the subtraction overflows,
554 // the result must be zero anyway. We prefer here to do it in the width of
555 // the induction variable because it helps a lot for certain cases; CodeGen
556 // isn't smart enough to ignore the overflow, which leads to much less
557 // efficient code if the width of the subtraction is wider than the native
558 // register width.
559 //
560 // (It's possible to not widen at all by pulling out factors of 2 before
561 // the multiplication; for example, K=2 can be calculated as
562 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
563 // extra arithmetic, so it's not an obvious win, and it gets
564 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000565
Eli Friedman7489ec92008-08-04 23:49:06 +0000566 // Protection from insane SCEVs; this bound is conservative,
567 // but it probably doesn't matter.
568 if (K > 1000)
569 return new SCEVCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000570
Eli Friedman7489ec92008-08-04 23:49:06 +0000571 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000572
Eli Friedman7489ec92008-08-04 23:49:06 +0000573 // Calculate K! / 2^T and T; we divide out the factors of two before
574 // multiplying for calculating K! / 2^T to avoid overflow.
575 // Other overflow doesn't matter because we only care about the bottom
576 // W bits of the result.
577 APInt OddFactorial(W, 1);
578 unsigned T = 1;
579 for (unsigned i = 3; i <= K; ++i) {
580 APInt Mult(W, i);
581 unsigned TwoFactors = Mult.countTrailingZeros();
582 T += TwoFactors;
583 Mult = Mult.lshr(TwoFactors);
584 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000586
Eli Friedman7489ec92008-08-04 23:49:06 +0000587 // We need at least W + T bits for the multiplication step
588 // FIXME: A temporary hack; we round up the bitwidths
589 // to the nearest power of 2 to be nice to the code generator.
590 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
591 // FIXME: Temporary hack to avoid generating integers that are too wide.
592 // Although, it's not completely clear how to determine how much
593 // widening is safe; for example, on X86, we can't really widen
594 // beyond 64 because we need to be able to do multiplication
595 // that's CalculationBits wide, but on X86-64, we can safely widen up to
596 // 128 bits.
597 if (CalculationBits > 64)
598 return new SCEVCouldNotCompute();
599
600 // Calcuate 2^T, at width T+W.
601 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
602
603 // Calculate the multiplicative inverse of K! / 2^T;
604 // this multiplication factor will perform the exact division by
605 // K! / 2^T.
606 APInt Mod = APInt::getSignedMinValue(W+1);
607 APInt MultiplyFactor = OddFactorial.zext(W+1);
608 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
609 MultiplyFactor = MultiplyFactor.trunc(W);
610
611 // Calculate the product, at width T+W
612 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
613 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
614 for (unsigned i = 1; i != K; ++i) {
615 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
616 Dividend = SE.getMulExpr(Dividend,
617 SE.getTruncateOrZeroExtend(S, CalculationTy));
618 }
619
620 // Divide by 2^T
621 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
622
623 // Truncate the result, and divide by K! / 2^T.
624
625 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
626 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627}
628
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629/// evaluateAtIteration - Return the value of this chain of recurrences at
630/// the specified iteration number. We can evaluate this recurrence by
631/// multiplying each element in the chain by the binomial coefficient
632/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
633///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000634/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000636/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637///
Dan Gohman89f85052007-10-22 18:31:58 +0000638SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
639 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000642 // The computation is correct in the face of overflow provided that the
643 // multiplication is performed _after_ the evaluation of the binomial
644 // coefficient.
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000645 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
646 cast<IntegerType>(getType()));
647 if (isa<SCEVCouldNotCompute>(Coeff))
648 return Coeff;
649
650 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 }
652 return Result;
653}
654
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655//===----------------------------------------------------------------------===//
656// SCEV Expression folder implementations
657//===----------------------------------------------------------------------===//
658
Dan Gohman89f85052007-10-22 18:31:58 +0000659SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000661 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662 ConstantExpr::getTrunc(SC->getValue(), Ty));
663
664 // If the input value is a chrec scev made out of constants, truncate
665 // all of the constants.
666 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
667 std::vector<SCEVHandle> Operands;
668 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
669 // FIXME: This should allow truncation of other expression types!
670 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000671 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672 else
673 break;
674 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000675 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676 }
677
678 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
679 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
680 return Result;
681}
682
Dan Gohman89f85052007-10-22 18:31:58 +0000683SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000685 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 ConstantExpr::getZExt(SC->getValue(), Ty));
687
688 // FIXME: If the input value is a chrec scev, and we can prove that the value
689 // did not overflow the old, smaller, value, we can zero extend all of the
690 // operands (often constants). This would allow analysis of something like
691 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
692
693 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
694 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
695 return Result;
696}
697
Dan Gohman89f85052007-10-22 18:31:58 +0000698SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000700 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701 ConstantExpr::getSExt(SC->getValue(), Ty));
702
703 // FIXME: If the input value is a chrec scev, and we can prove that the value
704 // did not overflow the old, smaller, value, we can sign extend all of the
705 // operands (often constants). This would allow analysis of something like
706 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
707
708 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
709 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
710 return Result;
711}
712
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000713/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
714/// of the input value to the specified type. If the type must be
715/// extended, it is zero extended.
716SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
717 const Type *Ty) {
718 const Type *SrcTy = V->getType();
719 assert(SrcTy->isInteger() && Ty->isInteger() &&
720 "Cannot truncate or zero extend with non-integer arguments!");
721 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
722 return V; // No conversion
723 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
724 return getTruncateExpr(V, Ty);
725 return getZeroExtendExpr(V, Ty);
726}
727
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000729SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000730 assert(!Ops.empty() && "Cannot get empty add!");
731 if (Ops.size() == 1) return Ops[0];
732
733 // Sort by complexity, this groups all similar expression types together.
734 GroupByComplexity(Ops);
735
736 // If there are any constants, fold them together.
737 unsigned Idx = 0;
738 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
739 ++Idx;
740 assert(Idx < Ops.size());
741 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
742 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000743 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
744 RHSC->getValue()->getValue());
745 Ops[0] = getConstant(Fold);
746 Ops.erase(Ops.begin()+1); // Erase the folded element
747 if (Ops.size() == 1) return Ops[0];
748 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 }
750
751 // If we are left with a constant zero being added, strip it off.
752 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
753 Ops.erase(Ops.begin());
754 --Idx;
755 }
756 }
757
758 if (Ops.size() == 1) return Ops[0];
759
760 // Okay, check to see if the same value occurs in the operand list twice. If
761 // so, merge them together into an multiply expression. Since we sorted the
762 // list, these values are required to be adjacent.
763 const Type *Ty = Ops[0]->getType();
764 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
765 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
766 // Found a match, merge the two values into a multiply, and add any
767 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000768 SCEVHandle Two = getIntegerSCEV(2, Ty);
769 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 if (Ops.size() == 2)
771 return Mul;
772 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
773 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000774 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 }
776
777 // Now we know the first non-constant operand. Skip past any cast SCEVs.
778 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
779 ++Idx;
780
781 // If there are add operands they would be next.
782 if (Idx < Ops.size()) {
783 bool DeletedAdd = false;
784 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
785 // If we have an add, expand the add operands onto the end of the operands
786 // list.
787 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
788 Ops.erase(Ops.begin()+Idx);
789 DeletedAdd = true;
790 }
791
792 // If we deleted at least one add, we added operands to the end of the list,
793 // and they are not necessarily sorted. Recurse to resort and resimplify
794 // any operands we just aquired.
795 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000796 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 }
798
799 // Skip over the add expression until we get to a multiply.
800 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
801 ++Idx;
802
803 // If we are adding something to a multiply expression, make sure the
804 // something is not already an operand of the multiply. If so, merge it into
805 // the multiply.
806 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
807 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
808 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
809 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
810 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
811 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
812 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
813 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
814 if (Mul->getNumOperands() != 2) {
815 // If the multiply has more than two operands, we must get the
816 // Y*Z term.
817 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
818 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000819 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 }
Dan Gohman89f85052007-10-22 18:31:58 +0000821 SCEVHandle One = getIntegerSCEV(1, Ty);
822 SCEVHandle AddOne = getAddExpr(InnerMul, One);
823 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 if (Ops.size() == 2) return OuterMul;
825 if (AddOp < Idx) {
826 Ops.erase(Ops.begin()+AddOp);
827 Ops.erase(Ops.begin()+Idx-1);
828 } else {
829 Ops.erase(Ops.begin()+Idx);
830 Ops.erase(Ops.begin()+AddOp-1);
831 }
832 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000833 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 }
835
836 // Check this multiply against other multiplies being added together.
837 for (unsigned OtherMulIdx = Idx+1;
838 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
839 ++OtherMulIdx) {
840 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
841 // If MulOp occurs in OtherMul, we can fold the two multiplies
842 // together.
843 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
844 OMulOp != e; ++OMulOp)
845 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
846 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
847 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
848 if (Mul->getNumOperands() != 2) {
849 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
850 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000851 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 }
853 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
854 if (OtherMul->getNumOperands() != 2) {
855 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
856 OtherMul->op_end());
857 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000858 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859 }
Dan Gohman89f85052007-10-22 18:31:58 +0000860 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
861 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 if (Ops.size() == 2) return OuterMul;
863 Ops.erase(Ops.begin()+Idx);
864 Ops.erase(Ops.begin()+OtherMulIdx-1);
865 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000866 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 }
868 }
869 }
870 }
871
872 // If there are any add recurrences in the operands list, see if any other
873 // added values are loop invariant. If so, we can fold them into the
874 // recurrence.
875 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
876 ++Idx;
877
878 // Scan over all recurrences, trying to fold loop invariants into them.
879 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
880 // Scan all of the other operands to this add and add them to the vector if
881 // they are loop invariant w.r.t. the recurrence.
882 std::vector<SCEVHandle> LIOps;
883 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
884 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
885 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
886 LIOps.push_back(Ops[i]);
887 Ops.erase(Ops.begin()+i);
888 --i; --e;
889 }
890
891 // If we found some loop invariants, fold them into the recurrence.
892 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000893 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 LIOps.push_back(AddRec->getStart());
895
896 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000897 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000898
Dan Gohman89f85052007-10-22 18:31:58 +0000899 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 // If all of the other operands were loop invariant, we are done.
901 if (Ops.size() == 1) return NewRec;
902
903 // Otherwise, add the folded AddRec by the non-liv parts.
904 for (unsigned i = 0;; ++i)
905 if (Ops[i] == AddRec) {
906 Ops[i] = NewRec;
907 break;
908 }
Dan Gohman89f85052007-10-22 18:31:58 +0000909 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910 }
911
912 // Okay, if there weren't any loop invariants to be folded, check to see if
913 // there are multiple AddRec's with the same loop induction variable being
914 // added together. If so, we can fold them.
915 for (unsigned OtherIdx = Idx+1;
916 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
917 if (OtherIdx != Idx) {
918 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
919 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
920 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
921 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
922 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
923 if (i >= NewOps.size()) {
924 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
925 OtherAddRec->op_end());
926 break;
927 }
Dan Gohman89f85052007-10-22 18:31:58 +0000928 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 }
Dan Gohman89f85052007-10-22 18:31:58 +0000930 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931
932 if (Ops.size() == 2) return NewAddRec;
933
934 Ops.erase(Ops.begin()+Idx);
935 Ops.erase(Ops.begin()+OtherIdx-1);
936 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000937 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 }
939 }
940
941 // Otherwise couldn't fold anything into this recurrence. Move onto the
942 // next one.
943 }
944
945 // Okay, it looks like we really DO need an add expr. Check to see if we
946 // already have one, otherwise create a new one.
947 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
948 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
949 SCEVOps)];
950 if (Result == 0) Result = new SCEVAddExpr(Ops);
951 return Result;
952}
953
954
Dan Gohman89f85052007-10-22 18:31:58 +0000955SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 assert(!Ops.empty() && "Cannot get empty mul!");
957
958 // Sort by complexity, this groups all similar expression types together.
959 GroupByComplexity(Ops);
960
961 // If there are any constants, fold them together.
962 unsigned Idx = 0;
963 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
964
965 // C1*(C2+V) -> C1*C2 + C1*V
966 if (Ops.size() == 2)
967 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
968 if (Add->getNumOperands() == 2 &&
969 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000970 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
971 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972
973
974 ++Idx;
975 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
976 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000977 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
978 RHSC->getValue()->getValue());
979 Ops[0] = getConstant(Fold);
980 Ops.erase(Ops.begin()+1); // Erase the folded element
981 if (Ops.size() == 1) return Ops[0];
982 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 }
984
985 // If we are left with a constant one being multiplied, strip it off.
986 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
987 Ops.erase(Ops.begin());
988 --Idx;
989 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
990 // If we have a multiply of zero, it will always be zero.
991 return Ops[0];
992 }
993 }
994
995 // Skip over the add expression until we get to a multiply.
996 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
997 ++Idx;
998
999 if (Ops.size() == 1)
1000 return Ops[0];
1001
1002 // If there are mul operands inline them all into this expression.
1003 if (Idx < Ops.size()) {
1004 bool DeletedMul = false;
1005 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1006 // If we have an mul, expand the mul operands onto the end of the operands
1007 // list.
1008 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1009 Ops.erase(Ops.begin()+Idx);
1010 DeletedMul = true;
1011 }
1012
1013 // If we deleted at least one mul, we added operands to the end of the list,
1014 // and they are not necessarily sorted. Recurse to resort and resimplify
1015 // any operands we just aquired.
1016 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001017 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 }
1019
1020 // If there are any add recurrences in the operands list, see if any other
1021 // added values are loop invariant. If so, we can fold them into the
1022 // recurrence.
1023 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1024 ++Idx;
1025
1026 // Scan over all recurrences, trying to fold loop invariants into them.
1027 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1028 // Scan all of the other operands to this mul and add them to the vector if
1029 // they are loop invariant w.r.t. the recurrence.
1030 std::vector<SCEVHandle> LIOps;
1031 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1032 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1033 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1034 LIOps.push_back(Ops[i]);
1035 Ops.erase(Ops.begin()+i);
1036 --i; --e;
1037 }
1038
1039 // If we found some loop invariants, fold them into the recurrence.
1040 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001041 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042 std::vector<SCEVHandle> NewOps;
1043 NewOps.reserve(AddRec->getNumOperands());
1044 if (LIOps.size() == 1) {
1045 SCEV *Scale = LIOps[0];
1046 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001047 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 } else {
1049 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1050 std::vector<SCEVHandle> MulOps(LIOps);
1051 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001052 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 }
1054 }
1055
Dan Gohman89f85052007-10-22 18:31:58 +00001056 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057
1058 // If all of the other operands were loop invariant, we are done.
1059 if (Ops.size() == 1) return NewRec;
1060
1061 // Otherwise, multiply the folded AddRec by the non-liv parts.
1062 for (unsigned i = 0;; ++i)
1063 if (Ops[i] == AddRec) {
1064 Ops[i] = NewRec;
1065 break;
1066 }
Dan Gohman89f85052007-10-22 18:31:58 +00001067 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068 }
1069
1070 // Okay, if there weren't any loop invariants to be folded, check to see if
1071 // there are multiple AddRec's with the same loop induction variable being
1072 // multiplied together. If so, we can fold them.
1073 for (unsigned OtherIdx = Idx+1;
1074 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1075 if (OtherIdx != Idx) {
1076 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1077 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1078 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1079 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001080 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001082 SCEVHandle B = F->getStepRecurrence(*this);
1083 SCEVHandle D = G->getStepRecurrence(*this);
1084 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1085 getMulExpr(G, B),
1086 getMulExpr(B, D));
1087 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1088 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 if (Ops.size() == 2) return NewAddRec;
1090
1091 Ops.erase(Ops.begin()+Idx);
1092 Ops.erase(Ops.begin()+OtherIdx-1);
1093 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001094 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 }
1096 }
1097
1098 // Otherwise couldn't fold anything into this recurrence. Move onto the
1099 // next one.
1100 }
1101
1102 // Okay, it looks like we really DO need an mul expr. Check to see if we
1103 // already have one, otherwise create a new one.
1104 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1105 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1106 SCEVOps)];
1107 if (Result == 0)
1108 Result = new SCEVMulExpr(Ops);
1109 return Result;
1110}
1111
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001112SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1114 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001115 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116
1117 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1118 Constant *LHSCV = LHSC->getValue();
1119 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001120 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 }
1122 }
1123
Nick Lewycky35b56022009-01-13 09:18:58 +00001124 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1125
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001126 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1127 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 return Result;
1129}
1130
1131
1132/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1133/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001134SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 const SCEVHandle &Step, const Loop *L) {
1136 std::vector<SCEVHandle> Operands;
1137 Operands.push_back(Start);
1138 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1139 if (StepChrec->getLoop() == L) {
1140 Operands.insert(Operands.end(), StepChrec->op_begin(),
1141 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001142 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 }
1144
1145 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001146 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147}
1148
1149/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1150/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001151SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 const Loop *L) {
1153 if (Operands.size() == 1) return Operands[0];
1154
Dan Gohman7b560c42008-06-18 16:23:07 +00001155 if (Operands.back()->isZero()) {
1156 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001157 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001158 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159
Dan Gohman42936882008-08-08 18:33:12 +00001160 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1161 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1162 const Loop* NestedLoop = NestedAR->getLoop();
1163 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1164 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1165 NestedAR->op_end());
1166 SCEVHandle NestedARHandle(NestedAR);
1167 Operands[0] = NestedAR->getStart();
1168 NestedOperands[0] = getAddRecExpr(Operands, L);
1169 return getAddRecExpr(NestedOperands, NestedLoop);
1170 }
1171 }
1172
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173 SCEVAddRecExpr *&Result =
1174 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1175 Operands.end()))];
1176 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1177 return Result;
1178}
1179
Nick Lewycky711640a2007-11-25 22:41:31 +00001180SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1181 const SCEVHandle &RHS) {
1182 std::vector<SCEVHandle> Ops;
1183 Ops.push_back(LHS);
1184 Ops.push_back(RHS);
1185 return getSMaxExpr(Ops);
1186}
1187
1188SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1189 assert(!Ops.empty() && "Cannot get empty smax!");
1190 if (Ops.size() == 1) return Ops[0];
1191
1192 // Sort by complexity, this groups all similar expression types together.
1193 GroupByComplexity(Ops);
1194
1195 // If there are any constants, fold them together.
1196 unsigned Idx = 0;
1197 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1198 ++Idx;
1199 assert(Idx < Ops.size());
1200 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1201 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001202 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001203 APIntOps::smax(LHSC->getValue()->getValue(),
1204 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001205 Ops[0] = getConstant(Fold);
1206 Ops.erase(Ops.begin()+1); // Erase the folded element
1207 if (Ops.size() == 1) return Ops[0];
1208 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001209 }
1210
1211 // If we are left with a constant -inf, strip it off.
1212 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1213 Ops.erase(Ops.begin());
1214 --Idx;
1215 }
1216 }
1217
1218 if (Ops.size() == 1) return Ops[0];
1219
1220 // Find the first SMax
1221 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1222 ++Idx;
1223
1224 // Check to see if one of the operands is an SMax. If so, expand its operands
1225 // onto our operand list, and recurse to simplify.
1226 if (Idx < Ops.size()) {
1227 bool DeletedSMax = false;
1228 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1229 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1230 Ops.erase(Ops.begin()+Idx);
1231 DeletedSMax = true;
1232 }
1233
1234 if (DeletedSMax)
1235 return getSMaxExpr(Ops);
1236 }
1237
1238 // Okay, check to see if the same value occurs in the operand list twice. If
1239 // so, delete one. Since we sorted the list, these values are required to
1240 // be adjacent.
1241 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1242 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1243 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1244 --i; --e;
1245 }
1246
1247 if (Ops.size() == 1) return Ops[0];
1248
1249 assert(!Ops.empty() && "Reduced smax down to nothing!");
1250
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001251 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001252 // already have one, otherwise create a new one.
1253 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1254 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1255 SCEVOps)];
1256 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1257 return Result;
1258}
1259
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001260SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1261 const SCEVHandle &RHS) {
1262 std::vector<SCEVHandle> Ops;
1263 Ops.push_back(LHS);
1264 Ops.push_back(RHS);
1265 return getUMaxExpr(Ops);
1266}
1267
1268SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1269 assert(!Ops.empty() && "Cannot get empty umax!");
1270 if (Ops.size() == 1) return Ops[0];
1271
1272 // Sort by complexity, this groups all similar expression types together.
1273 GroupByComplexity(Ops);
1274
1275 // If there are any constants, fold them together.
1276 unsigned Idx = 0;
1277 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1278 ++Idx;
1279 assert(Idx < Ops.size());
1280 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1281 // We found two constants, fold them together!
1282 ConstantInt *Fold = ConstantInt::get(
1283 APIntOps::umax(LHSC->getValue()->getValue(),
1284 RHSC->getValue()->getValue()));
1285 Ops[0] = getConstant(Fold);
1286 Ops.erase(Ops.begin()+1); // Erase the folded element
1287 if (Ops.size() == 1) return Ops[0];
1288 LHSC = cast<SCEVConstant>(Ops[0]);
1289 }
1290
1291 // If we are left with a constant zero, strip it off.
1292 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1293 Ops.erase(Ops.begin());
1294 --Idx;
1295 }
1296 }
1297
1298 if (Ops.size() == 1) return Ops[0];
1299
1300 // Find the first UMax
1301 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1302 ++Idx;
1303
1304 // Check to see if one of the operands is a UMax. If so, expand its operands
1305 // onto our operand list, and recurse to simplify.
1306 if (Idx < Ops.size()) {
1307 bool DeletedUMax = false;
1308 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1309 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1310 Ops.erase(Ops.begin()+Idx);
1311 DeletedUMax = true;
1312 }
1313
1314 if (DeletedUMax)
1315 return getUMaxExpr(Ops);
1316 }
1317
1318 // Okay, check to see if the same value occurs in the operand list twice. If
1319 // so, delete one. Since we sorted the list, these values are required to
1320 // be adjacent.
1321 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1322 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1323 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1324 --i; --e;
1325 }
1326
1327 if (Ops.size() == 1) return Ops[0];
1328
1329 assert(!Ops.empty() && "Reduced umax down to nothing!");
1330
1331 // Okay, it looks like we really DO need a umax expr. Check to see if we
1332 // already have one, otherwise create a new one.
1333 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1334 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1335 SCEVOps)];
1336 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1337 return Result;
1338}
1339
Dan Gohman89f85052007-10-22 18:31:58 +00001340SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001342 return getConstant(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1344 if (Result == 0) Result = new SCEVUnknown(V);
1345 return Result;
1346}
1347
1348
1349//===----------------------------------------------------------------------===//
1350// ScalarEvolutionsImpl Definition and Implementation
1351//===----------------------------------------------------------------------===//
1352//
1353/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1354/// evolution code.
1355///
1356namespace {
1357 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001358 /// SE - A reference to the public ScalarEvolution object.
1359 ScalarEvolution &SE;
1360
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 /// F - The function we are analyzing.
1362 ///
1363 Function &F;
1364
1365 /// LI - The loop information for the function we are currently analyzing.
1366 ///
1367 LoopInfo &LI;
1368
1369 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1370 /// things.
1371 SCEVHandle UnknownValue;
1372
1373 /// Scalars - This is a cache of the scalars we have analyzed so far.
1374 ///
1375 std::map<Value*, SCEVHandle> Scalars;
1376
1377 /// IterationCounts - Cache the iteration count of the loops for this
1378 /// function as they are computed.
1379 std::map<const Loop*, SCEVHandle> IterationCounts;
1380
1381 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1382 /// the PHI instructions that we attempt to compute constant evolutions for.
1383 /// This allows us to avoid potentially expensive recomputation of these
1384 /// properties. An instruction maps to null if we are unable to compute its
1385 /// exit value.
1386 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1387
1388 public:
Dan Gohman89f85052007-10-22 18:31:58 +00001389 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1390 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391
1392 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1393 /// expression and create a new one.
1394 SCEVHandle getSCEV(Value *V);
1395
1396 /// hasSCEV - Return true if the SCEV for this value has already been
1397 /// computed.
1398 bool hasSCEV(Value *V) const {
1399 return Scalars.count(V);
1400 }
1401
1402 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1403 /// the specified value.
1404 void setSCEV(Value *V, const SCEVHandle &H) {
1405 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1406 assert(isNew && "This entry already existed!");
Devang Patelfc736502008-11-11 19:17:41 +00001407 isNew = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001408 }
1409
1410
1411 /// getSCEVAtScope - Compute the value of the specified expression within
1412 /// the indicated loop (which may be null to indicate in no loop). If the
1413 /// expression cannot be evaluated, return UnknownValue itself.
1414 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1415
1416
1417 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1418 /// an analyzable loop-invariant iteration count.
1419 bool hasLoopInvariantIterationCount(const Loop *L);
1420
1421 /// getIterationCount - If the specified loop has a predictable iteration
1422 /// count, return it. Note that it is not valid to call this method on a
1423 /// loop without a loop-invariant iteration count.
1424 SCEVHandle getIterationCount(const Loop *L);
1425
1426 /// deleteValueFromRecords - This method should be called by the
1427 /// client before it removes a value from the program, to make sure
1428 /// that no dangling references are left around.
1429 void deleteValueFromRecords(Value *V);
1430
1431 private:
1432 /// createSCEV - We know that there is no SCEV for the specified value.
1433 /// Analyze the expression.
1434 SCEVHandle createSCEV(Value *V);
1435
1436 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1437 /// SCEVs.
1438 SCEVHandle createNodeForPHI(PHINode *PN);
1439
1440 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1441 /// for the specified instruction and replaces any references to the
1442 /// symbolic value SymName with the specified value. This is used during
1443 /// PHI resolution.
1444 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1445 const SCEVHandle &SymName,
1446 const SCEVHandle &NewVal);
1447
1448 /// ComputeIterationCount - Compute the number of times the specified loop
1449 /// will iterate.
1450 SCEVHandle ComputeIterationCount(const Loop *L);
1451
1452 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001453 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1455 Constant *RHS,
1456 const Loop *L,
1457 ICmpInst::Predicate p);
1458
1459 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1460 /// constant number of times (the condition evolves only from constants),
1461 /// try to evaluate a few iterations of the loop until we get the exit
1462 /// condition gets a value of ExitWhen (true or false). If we cannot
1463 /// evaluate the trip count of the loop, return UnknownValue.
1464 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1465 bool ExitWhen);
1466
1467 /// HowFarToZero - Return the number of times a backedge comparing the
1468 /// specified value to zero will execute. If not computable, return
1469 /// UnknownValue.
1470 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1471
1472 /// HowFarToNonZero - Return the number of times a backedge checking the
1473 /// specified value for nonzero will execute. If not computable, return
1474 /// UnknownValue.
1475 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1476
1477 /// HowManyLessThans - Return the number of times a backedge containing the
1478 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001479 /// UnknownValue. isSigned specifies whether the less-than is signed.
1480 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewycky35b56022009-01-13 09:18:58 +00001481 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001482
Dan Gohman1cddf972008-09-15 22:18:04 +00001483 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1484 /// (which may not be an immediate predecessor) which has exactly one
1485 /// successor from which BB is reachable, or null if no such block is
1486 /// found.
1487 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1488
Nick Lewycky1b020bf2008-07-12 07:41:32 +00001489 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1490 /// a conditional between LHS and RHS.
Nick Lewycky35b56022009-01-13 09:18:58 +00001491 bool executesAtLeastOnce(const Loop *L, bool isSigned, SCEV *LHS, SCEV *RHS);
Nick Lewycky1b020bf2008-07-12 07:41:32 +00001492
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1494 /// in the header of its containing loop, we know the loop executes a
1495 /// constant number of times, and the PHI node is just a recurrence
1496 /// involving constants, fold it.
1497 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1498 const Loop *L);
1499 };
1500}
1501
1502//===----------------------------------------------------------------------===//
1503// Basic SCEV Analysis and PHI Idiom Recognition Code
1504//
1505
1506/// deleteValueFromRecords - This method should be called by the
1507/// client before it removes an instruction from the program, to make sure
1508/// that no dangling references are left around.
1509void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1510 SmallVector<Value *, 16> Worklist;
1511
1512 if (Scalars.erase(V)) {
1513 if (PHINode *PN = dyn_cast<PHINode>(V))
1514 ConstantEvolutionLoopExitValue.erase(PN);
1515 Worklist.push_back(V);
1516 }
1517
1518 while (!Worklist.empty()) {
1519 Value *VV = Worklist.back();
1520 Worklist.pop_back();
1521
1522 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1523 UI != UE; ++UI) {
1524 Instruction *Inst = cast<Instruction>(*UI);
1525 if (Scalars.erase(Inst)) {
1526 if (PHINode *PN = dyn_cast<PHINode>(VV))
1527 ConstantEvolutionLoopExitValue.erase(PN);
1528 Worklist.push_back(Inst);
1529 }
1530 }
1531 }
1532}
1533
1534
1535/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1536/// expression and create a new one.
1537SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1538 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1539
1540 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1541 if (I != Scalars.end()) return I->second;
1542 SCEVHandle S = createSCEV(V);
1543 Scalars.insert(std::make_pair(V, S));
1544 return S;
1545}
1546
1547/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1548/// the specified instruction and replaces any references to the symbolic value
1549/// SymName with the specified value. This is used during PHI resolution.
1550void ScalarEvolutionsImpl::
1551ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1552 const SCEVHandle &NewVal) {
1553 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1554 if (SI == Scalars.end()) return;
1555
1556 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001557 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558 if (NV == SI->second) return; // No change.
1559
1560 SI->second = NV; // Update the scalars map!
1561
1562 // Any instruction values that use this instruction might also need to be
1563 // updated!
1564 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1565 UI != E; ++UI)
1566 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1567}
1568
1569/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1570/// a loop header, making it a potential recurrence, or it doesn't.
1571///
1572SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1573 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1574 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1575 if (L->getHeader() == PN->getParent()) {
1576 // If it lives in the loop header, it has two incoming values, one
1577 // from outside the loop, and one from inside.
1578 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1579 unsigned BackEdge = IncomingEdge^1;
1580
1581 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001582 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001583 assert(Scalars.find(PN) == Scalars.end() &&
1584 "PHI node already processed?");
1585 Scalars.insert(std::make_pair(PN, SymbolicName));
1586
1587 // Using this symbolic name for the PHI, analyze the value coming around
1588 // the back-edge.
1589 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1590
1591 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1592 // has a special value for the first iteration of the loop.
1593
1594 // If the value coming around the backedge is an add with the symbolic
1595 // value we just inserted, then we found a simple induction variable!
1596 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1597 // If there is a single occurrence of the symbolic value, replace it
1598 // with a recurrence.
1599 unsigned FoundIndex = Add->getNumOperands();
1600 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1601 if (Add->getOperand(i) == SymbolicName)
1602 if (FoundIndex == e) {
1603 FoundIndex = i;
1604 break;
1605 }
1606
1607 if (FoundIndex != Add->getNumOperands()) {
1608 // Create an add with everything but the specified operand.
1609 std::vector<SCEVHandle> Ops;
1610 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1611 if (i != FoundIndex)
1612 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001613 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614
1615 // This is not a valid addrec if the step amount is varying each
1616 // loop iteration, but is not itself an addrec in this loop.
1617 if (Accum->isLoopInvariant(L) ||
1618 (isa<SCEVAddRecExpr>(Accum) &&
1619 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1620 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001621 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001622
1623 // Okay, for the entire analysis of this edge we assumed the PHI
1624 // to be symbolic. We now need to go back and update all of the
1625 // entries for the scalars that use the PHI (except for the PHI
1626 // itself) to use the new analyzed value instead of the "symbolic"
1627 // value.
1628 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1629 return PHISCEV;
1630 }
1631 }
1632 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1633 // Otherwise, this could be a loop like this:
1634 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1635 // In this case, j = {1,+,1} and BEValue is j.
1636 // Because the other in-value of i (0) fits the evolution of BEValue
1637 // i really is an addrec evolution.
1638 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1639 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1640
1641 // If StartVal = j.start - j.stride, we can use StartVal as the
1642 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001643 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1644 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001646 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647
1648 // Okay, for the entire analysis of this edge we assumed the PHI
1649 // to be symbolic. We now need to go back and update all of the
1650 // entries for the scalars that use the PHI (except for the PHI
1651 // itself) to use the new analyzed value instead of the "symbolic"
1652 // value.
1653 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1654 return PHISCEV;
1655 }
1656 }
1657 }
1658
1659 return SymbolicName;
1660 }
1661
1662 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001663 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001664}
1665
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001666/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1667/// guaranteed to end in (at every loop iteration). It is, at the same time,
1668/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1669/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1670static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1671 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001672 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001674 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001675 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1676
1677 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1678 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1679 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1680 }
1681
1682 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1683 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1684 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1685 }
1686
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001688 // The result is the min of all operands results.
1689 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1690 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1691 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1692 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001693 }
1694
1695 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001696 // The result is the sum of all operands results.
1697 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1698 uint32_t BitWidth = M->getBitWidth();
1699 for (unsigned i = 1, e = M->getNumOperands();
1700 SumOpRes != BitWidth && i != e; ++i)
1701 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1702 BitWidth);
1703 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001704 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001705
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001706 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001707 // The result is the min of all operands results.
1708 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1709 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1710 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1711 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001713
Nick Lewycky711640a2007-11-25 22:41:31 +00001714 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1715 // The result is the min of all operands results.
1716 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1717 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1718 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1719 return MinOpRes;
1720 }
1721
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001722 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1723 // The result is the min of all operands results.
1724 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1725 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1726 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1727 return MinOpRes;
1728 }
1729
Nick Lewycky35b56022009-01-13 09:18:58 +00001730 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001731 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001732}
1733
1734/// createSCEV - We know that there is no SCEV for the specified value.
1735/// Analyze the expression.
1736///
1737SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner3fff4642007-11-23 08:46:22 +00001738 if (!isa<IntegerType>(V->getType()))
1739 return SE.getUnknown(V);
1740
Dan Gohman3996f472008-06-22 19:56:46 +00001741 unsigned Opcode = Instruction::UserOp1;
1742 if (Instruction *I = dyn_cast<Instruction>(V))
1743 Opcode = I->getOpcode();
1744 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1745 Opcode = CE->getOpcode();
1746 else
1747 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001748
Dan Gohman3996f472008-06-22 19:56:46 +00001749 User *U = cast<User>(V);
1750 switch (Opcode) {
1751 case Instruction::Add:
1752 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1753 getSCEV(U->getOperand(1)));
1754 case Instruction::Mul:
1755 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1756 getSCEV(U->getOperand(1)));
1757 case Instruction::UDiv:
1758 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1759 getSCEV(U->getOperand(1)));
1760 case Instruction::Sub:
1761 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1762 getSCEV(U->getOperand(1)));
1763 case Instruction::Or:
1764 // If the RHS of the Or is a constant, we may have something like:
1765 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1766 // optimizations will transparently handle this case.
1767 //
1768 // In order for this transformation to be safe, the LHS must be of the
1769 // form X*(2^n) and the Or constant must be less than 2^n.
1770 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1771 SCEVHandle LHS = getSCEV(U->getOperand(0));
1772 const APInt &CIVal = CI->getValue();
1773 if (GetMinTrailingZeros(LHS) >=
1774 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1775 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776 }
Dan Gohman3996f472008-06-22 19:56:46 +00001777 break;
1778 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001779 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001780 // If the RHS of the xor is a signbit, then this is just an add.
1781 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001782 if (CI->getValue().isSignBit())
1783 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1784 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001785
1786 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001787 else if (CI->isAllOnesValue())
1788 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1789 }
1790 break;
1791
1792 case Instruction::Shl:
1793 // Turn shift left of a constant amount into a multiply.
1794 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1795 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1796 Constant *X = ConstantInt::get(
1797 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1798 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1799 }
1800 break;
1801
Nick Lewycky7fd27892008-07-07 06:15:49 +00001802 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001803 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001804 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1805 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1806 Constant *X = ConstantInt::get(
1807 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1808 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1809 }
1810 break;
1811
Dan Gohman3996f472008-06-22 19:56:46 +00001812 case Instruction::Trunc:
1813 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1814
1815 case Instruction::ZExt:
1816 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1817
1818 case Instruction::SExt:
1819 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1820
1821 case Instruction::BitCast:
1822 // BitCasts are no-op casts so we just eliminate the cast.
1823 if (U->getType()->isInteger() &&
1824 U->getOperand(0)->getType()->isInteger())
1825 return getSCEV(U->getOperand(0));
1826 break;
1827
1828 case Instruction::PHI:
1829 return createNodeForPHI(cast<PHINode>(U));
1830
1831 case Instruction::Select:
1832 // This could be a smax or umax that was lowered earlier.
1833 // Try to recover it.
1834 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1835 Value *LHS = ICI->getOperand(0);
1836 Value *RHS = ICI->getOperand(1);
1837 switch (ICI->getPredicate()) {
1838 case ICmpInst::ICMP_SLT:
1839 case ICmpInst::ICMP_SLE:
1840 std::swap(LHS, RHS);
1841 // fall through
1842 case ICmpInst::ICMP_SGT:
1843 case ICmpInst::ICMP_SGE:
1844 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1845 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1846 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00001847 // ~smax(~x, ~y) == smin(x, y).
1848 return SE.getNotSCEV(SE.getSMaxExpr(
1849 SE.getNotSCEV(getSCEV(LHS)),
1850 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001851 break;
1852 case ICmpInst::ICMP_ULT:
1853 case ICmpInst::ICMP_ULE:
1854 std::swap(LHS, RHS);
1855 // fall through
1856 case ICmpInst::ICMP_UGT:
1857 case ICmpInst::ICMP_UGE:
1858 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1859 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1860 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1861 // ~umax(~x, ~y) == umin(x, y)
1862 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1863 SE.getNotSCEV(getSCEV(RHS))));
1864 break;
1865 default:
1866 break;
1867 }
1868 }
1869
1870 default: // We cannot analyze this expression.
1871 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 }
1873
Dan Gohman89f85052007-10-22 18:31:58 +00001874 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875}
1876
1877
1878
1879//===----------------------------------------------------------------------===//
1880// Iteration Count Computation Code
1881//
1882
1883/// getIterationCount - If the specified loop has a predictable iteration
1884/// count, return it. Note that it is not valid to call this method on a
1885/// loop without a loop-invariant iteration count.
1886SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1887 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1888 if (I == IterationCounts.end()) {
1889 SCEVHandle ItCount = ComputeIterationCount(L);
1890 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1891 if (ItCount != UnknownValue) {
1892 assert(ItCount->isLoopInvariant(L) &&
1893 "Computed trip count isn't loop invariant for loop!");
1894 ++NumTripCountsComputed;
1895 } else if (isa<PHINode>(L->getHeader()->begin())) {
1896 // Only count loops that have phi nodes as not being computable.
1897 ++NumTripCountsNotComputed;
1898 }
1899 }
1900 return I->second;
1901}
1902
1903/// ComputeIterationCount - Compute the number of times the specified loop
1904/// will iterate.
1905SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1906 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00001907 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001908 L->getExitBlocks(ExitBlocks);
1909 if (ExitBlocks.size() != 1) return UnknownValue;
1910
1911 // Okay, there is one exit block. Try to find the condition that causes the
1912 // loop to be exited.
1913 BasicBlock *ExitBlock = ExitBlocks[0];
1914
1915 BasicBlock *ExitingBlock = 0;
1916 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1917 PI != E; ++PI)
1918 if (L->contains(*PI)) {
1919 if (ExitingBlock == 0)
1920 ExitingBlock = *PI;
1921 else
1922 return UnknownValue; // More than one block exiting!
1923 }
1924 assert(ExitingBlock && "No exits from loop, something is broken!");
1925
1926 // Okay, we've computed the exiting block. See what condition causes us to
1927 // exit.
1928 //
1929 // FIXME: we should be able to handle switch instructions (with a single exit)
1930 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1931 if (ExitBr == 0) return UnknownValue;
1932 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1933
1934 // At this point, we know we have a conditional branch that determines whether
1935 // the loop is exited. However, we don't know if the branch is executed each
1936 // time through the loop. If not, then the execution count of the branch will
1937 // not be equal to the trip count of the loop.
1938 //
1939 // Currently we check for this by checking to see if the Exit branch goes to
1940 // the loop header. If so, we know it will always execute the same number of
1941 // times as the loop. We also handle the case where the exit block *is* the
1942 // loop header. This is common for un-rotated loops. More extensive analysis
1943 // could be done to handle more cases here.
1944 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1945 ExitBr->getSuccessor(1) != L->getHeader() &&
1946 ExitBr->getParent() != L->getHeader())
1947 return UnknownValue;
1948
1949 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1950
Nick Lewyckyb3d24332008-02-21 08:34:02 +00001951 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001952 // Note that ICmpInst deals with pointer comparisons too so we must check
1953 // the type of the operand.
1954 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1955 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1956 ExitBr->getSuccessor(0) == ExitBlock);
1957
1958 // If the condition was exit on true, convert the condition to exit on false
1959 ICmpInst::Predicate Cond;
1960 if (ExitBr->getSuccessor(1) == ExitBlock)
1961 Cond = ExitCond->getPredicate();
1962 else
1963 Cond = ExitCond->getInversePredicate();
1964
1965 // Handle common loops like: for (X = "string"; *X; ++X)
1966 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1967 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1968 SCEVHandle ItCnt =
1969 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1970 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1971 }
1972
1973 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1974 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1975
1976 // Try to evaluate any dependencies out of the loop.
1977 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1978 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1979 Tmp = getSCEVAtScope(RHS, L);
1980 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1981
1982 // At this point, we would like to compute how many iterations of the
1983 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00001984 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
1985 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986 std::swap(LHS, RHS);
1987 Cond = ICmpInst::getSwappedPredicate(Cond);
1988 }
1989
1990 // FIXME: think about handling pointer comparisons! i.e.:
1991 // while (P != P+100) ++P;
1992
1993 // If we have a comparison of a chrec against a constant, try to use value
1994 // ranges to answer this query.
1995 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1996 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1997 if (AddRec->getLoop() == L) {
1998 // Form the comparison range using the constant of the correct type so
1999 // that the ConstantRange class knows to do a signed or unsigned
2000 // comparison.
2001 ConstantInt *CompVal = RHSC->getValue();
2002 const Type *RealTy = ExitCond->getOperand(0)->getType();
2003 CompVal = dyn_cast<ConstantInt>(
2004 ConstantExpr::getBitCast(CompVal, RealTy));
2005 if (CompVal) {
2006 // Form the constant range.
2007 ConstantRange CompRange(
2008 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2009
Dan Gohman89f85052007-10-22 18:31:58 +00002010 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002011 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2012 }
2013 }
2014
2015 switch (Cond) {
2016 case ICmpInst::ICMP_NE: { // while (X != Y)
2017 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00002018 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002019 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2020 break;
2021 }
2022 case ICmpInst::ICMP_EQ: {
2023 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00002024 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2026 break;
2027 }
2028 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002029 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2031 break;
2032 }
2033 case ICmpInst::ICMP_SGT: {
Eli Friedman0dcd4ed2008-07-30 00:04:08 +00002034 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002035 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002036 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2037 break;
2038 }
2039 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002040 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002041 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2042 break;
2043 }
2044 case ICmpInst::ICMP_UGT: {
Dale Johannesend721b952008-04-20 16:58:57 +00002045 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002046 SE.getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002047 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2048 break;
2049 }
2050 default:
2051#if 0
2052 cerr << "ComputeIterationCount ";
2053 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2054 cerr << "[unsigned] ";
2055 cerr << *LHS << " "
2056 << Instruction::getOpcodeName(Instruction::ICmp)
2057 << " " << *RHS << "\n";
2058#endif
2059 break;
2060 }
2061 return ComputeIterationCountExhaustively(L, ExitCond,
2062 ExitBr->getSuccessor(0) == ExitBlock);
2063}
2064
2065static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002066EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2067 ScalarEvolution &SE) {
2068 SCEVHandle InVal = SE.getConstant(C);
2069 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070 assert(isa<SCEVConstant>(Val) &&
2071 "Evaluation of SCEV at constant didn't fold correctly?");
2072 return cast<SCEVConstant>(Val)->getValue();
2073}
2074
2075/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2076/// and a GEP expression (missing the pointer index) indexing into it, return
2077/// the addressed element of the initializer or null if the index expression is
2078/// invalid.
2079static Constant *
2080GetAddressedElementFromGlobal(GlobalVariable *GV,
2081 const std::vector<ConstantInt*> &Indices) {
2082 Constant *Init = GV->getInitializer();
2083 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2084 uint64_t Idx = Indices[i]->getZExtValue();
2085 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2086 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2087 Init = cast<Constant>(CS->getOperand(Idx));
2088 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2089 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2090 Init = cast<Constant>(CA->getOperand(Idx));
2091 } else if (isa<ConstantAggregateZero>(Init)) {
2092 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2093 assert(Idx < STy->getNumElements() && "Bad struct index!");
2094 Init = Constant::getNullValue(STy->getElementType(Idx));
2095 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2096 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2097 Init = Constant::getNullValue(ATy->getElementType());
2098 } else {
2099 assert(0 && "Unknown constant aggregate type!");
2100 }
2101 return 0;
2102 } else {
2103 return 0; // Unknown initializer type
2104 }
2105 }
2106 return Init;
2107}
2108
2109/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky347e4222008-05-06 04:03:18 +00002110/// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002111SCEVHandle ScalarEvolutionsImpl::
2112ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2113 const Loop *L,
2114 ICmpInst::Predicate predicate) {
2115 if (LI->isVolatile()) return UnknownValue;
2116
2117 // Check to see if the loaded pointer is a getelementptr of a global.
2118 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2119 if (!GEP) return UnknownValue;
2120
2121 // Make sure that it is really a constant global we are gepping, with an
2122 // initializer, and make sure the first IDX is really 0.
2123 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2124 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2125 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2126 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2127 return UnknownValue;
2128
2129 // Okay, we allow one non-constant index into the GEP instruction.
2130 Value *VarIdx = 0;
2131 std::vector<ConstantInt*> Indexes;
2132 unsigned VarIdxNum = 0;
2133 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2134 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2135 Indexes.push_back(CI);
2136 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2137 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2138 VarIdx = GEP->getOperand(i);
2139 VarIdxNum = i-2;
2140 Indexes.push_back(0);
2141 }
2142
2143 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2144 // Check to see if X is a loop variant variable value now.
2145 SCEVHandle Idx = getSCEV(VarIdx);
2146 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2147 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2148
2149 // We can only recognize very limited forms of loop index expressions, in
2150 // particular, only affine AddRec's like {C1,+,C2}.
2151 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2152 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2153 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2154 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2155 return UnknownValue;
2156
2157 unsigned MaxSteps = MaxBruteForceIterations;
2158 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2159 ConstantInt *ItCst =
2160 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00002161 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002162
2163 // Form the GEP offset.
2164 Indexes[VarIdxNum] = Val;
2165
2166 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2167 if (Result == 0) break; // Cannot compute!
2168
2169 // Evaluate the condition for this iteration.
2170 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2171 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2172 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2173#if 0
2174 cerr << "\n***\n*** Computed loop count " << *ItCst
2175 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2176 << "***\n";
2177#endif
2178 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00002179 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002180 }
2181 }
2182 return UnknownValue;
2183}
2184
2185
2186/// CanConstantFold - Return true if we can constant fold an instruction of the
2187/// specified type, assuming that all operands were constants.
2188static bool CanConstantFold(const Instruction *I) {
2189 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2190 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2191 return true;
2192
2193 if (const CallInst *CI = dyn_cast<CallInst>(I))
2194 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002195 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002196 return false;
2197}
2198
2199/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2200/// in the loop that V is derived from. We allow arbitrary operations along the
2201/// way, but the operands of an operation must either be constants or a value
2202/// derived from a constant PHI. If this expression does not fit with these
2203/// constraints, return null.
2204static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2205 // If this is not an instruction, or if this is an instruction outside of the
2206 // loop, it can't be derived from a loop PHI.
2207 Instruction *I = dyn_cast<Instruction>(V);
2208 if (I == 0 || !L->contains(I->getParent())) return 0;
2209
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002210 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002211 if (L->getHeader() == I->getParent())
2212 return PN;
2213 else
2214 // We don't currently keep track of the control flow needed to evaluate
2215 // PHIs, so we cannot handle PHIs inside of loops.
2216 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002217 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002218
2219 // If we won't be able to constant fold this expression even if the operands
2220 // are constants, return early.
2221 if (!CanConstantFold(I)) return 0;
2222
2223 // Otherwise, we can evaluate this instruction if all of its operands are
2224 // constant or derived from a PHI node themselves.
2225 PHINode *PHI = 0;
2226 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2227 if (!(isa<Constant>(I->getOperand(Op)) ||
2228 isa<GlobalValue>(I->getOperand(Op)))) {
2229 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2230 if (P == 0) return 0; // Not evolving from PHI
2231 if (PHI == 0)
2232 PHI = P;
2233 else if (PHI != P)
2234 return 0; // Evolving from multiple different PHIs.
2235 }
2236
2237 // This is a expression evolving from a constant PHI!
2238 return PHI;
2239}
2240
2241/// EvaluateExpression - Given an expression that passes the
2242/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2243/// in the loop has the value PHIVal. If we can't fold this expression for some
2244/// reason, return null.
2245static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2246 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002247 if (Constant *C = dyn_cast<Constant>(V)) return C;
2248 Instruction *I = cast<Instruction>(V);
2249
2250 std::vector<Constant*> Operands;
2251 Operands.resize(I->getNumOperands());
2252
2253 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2254 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2255 if (Operands[i] == 0) return 0;
2256 }
2257
Chris Lattnerd6e56912007-12-10 22:53:04 +00002258 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2259 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2260 &Operands[0], Operands.size());
2261 else
2262 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2263 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264}
2265
2266/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2267/// in the header of its containing loop, we know the loop executes a
2268/// constant number of times, and the PHI node is just a recurrence
2269/// involving constants, fold it.
2270Constant *ScalarEvolutionsImpl::
2271getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2272 std::map<PHINode*, Constant*>::iterator I =
2273 ConstantEvolutionLoopExitValue.find(PN);
2274 if (I != ConstantEvolutionLoopExitValue.end())
2275 return I->second;
2276
2277 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2278 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2279
2280 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2281
2282 // Since the loop is canonicalized, the PHI node must have two entries. One
2283 // entry must be a constant (coming in from outside of the loop), and the
2284 // second must be derived from the same PHI.
2285 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2286 Constant *StartCST =
2287 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2288 if (StartCST == 0)
2289 return RetVal = 0; // Must be a constant.
2290
2291 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2292 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2293 if (PN2 != PN)
2294 return RetVal = 0; // Not derived from same PHI.
2295
2296 // Execute the loop symbolically to determine the exit value.
2297 if (Its.getActiveBits() >= 32)
2298 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2299
2300 unsigned NumIterations = Its.getZExtValue(); // must be in range
2301 unsigned IterationNum = 0;
2302 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2303 if (IterationNum == NumIterations)
2304 return RetVal = PHIVal; // Got exit value!
2305
2306 // Compute the value of the PHI node for the next iteration.
2307 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2308 if (NextPHI == PHIVal)
2309 return RetVal = NextPHI; // Stopped evolving!
2310 if (NextPHI == 0)
2311 return 0; // Couldn't evaluate!
2312 PHIVal = NextPHI;
2313 }
2314}
2315
2316/// ComputeIterationCountExhaustively - If the trip is known to execute a
2317/// constant number of times (the condition evolves only from constants),
2318/// try to evaluate a few iterations of the loop until we get the exit
2319/// condition gets a value of ExitWhen (true or false). If we cannot
2320/// evaluate the trip count of the loop, return UnknownValue.
2321SCEVHandle ScalarEvolutionsImpl::
2322ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2323 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2324 if (PN == 0) return UnknownValue;
2325
2326 // Since the loop is canonicalized, the PHI node must have two entries. One
2327 // entry must be a constant (coming in from outside of the loop), and the
2328 // second must be derived from the same PHI.
2329 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2330 Constant *StartCST =
2331 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2332 if (StartCST == 0) return UnknownValue; // Must be a constant.
2333
2334 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2335 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2336 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2337
2338 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2339 // the loop symbolically to determine when the condition gets a value of
2340 // "ExitWhen".
2341 unsigned IterationNum = 0;
2342 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2343 for (Constant *PHIVal = StartCST;
2344 IterationNum != MaxIterations; ++IterationNum) {
2345 ConstantInt *CondVal =
2346 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2347
2348 // Couldn't symbolically evaluate.
2349 if (!CondVal) return UnknownValue;
2350
2351 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2352 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2353 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002354 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355 }
2356
2357 // Compute the value of the PHI node for the next iteration.
2358 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2359 if (NextPHI == 0 || NextPHI == PHIVal)
2360 return UnknownValue; // Couldn't evaluate or not making progress...
2361 PHIVal = NextPHI;
2362 }
2363
2364 // Too many iterations were needed to evaluate.
2365 return UnknownValue;
2366}
2367
2368/// getSCEVAtScope - Compute the value of the specified expression within the
2369/// indicated loop (which may be null to indicate in no loop). If the
2370/// expression cannot be evaluated, return UnknownValue.
2371SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2372 // FIXME: this should be turned into a virtual method on SCEV!
2373
2374 if (isa<SCEVConstant>(V)) return V;
2375
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002376 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002377 // exit value from the loop without using SCEVs.
2378 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2379 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2380 const Loop *LI = this->LI[I->getParent()];
2381 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2382 if (PHINode *PN = dyn_cast<PHINode>(I))
2383 if (PN->getParent() == LI->getHeader()) {
2384 // Okay, there is no closed form solution for the PHI node. Check
2385 // to see if the loop that contains it has a known iteration count.
2386 // If so, we may be able to force computation of the exit value.
2387 SCEVHandle IterationCount = getIterationCount(LI);
2388 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2389 // Okay, we know how many times the containing loop executes. If
2390 // this is a constant evolving PHI node, get the final value at
2391 // the specified iteration number.
2392 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2393 ICC->getValue()->getValue(),
2394 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002395 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002396 }
2397 }
2398
2399 // Okay, this is an expression that we cannot symbolically evaluate
2400 // into a SCEV. Check to see if it's possible to symbolically evaluate
2401 // the arguments into constants, and if so, try to constant propagate the
2402 // result. This is particularly useful for computing loop exit values.
2403 if (CanConstantFold(I)) {
2404 std::vector<Constant*> Operands;
2405 Operands.reserve(I->getNumOperands());
2406 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2407 Value *Op = I->getOperand(i);
2408 if (Constant *C = dyn_cast<Constant>(Op)) {
2409 Operands.push_back(C);
2410 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002411 // If any of the operands is non-constant and if they are
2412 // non-integer, don't even try to analyze them with scev techniques.
2413 if (!isa<IntegerType>(Op->getType()))
2414 return V;
2415
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002416 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2417 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2418 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2419 Op->getType(),
2420 false));
2421 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2422 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2423 Operands.push_back(ConstantExpr::getIntegerCast(C,
2424 Op->getType(),
2425 false));
2426 else
2427 return V;
2428 } else {
2429 return V;
2430 }
2431 }
2432 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002433
2434 Constant *C;
2435 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2436 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2437 &Operands[0], Operands.size());
2438 else
2439 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2440 &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002441 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002442 }
2443 }
2444
2445 // This is some other type of SCEVUnknown, just return it.
2446 return V;
2447 }
2448
2449 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2450 // Avoid performing the look-up in the common case where the specified
2451 // expression has no loop-variant portions.
2452 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2453 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2454 if (OpAtScope != Comm->getOperand(i)) {
2455 if (OpAtScope == UnknownValue) return UnknownValue;
2456 // Okay, at least one of these operands is loop variant but might be
2457 // foldable. Build a new instance of the folded commutative expression.
2458 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2459 NewOps.push_back(OpAtScope);
2460
2461 for (++i; i != e; ++i) {
2462 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2463 if (OpAtScope == UnknownValue) return UnknownValue;
2464 NewOps.push_back(OpAtScope);
2465 }
2466 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002467 return SE.getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002468 if (isa<SCEVMulExpr>(Comm))
2469 return SE.getMulExpr(NewOps);
2470 if (isa<SCEVSMaxExpr>(Comm))
2471 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002472 if (isa<SCEVUMaxExpr>(Comm))
2473 return SE.getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002474 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002475 }
2476 }
2477 // If we got here, all operands are loop invariant.
2478 return Comm;
2479 }
2480
Nick Lewycky35b56022009-01-13 09:18:58 +00002481 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2482 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002484 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002485 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002486 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2487 return Div; // must be loop invariant
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002488 return SE.getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489 }
2490
2491 // If this is a loop recurrence for a loop that does not contain L, then we
2492 // are dealing with the final value computed by the loop.
2493 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2494 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2495 // To evaluate this recurrence, we need to know how many times the AddRec
2496 // loop iterates. Compute this now.
2497 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2498 if (IterationCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499
Eli Friedman7489ec92008-08-04 23:49:06 +00002500 // Then, evaluate the AddRec.
Dan Gohman89f85052007-10-22 18:31:58 +00002501 return AddRec->evaluateAtIteration(IterationCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002502 }
2503 return UnknownValue;
2504 }
2505
2506 //assert(0 && "Unknown SCEV type!");
2507 return UnknownValue;
2508}
2509
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002510/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2511/// following equation:
2512///
2513/// A * X = B (mod N)
2514///
2515/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2516/// A and B isn't important.
2517///
2518/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2519static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2520 ScalarEvolution &SE) {
2521 uint32_t BW = A.getBitWidth();
2522 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2523 assert(A != 0 && "A must be non-zero.");
2524
2525 // 1. D = gcd(A, N)
2526 //
2527 // The gcd of A and N may have only one prime factor: 2. The number of
2528 // trailing zeros in A is its multiplicity
2529 uint32_t Mult2 = A.countTrailingZeros();
2530 // D = 2^Mult2
2531
2532 // 2. Check if B is divisible by D.
2533 //
2534 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2535 // is not less than multiplicity of this prime factor for D.
2536 if (B.countTrailingZeros() < Mult2)
2537 return new SCEVCouldNotCompute();
2538
2539 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2540 // modulo (N / D).
2541 //
2542 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2543 // bit width during computations.
2544 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2545 APInt Mod(BW + 1, 0);
2546 Mod.set(BW - Mult2); // Mod = N / D
2547 APInt I = AD.multiplicativeInverse(Mod);
2548
2549 // 4. Compute the minimum unsigned root of the equation:
2550 // I * (B / D) mod (N / D)
2551 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2552
2553 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2554 // bits.
2555 return SE.getConstant(Result.trunc(BW));
2556}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002557
2558/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2559/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2560/// might be the same) or two SCEVCouldNotCompute objects.
2561///
2562static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002563SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002564 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2565 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2566 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2567 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2568
2569 // We currently can only solve this if the coefficients are constants.
2570 if (!LC || !MC || !NC) {
2571 SCEV *CNC = new SCEVCouldNotCompute();
2572 return std::make_pair(CNC, CNC);
2573 }
2574
2575 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2576 const APInt &L = LC->getValue()->getValue();
2577 const APInt &M = MC->getValue()->getValue();
2578 const APInt &N = NC->getValue()->getValue();
2579 APInt Two(BitWidth, 2);
2580 APInt Four(BitWidth, 4);
2581
2582 {
2583 using namespace APIntOps;
2584 const APInt& C = L;
2585 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2586 // The B coefficient is M-N/2
2587 APInt B(M);
2588 B -= sdiv(N,Two);
2589
2590 // The A coefficient is N/2
2591 APInt A(N.sdiv(Two));
2592
2593 // Compute the B^2-4ac term.
2594 APInt SqrtTerm(B);
2595 SqrtTerm *= B;
2596 SqrtTerm -= Four * (A * C);
2597
2598 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2599 // integer value or else APInt::sqrt() will assert.
2600 APInt SqrtVal(SqrtTerm.sqrt());
2601
2602 // Compute the two solutions for the quadratic formula.
2603 // The divisions must be performed as signed divisions.
2604 APInt NegB(-B);
2605 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002606 if (TwoA.isMinValue()) {
2607 SCEV *CNC = new SCEVCouldNotCompute();
2608 return std::make_pair(CNC, CNC);
2609 }
2610
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002611 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2612 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2613
Dan Gohman89f85052007-10-22 18:31:58 +00002614 return std::make_pair(SE.getConstant(Solution1),
2615 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002616 } // end APIntOps namespace
2617}
2618
2619/// HowFarToZero - Return the number of times a backedge comparing the specified
2620/// value to zero will execute. If not computable, return UnknownValue
2621SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2622 // If the value is a constant
2623 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2624 // If the value is already zero, the branch will execute zero times.
2625 if (C->getValue()->isZero()) return C;
2626 return UnknownValue; // Otherwise it will loop infinitely.
2627 }
2628
2629 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2630 if (!AddRec || AddRec->getLoop() != L)
2631 return UnknownValue;
2632
2633 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002634 // If this is an affine expression, the execution count of this branch is
2635 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002636 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002637 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002639 // equivalent to:
2640 //
2641 // Step*N = -Start (mod 2^BW)
2642 //
2643 // where BW is the common bit width of Start and Step.
2644
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645 // Get the initial value for the loop.
2646 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2647 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002648
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002649 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002650
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002651 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002652 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002653
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002654 // First, handle unitary steps.
2655 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2656 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2657 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2658 return Start; // N = Start (as unsigned)
2659
2660 // Then, try to solve the above equation provided that Start is constant.
2661 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2662 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2663 -StartC->getValue()->getValue(),SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 }
2665 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2666 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2667 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002668 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2670 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2671 if (R1) {
2672#if 0
2673 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2674 << " sol#2: " << *R2 << "\n";
2675#endif
2676 // Pick the smallest positive root value.
2677 if (ConstantInt *CB =
2678 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2679 R1->getValue(), R2->getValue()))) {
2680 if (CB->getZExtValue() == false)
2681 std::swap(R1, R2); // R1 is the minimum root now.
2682
2683 // We can only use this value if the chrec ends up with an exact zero
2684 // value at this index. When solving for "X*X != 5", for example, we
2685 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002686 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohman7b560c42008-06-18 16:23:07 +00002687 if (Val->isZero())
2688 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002689 }
2690 }
2691 }
2692
2693 return UnknownValue;
2694}
2695
2696/// HowFarToNonZero - Return the number of times a backedge checking the
2697/// specified value for nonzero will execute. If not computable, return
2698/// UnknownValue
2699SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2700 // Loops that look like: while (X == 0) are very strange indeed. We don't
2701 // handle them yet except for the trivial case. This could be expanded in the
2702 // future as needed.
2703
2704 // If the value is a constant, check to see if it is known to be non-zero
2705 // already. If so, the backedge will execute zero times.
2706 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002707 if (!C->getValue()->isNullValue())
2708 return SE.getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002709 return UnknownValue; // Otherwise it will loop infinitely.
2710 }
2711
2712 // We could implement others, but I really doubt anyone writes loops like
2713 // this, and if they did, they would already be constant folded.
2714 return UnknownValue;
2715}
2716
Dan Gohman1cddf972008-09-15 22:18:04 +00002717/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2718/// (which may not be an immediate predecessor) which has exactly one
2719/// successor from which BB is reachable, or null if no such block is
2720/// found.
2721///
2722BasicBlock *
2723ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2724 // If the block has a unique predecessor, the predecessor must have
2725 // no other successors from which BB is reachable.
2726 if (BasicBlock *Pred = BB->getSinglePredecessor())
2727 return Pred;
2728
2729 // A loop's header is defined to be a block that dominates the loop.
2730 // If the loop has a preheader, it must be a block that has exactly
2731 // one successor that can reach BB. This is slightly more strict
2732 // than necessary, but works if critical edges are split.
2733 if (Loop *L = LI.getLoopFor(BB))
2734 return L->getLoopPreheader();
2735
2736 return 0;
2737}
2738
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002739/// executesAtLeastOnce - Test whether entry to the loop is protected by
2740/// a conditional between LHS and RHS.
2741bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2742 SCEV *LHS, SCEV *RHS) {
2743 BasicBlock *Preheader = L->getLoopPreheader();
2744 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002745
Dan Gohmanab678fb2008-08-12 20:17:31 +00002746 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002747 // there are predecessors that can be found that have unique successors
2748 // leading to the original header.
2749 for (; Preheader;
2750 PreheaderDest = Preheader,
2751 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002752
2753 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002754 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002755 if (!LoopEntryPredicate ||
2756 LoopEntryPredicate->isUnconditional())
2757 continue;
2758
2759 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2760 if (!ICI) continue;
2761
2762 // Now that we found a conditional branch that dominates the loop, check to
2763 // see if it is the comparison we are looking for.
2764 Value *PreCondLHS = ICI->getOperand(0);
2765 Value *PreCondRHS = ICI->getOperand(1);
2766 ICmpInst::Predicate Cond;
2767 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2768 Cond = ICI->getPredicate();
2769 else
2770 Cond = ICI->getInversePredicate();
2771
2772 switch (Cond) {
2773 case ICmpInst::ICMP_UGT:
Nick Lewycky35b56022009-01-13 09:18:58 +00002774 if (isSigned) continue;
Dan Gohmanab678fb2008-08-12 20:17:31 +00002775 std::swap(PreCondLHS, PreCondRHS);
2776 Cond = ICmpInst::ICMP_ULT;
2777 break;
2778 case ICmpInst::ICMP_SGT:
Nick Lewycky35b56022009-01-13 09:18:58 +00002779 if (!isSigned) continue;
Dan Gohmanab678fb2008-08-12 20:17:31 +00002780 std::swap(PreCondLHS, PreCondRHS);
2781 Cond = ICmpInst::ICMP_SLT;
2782 break;
2783 case ICmpInst::ICMP_ULT:
Nick Lewycky35b56022009-01-13 09:18:58 +00002784 if (isSigned) continue;
Dan Gohmanab678fb2008-08-12 20:17:31 +00002785 break;
2786 case ICmpInst::ICMP_SLT:
Nick Lewycky35b56022009-01-13 09:18:58 +00002787 if (!isSigned) continue;
Dan Gohmanab678fb2008-08-12 20:17:31 +00002788 break;
2789 default:
2790 continue;
2791 }
2792
2793 if (!PreCondLHS->getType()->isInteger()) continue;
2794
2795 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2796 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2797 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2798 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2799 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2800 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002801 }
2802
Dan Gohmanab678fb2008-08-12 20:17:31 +00002803 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002804}
2805
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002806/// HowManyLessThans - Return the number of times a backedge containing the
2807/// specified less-than comparison will execute. If not computable, return
2808/// UnknownValue.
2809SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky35b56022009-01-13 09:18:58 +00002810HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002811 // Only handle: "ADDREC < LoopInvariant".
2812 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2813
2814 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2815 if (!AddRec || AddRec->getLoop() != L)
2816 return UnknownValue;
2817
2818 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002819 // FORNOW: We only support unit strides.
2820 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2821 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822 return UnknownValue;
2823
Nick Lewycky35b56022009-01-13 09:18:58 +00002824 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2825 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2826 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00002827 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002828
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002829 // First, we get the value of the LHS in the first iteration: n
2830 SCEVHandle Start = AddRec->getOperand(0);
2831
Nick Lewycky35b56022009-01-13 09:18:58 +00002832 if (executesAtLeastOnce(L, isSigned,
2833 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2834 // Since we know that the condition is true in order to enter the loop,
2835 // we know that it will run exactly m-n times.
2836 return SE.getMinusSCEV(RHS, Start);
2837 } else {
2838 // Then, we get the value of the LHS in the first iteration in which the
2839 // above condition doesn't hold. This equals to max(m,n).
2840 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2841 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002842
Nick Lewycky35b56022009-01-13 09:18:58 +00002843 // Finally, we subtract these two values to get the number of times the
2844 // backedge is executed: max(m,n)-n.
2845 return SE.getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00002846 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002847 }
2848
2849 return UnknownValue;
2850}
2851
2852/// getNumIterationsInRange - Return the number of iterations of this loop that
2853/// produce values in the specified constant range. Another way of looking at
2854/// this is that it returns the first iteration number where the value is not in
2855/// the condition, thus computing the exit count. If the iteration count can't
2856/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00002857SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2858 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002859 if (Range.isFullSet()) // Infinite loop.
2860 return new SCEVCouldNotCompute();
2861
2862 // If the start is a non-zero constant, shift the range to simplify things.
2863 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2864 if (!SC->getValue()->isZero()) {
2865 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002866 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2867 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002868 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2869 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00002870 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871 // This is strange and shouldn't happen.
2872 return new SCEVCouldNotCompute();
2873 }
2874
2875 // The only time we can solve this is when we have all constant indices.
2876 // Otherwise, we cannot determine the overflow conditions.
2877 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2878 if (!isa<SCEVConstant>(getOperand(i)))
2879 return new SCEVCouldNotCompute();
2880
2881
2882 // Okay at this point we know that all elements of the chrec are constants and
2883 // that the start element is zero.
2884
2885 // First check to see if the range contains zero. If not, the first
2886 // iteration exits.
2887 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman89f85052007-10-22 18:31:58 +00002888 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002889
2890 if (isAffine()) {
2891 // If this is an affine expression then we have this situation:
2892 // Solve {0,+,A} in Range === Ax in Range
2893
2894 // We know that zero is in the range. If A is positive then we know that
2895 // the upper value of the range must be the first possible exit value.
2896 // If A is negative then the lower of the range is the last possible loop
2897 // value. Also note that we already checked for a full range.
2898 APInt One(getBitWidth(),1);
2899 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2900 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2901
2902 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00002903 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002904 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2905
2906 // Evaluate at the exit value. If we really did fall out of the valid
2907 // range, then we computed our trip count, otherwise wrap around or other
2908 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00002909 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 if (Range.contains(Val->getValue()))
2911 return new SCEVCouldNotCompute(); // Something strange happened
2912
2913 // Ensure that the previous value is in the range. This is a sanity check.
2914 assert(Range.contains(
2915 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002916 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00002918 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002919 } else if (isQuadratic()) {
2920 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2921 // quadratic equation to solve it. To do this, we must frame our problem in
2922 // terms of figuring out when zero is crossed, instead of when
2923 // Range.getUpper() is crossed.
2924 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002925 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2926 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002927
2928 // Next, solve the constructed addrec
2929 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00002930 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002931 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2932 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2933 if (R1) {
2934 // Pick the smallest positive root value.
2935 if (ConstantInt *CB =
2936 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2937 R1->getValue(), R2->getValue()))) {
2938 if (CB->getZExtValue() == false)
2939 std::swap(R1, R2); // R1 is the minimum root now.
2940
2941 // Make sure the root is not off by one. The returned iteration should
2942 // not be in the range, but the previous one should be. When solving
2943 // for "X*X < 5", for example, we should not return a root of 2.
2944 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002945 R1->getValue(),
2946 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002947 if (Range.contains(R1Val->getValue())) {
2948 // The next iteration must be out of the range...
2949 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2950
Dan Gohman89f85052007-10-22 18:31:58 +00002951 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00002953 return SE.getConstant(NextVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002954 return new SCEVCouldNotCompute(); // Something strange happened
2955 }
2956
2957 // If R1 was not in the range, then it is a good return value. Make
2958 // sure that R1-1 WAS in the range though, just in case.
2959 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00002960 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002961 if (Range.contains(R1Val->getValue()))
2962 return R1;
2963 return new SCEVCouldNotCompute(); // Something strange happened
2964 }
2965 }
2966 }
2967
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002968 return new SCEVCouldNotCompute();
2969}
2970
2971
2972
2973//===----------------------------------------------------------------------===//
2974// ScalarEvolution Class Implementation
2975//===----------------------------------------------------------------------===//
2976
2977bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman89f85052007-10-22 18:31:58 +00002978 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979 return false;
2980}
2981
2982void ScalarEvolution::releaseMemory() {
2983 delete (ScalarEvolutionsImpl*)Impl;
2984 Impl = 0;
2985}
2986
2987void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2988 AU.setPreservesAll();
2989 AU.addRequiredTransitive<LoopInfo>();
2990}
2991
2992SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2993 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2994}
2995
2996/// hasSCEV - Return true if the SCEV for this value has already been
2997/// computed.
2998bool ScalarEvolution::hasSCEV(Value *V) const {
2999 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3000}
3001
3002
3003/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3004/// the specified value.
3005void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3006 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3007}
3008
3009
3010SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3011 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3012}
3013
3014bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3015 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3016}
3017
3018SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3019 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3020}
3021
3022void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3023 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3024}
3025
3026static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3027 const Loop *L) {
3028 // Print all inner loops first
3029 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3030 PrintLoopInfo(OS, SE, *I);
3031
Nick Lewyckye5da1912008-01-02 02:49:20 +00003032 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033
Devang Patel02451fa2007-08-21 00:31:24 +00003034 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035 L->getExitBlocks(ExitBlocks);
3036 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003037 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038
3039 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckye5da1912008-01-02 02:49:20 +00003040 OS << *SE->getIterationCount(L) << " iterations! ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003041 } else {
Nick Lewyckye5da1912008-01-02 02:49:20 +00003042 OS << "Unpredictable iteration count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043 }
3044
Nick Lewyckye5da1912008-01-02 02:49:20 +00003045 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046}
3047
3048void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3049 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3050 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3051
3052 OS << "Classifying expressions for: " << F.getName() << "\n";
3053 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3054 if (I->getType()->isInteger()) {
3055 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003056 OS << " --> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003057 SCEVHandle SV = getSCEV(&*I);
3058 SV->print(OS);
3059 OS << "\t\t";
3060
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003061 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3062 OS << "Exits: ";
3063 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3064 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3065 OS << "<<Unknown>>";
3066 } else {
3067 OS << *ExitValue;
3068 }
3069 }
3070
3071
3072 OS << "\n";
3073 }
3074
3075 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3076 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3077 PrintLoopInfo(OS, this, *I);
3078}