blob: f0848569ddbe36c30762c8b8381eb6b7160dfe8e [file] [log] [blame]
Chris Lattnerd934c702004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
Chris Lattnerd934c702004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
Chris Lattnerd934c702004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
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.
Misha Brukman01808ca2005-04-21 21:13:18 +000031//
Chris Lattnerd934c702004-04-02 20:23:17 +000032// 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//
Chris Lattnerd934c702004-04-02 20:23:17 +000036// 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
Chris Lattnerb4f681b2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattnerec901cc2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000066#include "llvm/Instructions.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000068#include "llvm/Analysis/LoopInfo.h"
69#include "llvm/Assembly/Writer.h"
70#include "llvm/Transforms/Scalar.h"
71#include "llvm/Support/CFG.h"
72#include "llvm/Support/ConstantRange.h"
73#include "llvm/Support/InstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000074#include "llvm/Support/CommandLine.h"
75#include "llvm/ADT/Statistic.h"
Brian Gaeke174633b2004-04-16 15:57:32 +000076#include <cmath>
Chris Lattner6806c022006-01-22 23:19:18 +000077#include <iostream>
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000078#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000079using namespace llvm;
80
81namespace {
82 RegisterAnalysis<ScalarEvolution>
Chris Lattner663ebc32004-04-19 03:42:32 +000083 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattnerd934c702004-04-02 20:23:17 +000084
85 Statistic<>
86 NumBruteForceEvaluations("scalar-evolution",
Chris Lattnerec901cc2004-10-12 01:49:27 +000087 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89 Statistic<>
90 NumArrayLenItCounts("scalar-evolution",
91 "Number of trip counts computed with array length");
Chris Lattnerd934c702004-04-02 20:23:17 +000092 Statistic<>
93 NumTripCountsComputed("scalar-evolution",
94 "Number of loops with predictable loop counts");
95 Statistic<>
96 NumTripCountsNotComputed("scalar-evolution",
97 "Number of loops without predictable loop counts");
Chris Lattner4021d1a2004-04-17 18:36:24 +000098 Statistic<>
99 NumBruteForceTripCountsComputed("scalar-evolution",
100 "Number of loops with trip counts computed by force");
101
102 cl::opt<unsigned>
103 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
Chris Lattnercd002b22005-09-28 22:30:58 +0000104 cl::desc("Maximum number of iterations SCEV will "
105 "symbolically execute a constant derived loop"),
Chris Lattner4021d1a2004-04-17 18:36:24 +0000106 cl::init(100));
Chris Lattnerd934c702004-04-02 20:23:17 +0000107}
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Chris Lattnerd934c702004-04-02 20:23:17 +0000116SCEV::~SCEV() {}
117void SCEV::dump() const {
118 print(std::cerr);
119}
120
121/// getValueRange - Return the tightest constant bounds that this value is
122/// known to have. This method is only valid on integer SCEV objects.
123ConstantRange SCEV::getValueRange() const {
124 const Type *Ty = getType();
125 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
126 Ty = Ty->getUnsignedVersion();
127 // Default to a full range if no better information is available.
128 return ConstantRange(getType());
129}
130
131
132SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
133
134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukman5ebc25c2004-04-05 19:00:46 +0000136 return false;
Chris Lattnerd934c702004-04-02 20:23:17 +0000137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukman5ebc25c2004-04-05 19:00:46 +0000141 return 0;
Chris Lattnerd934c702004-04-02 20:23:17 +0000142}
143
144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
151 const SCEVHandle &Conc) const {
152 return this;
153}
154
Chris Lattnerd934c702004-04-02 20:23:17 +0000155void 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
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000164// 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 std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
Misha Brukman01808ca2005-04-21 21:13:18 +0000168
Chris Lattnerd934c702004-04-02 20:23:17 +0000169
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000170SCEVConstant::~SCEVConstant() {
171 SCEVConstants.erase(V);
172}
Chris Lattnerd934c702004-04-02 20:23:17 +0000173
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000174SCEVHandle SCEVConstant::get(ConstantInt *V) {
175 // Make sure that SCEVConstant instances are all unsigned.
176 if (V->getType()->isSigned()) {
177 const Type *NewTy = V->getType()->getUnsignedVersion();
178 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
179 }
Misha Brukman01808ca2005-04-21 21:13:18 +0000180
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000181 SCEVConstant *&R = SCEVConstants[V];
182 if (R == 0) R = new SCEVConstant(V);
183 return R;
184}
Chris Lattnerd934c702004-04-02 20:23:17 +0000185
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000186ConstantRange SCEVConstant::getValueRange() const {
187 return ConstantRange(V);
188}
Chris Lattnerd934c702004-04-02 20:23:17 +0000189
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000190const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattnerd934c702004-04-02 20:23:17 +0000191
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000192void SCEVConstant::print(std::ostream &OS) const {
193 WriteAsOperand(OS, V, false);
194}
Chris Lattnerd934c702004-04-02 20:23:17 +0000195
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000196// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
197// particular input. Don't use a SCEVHandle here, or else the object will
198// never be deleted!
199static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
Chris Lattnerd934c702004-04-02 20:23:17 +0000200
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000201SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
202 : SCEV(scTruncate), Op(op), Ty(ty) {
203 assert(Op->getType()->isInteger() && Ty->isInteger() &&
204 Ty->isUnsigned() &&
205 "Cannot truncate non-integer value!");
206 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
207 "This is not a truncating conversion!");
208}
Chris Lattnerd934c702004-04-02 20:23:17 +0000209
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000210SCEVTruncateExpr::~SCEVTruncateExpr() {
211 SCEVTruncates.erase(std::make_pair(Op, Ty));
212}
Chris Lattnerd934c702004-04-02 20:23:17 +0000213
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000214ConstantRange SCEVTruncateExpr::getValueRange() const {
215 return getOperand()->getValueRange().truncate(getType());
216}
Chris Lattnerd934c702004-04-02 20:23:17 +0000217
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000218void SCEVTruncateExpr::print(std::ostream &OS) const {
219 OS << "(truncate " << *Op << " to " << *Ty << ")";
220}
221
222// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223// particular input. Don't use a SCEVHandle here, or else the object will never
224// be deleted!
225static std::map<std::pair<SCEV*, const Type*>,
226 SCEVZeroExtendExpr*> SCEVZeroExtends;
227
228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Chris Lattner47555de2005-02-17 16:54:16 +0000229 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000230 assert(Op->getType()->isInteger() && Ty->isInteger() &&
231 Ty->isUnsigned() &&
232 "Cannot zero extend non-integer value!");
233 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
234 "This is not an extending conversion!");
235}
236
237SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
238 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
239}
240
241ConstantRange SCEVZeroExtendExpr::getValueRange() const {
242 return getOperand()->getValueRange().zeroExtend(getType());
243}
244
245void SCEVZeroExtendExpr::print(std::ostream &OS) const {
246 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
247}
248
249// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
250// particular input. Don't use a SCEVHandle here, or else the object will never
251// be deleted!
252static std::map<std::pair<unsigned, std::vector<SCEV*> >,
253 SCEVCommutativeExpr*> SCEVCommExprs;
254
255SCEVCommutativeExpr::~SCEVCommutativeExpr() {
256 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
257 std::vector<SCEV*>(Operands.begin(),
258 Operands.end())));
259}
260
261void SCEVCommutativeExpr::print(std::ostream &OS) const {
262 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
263 const char *OpStr = getOperationStr();
264 OS << "(" << *Operands[0];
265 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
266 OS << OpStr << *Operands[i];
267 OS << ")";
268}
269
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000270SCEVHandle SCEVCommutativeExpr::
271replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
272 const SCEVHandle &Conc) const {
273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
274 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
275 if (H != getOperand(i)) {
276 std::vector<SCEVHandle> NewOps;
277 NewOps.reserve(getNumOperands());
278 for (unsigned j = 0; j != i; ++j)
279 NewOps.push_back(getOperand(j));
280 NewOps.push_back(H);
281 for (++i; i != e; ++i)
282 NewOps.push_back(getOperand(i)->
283 replaceSymbolicValuesWithConcrete(Sym, Conc));
284
285 if (isa<SCEVAddExpr>(this))
286 return SCEVAddExpr::get(NewOps);
287 else if (isa<SCEVMulExpr>(this))
288 return SCEVMulExpr::get(NewOps);
289 else
290 assert(0 && "Unknown commutative expr!");
291 }
292 }
293 return this;
294}
295
296
Chris Lattner98e96042006-04-01 04:48:52 +0000297// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000298// input. Don't use a SCEVHandle here, or else the object will never be
299// deleted!
Chris Lattner98e96042006-04-01 04:48:52 +0000300static std::map<std::pair<SCEV*, SCEV*>, SCEVSDivExpr*> SCEVSDivs;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000301
Chris Lattner98e96042006-04-01 04:48:52 +0000302SCEVSDivExpr::~SCEVSDivExpr() {
303 SCEVSDivs.erase(std::make_pair(LHS, RHS));
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000304}
305
Chris Lattner98e96042006-04-01 04:48:52 +0000306void SCEVSDivExpr::print(std::ostream &OS) const {
307 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000308}
309
Chris Lattner98e96042006-04-01 04:48:52 +0000310const Type *SCEVSDivExpr::getType() const {
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000311 const Type *Ty = LHS->getType();
Chris Lattner98e96042006-04-01 04:48:52 +0000312 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000313 return Ty;
314}
315
316// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
317// particular input. Don't use a SCEVHandle here, or else the object will never
318// be deleted!
319static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
320 SCEVAddRecExpr*> SCEVAddRecExprs;
321
322SCEVAddRecExpr::~SCEVAddRecExpr() {
323 SCEVAddRecExprs.erase(std::make_pair(L,
324 std::vector<SCEV*>(Operands.begin(),
325 Operands.end())));
326}
327
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000328SCEVHandle SCEVAddRecExpr::
329replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
330 const SCEVHandle &Conc) const {
331 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
332 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
333 if (H != getOperand(i)) {
334 std::vector<SCEVHandle> NewOps;
335 NewOps.reserve(getNumOperands());
336 for (unsigned j = 0; j != i; ++j)
337 NewOps.push_back(getOperand(j));
338 NewOps.push_back(H);
339 for (++i; i != e; ++i)
340 NewOps.push_back(getOperand(i)->
341 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman01808ca2005-04-21 21:13:18 +0000342
Chris Lattner7b0fbe72005-02-13 04:37:18 +0000343 return get(NewOps, L);
344 }
345 }
346 return this;
347}
348
349
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000350bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
351 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnere5154162005-08-16 00:37:01 +0000352 // contain L and if the start is invariant.
353 return !QueryLoop->contains(L->getHeader()) &&
354 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattnerd934c702004-04-02 20:23:17 +0000355}
356
357
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000358void SCEVAddRecExpr::print(std::ostream &OS) const {
359 OS << "{" << *Operands[0];
360 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
361 OS << ",+," << *Operands[i];
362 OS << "}<" << L->getHeader()->getName() + ">";
363}
Chris Lattnerd934c702004-04-02 20:23:17 +0000364
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000365// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
366// value. Don't use a SCEVHandle here, or else the object will never be
367// deleted!
368static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
Chris Lattnerd934c702004-04-02 20:23:17 +0000369
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000370SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
Chris Lattnerd934c702004-04-02 20:23:17 +0000371
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000372bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
373 // All non-instruction values are loop invariant. All instructions are loop
374 // invariant if they are not contained in the specified loop.
375 if (Instruction *I = dyn_cast<Instruction>(V))
376 return !L->contains(I->getParent());
377 return true;
378}
Chris Lattnerd934c702004-04-02 20:23:17 +0000379
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000380const Type *SCEVUnknown::getType() const {
381 return V->getType();
382}
Chris Lattnerd934c702004-04-02 20:23:17 +0000383
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000384void SCEVUnknown::print(std::ostream &OS) const {
385 WriteAsOperand(OS, V, false);
Chris Lattnerd934c702004-04-02 20:23:17 +0000386}
387
Chris Lattnereb3e8402004-06-20 06:23:15 +0000388//===----------------------------------------------------------------------===//
389// SCEV Utilities
390//===----------------------------------------------------------------------===//
391
392namespace {
393 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
394 /// than the complexity of the RHS. This comparator is used to canonicalize
395 /// expressions.
396 struct SCEVComplexityCompare {
397 bool operator()(SCEV *LHS, SCEV *RHS) {
398 return LHS->getSCEVType() < RHS->getSCEVType();
399 }
400 };
401}
402
403/// GroupByComplexity - Given a list of SCEV objects, order them by their
404/// complexity, and group objects of the same complexity together by value.
405/// When this routine is finished, we know that any duplicates in the vector are
406/// consecutive and that complexity is monotonically increasing.
407///
408/// Note that we go take special precautions to ensure that we get determinstic
409/// results from this routine. In other words, we don't want the results of
410/// this to depend on where the addresses of various SCEV objects happened to
411/// land in memory.
412///
413static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
414 if (Ops.size() < 2) return; // Noop
415 if (Ops.size() == 2) {
416 // This is the common case, which also happens to be trivially simple.
417 // Special case it.
418 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
419 std::swap(Ops[0], Ops[1]);
420 return;
421 }
422
423 // Do the rough sort by complexity.
424 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
425
426 // Now that we are sorted by complexity, group elements of the same
427 // complexity. Note that this is, at worst, N^2, but the vector is likely to
428 // be extremely short in practice. Note that we take this approach because we
429 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner6bfca8f2004-06-20 17:01:44 +0000430 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000431 SCEV *S = Ops[i];
432 unsigned Complexity = S->getSCEVType();
433
434 // If there are any objects of the same complexity and same value as this
435 // one, group them.
436 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
437 if (Ops[j] == S) { // Found a duplicate.
438 // Move it to immediately after i'th element.
439 std::swap(Ops[i+1], Ops[j]);
440 ++i; // no need to rescan it.
Chris Lattnerbaaed7e2004-06-20 20:32:16 +0000441 if (i == e-2) return; // Done!
Chris Lattnereb3e8402004-06-20 06:23:15 +0000442 }
443 }
444 }
445}
446
Chris Lattnerd934c702004-04-02 20:23:17 +0000447
Chris Lattnerd934c702004-04-02 20:23:17 +0000448
449//===----------------------------------------------------------------------===//
450// Simple SCEV method implementations
451//===----------------------------------------------------------------------===//
452
453/// getIntegerSCEV - Given an integer or FP type, create a constant for the
454/// specified signed integer value and return a SCEV for the constant.
Chris Lattner05ef97f2004-04-23 21:29:03 +0000455SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000456 Constant *C;
Misha Brukman01808ca2005-04-21 21:13:18 +0000457 if (Val == 0)
Chris Lattnerd934c702004-04-02 20:23:17 +0000458 C = Constant::getNullValue(Ty);
459 else if (Ty->isFloatingPoint())
460 C = ConstantFP::get(Ty, Val);
461 else if (Ty->isSigned())
462 C = ConstantSInt::get(Ty, Val);
463 else {
464 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
465 C = ConstantExpr::getCast(C, Ty);
466 }
467 return SCEVUnknown::get(C);
468}
469
470/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
471/// input value to the specified type. If the type must be extended, it is zero
472/// extended.
473static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
474 const Type *SrcTy = V->getType();
475 assert(SrcTy->isInteger() && Ty->isInteger() &&
476 "Cannot truncate or zero extend with non-integer arguments!");
477 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
478 return V; // No conversion
479 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
480 return SCEVTruncateExpr::get(V, Ty);
481 return SCEVZeroExtendExpr::get(V, Ty);
482}
483
484/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
485///
Chris Lattneradb043c2005-03-09 05:34:41 +0000486SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000487 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
488 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman01808ca2005-04-21 21:13:18 +0000489
Chris Lattner05ef97f2004-04-23 21:29:03 +0000490 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattnerd934c702004-04-02 20:23:17 +0000491}
492
493/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
494///
Chris Lattneradb043c2005-03-09 05:34:41 +0000495SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000496 // X - Y --> X + -Y
Chris Lattneradb043c2005-03-09 05:34:41 +0000497 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattnerd934c702004-04-02 20:23:17 +0000498}
499
500
Chris Lattnerd934c702004-04-02 20:23:17 +0000501/// PartialFact - Compute V!/(V-NumSteps)!
502static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
503 // Handle this case efficiently, it is common to have constant iteration
504 // counts while computing loop exit values.
505 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
506 uint64_t Val = SC->getValue()->getRawValue();
507 uint64_t Result = 1;
508 for (; NumSteps; --NumSteps)
509 Result *= Val-(NumSteps-1);
510 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
511 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
512 }
513
514 const Type *Ty = V->getType();
515 if (NumSteps == 0)
Chris Lattner05ef97f2004-04-23 21:29:03 +0000516 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman01808ca2005-04-21 21:13:18 +0000517
Chris Lattnerd934c702004-04-02 20:23:17 +0000518 SCEVHandle Result = V;
519 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattneradb043c2005-03-09 05:34:41 +0000520 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattner05ef97f2004-04-23 21:29:03 +0000521 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +0000522 return Result;
523}
524
525
526/// evaluateAtIteration - Return the value of this chain of recurrences at
527/// the specified iteration number. We can evaluate this recurrence by
528/// multiplying each element in the chain by the binomial coefficient
529/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
530///
531/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
532///
533/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
534/// Is the binomial equation safe using modular arithmetic??
535///
536SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
537 SCEVHandle Result = getStart();
538 int Divisor = 1;
539 const Type *Ty = It->getType();
540 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
541 SCEVHandle BC = PartialFact(It, i);
542 Divisor *= i;
Chris Lattner98e96042006-04-01 04:48:52 +0000543 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattner05ef97f2004-04-23 21:29:03 +0000544 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattnerd934c702004-04-02 20:23:17 +0000545 Result = SCEVAddExpr::get(Result, Val);
546 }
547 return Result;
548}
549
550
551//===----------------------------------------------------------------------===//
552// SCEV Expression folder implementations
553//===----------------------------------------------------------------------===//
554
555SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
556 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
557 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
558
559 // If the input value is a chrec scev made out of constants, truncate
560 // all of the constants.
561 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
562 std::vector<SCEVHandle> Operands;
563 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
564 // FIXME: This should allow truncation of other expression types!
565 if (isa<SCEVConstant>(AddRec->getOperand(i)))
566 Operands.push_back(get(AddRec->getOperand(i), Ty));
567 else
568 break;
569 if (Operands.size() == AddRec->getNumOperands())
570 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
571 }
572
573 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
574 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
575 return Result;
576}
577
578SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
579 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
580 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
581
582 // FIXME: If the input value is a chrec scev, and we can prove that the value
583 // did not overflow the old, smaller, value, we can zero extend all of the
584 // operands (often constants). This would allow analysis of something like
585 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
586
587 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
588 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
589 return Result;
590}
591
592// get - Get a canonical add expression, or something simpler if possible.
593SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
594 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +0000595 if (Ops.size() == 1) return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +0000596
597 // Sort by complexity, this groups all similar expression types together.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000598 GroupByComplexity(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000599
600 // If there are any constants, fold them together.
601 unsigned Idx = 0;
602 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
603 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +0000604 assert(Idx < Ops.size());
Chris Lattnerd934c702004-04-02 20:23:17 +0000605 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
606 // We found two constants, fold them together!
607 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
609 Ops[0] = SCEVConstant::get(CI);
610 Ops.erase(Ops.begin()+1); // Erase the folded element
611 if (Ops.size() == 1) return Ops[0];
Chris Lattnerf05d2b32005-02-26 18:50:19 +0000612 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +0000613 } else {
614 // If we couldn't fold the expression, move to the next constant. Note
615 // that this is impossible to happen in practice because we always
616 // constant fold constant ints to constant ints.
617 ++Idx;
618 }
619 }
620
621 // If we are left with a constant zero being added, strip it off.
622 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
623 Ops.erase(Ops.begin());
624 --Idx;
625 }
626 }
627
Chris Lattner74498e12004-04-07 16:16:11 +0000628 if (Ops.size() == 1) return Ops[0];
Misha Brukman01808ca2005-04-21 21:13:18 +0000629
Chris Lattnerd934c702004-04-02 20:23:17 +0000630 // Okay, check to see if the same value occurs in the operand list twice. If
631 // so, merge them together into an multiply expression. Since we sorted the
632 // list, these values are required to be adjacent.
633 const Type *Ty = Ops[0]->getType();
634 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
635 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
636 // Found a match, merge the two values into a multiply, and add any
637 // remaining values to the result.
Chris Lattner05ef97f2004-04-23 21:29:03 +0000638 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattnerd934c702004-04-02 20:23:17 +0000639 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
640 if (Ops.size() == 2)
641 return Mul;
642 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
643 Ops.push_back(Mul);
644 return SCEVAddExpr::get(Ops);
645 }
646
647 // Okay, now we know the first non-constant operand. If there are add
648 // operands they would be next.
649 if (Idx < Ops.size()) {
650 bool DeletedAdd = false;
651 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
652 // If we have an add, expand the add operands onto the end of the operands
653 // list.
654 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
655 Ops.erase(Ops.begin()+Idx);
656 DeletedAdd = true;
657 }
658
659 // If we deleted at least one add, we added operands to the end of the list,
660 // and they are not necessarily sorted. Recurse to resort and resimplify
661 // any operands we just aquired.
662 if (DeletedAdd)
663 return get(Ops);
664 }
665
666 // Skip over the add expression until we get to a multiply.
667 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
668 ++Idx;
669
670 // If we are adding something to a multiply expression, make sure the
671 // something is not already an operand of the multiply. If so, merge it into
672 // the multiply.
673 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
674 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
675 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
676 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
677 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattnera27dd472004-12-04 20:54:32 +0000678 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000679 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
680 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
681 if (Mul->getNumOperands() != 2) {
682 // If the multiply has more than two operands, we must get the
683 // Y*Z term.
684 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
685 MulOps.erase(MulOps.begin()+MulOp);
686 InnerMul = SCEVMulExpr::get(MulOps);
687 }
Chris Lattner05ef97f2004-04-23 21:29:03 +0000688 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattnerd934c702004-04-02 20:23:17 +0000689 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
690 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
691 if (Ops.size() == 2) return OuterMul;
692 if (AddOp < Idx) {
693 Ops.erase(Ops.begin()+AddOp);
694 Ops.erase(Ops.begin()+Idx-1);
695 } else {
696 Ops.erase(Ops.begin()+Idx);
697 Ops.erase(Ops.begin()+AddOp-1);
698 }
699 Ops.push_back(OuterMul);
700 return SCEVAddExpr::get(Ops);
701 }
Misha Brukman01808ca2005-04-21 21:13:18 +0000702
Chris Lattnerd934c702004-04-02 20:23:17 +0000703 // Check this multiply against other multiplies being added together.
704 for (unsigned OtherMulIdx = Idx+1;
705 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
706 ++OtherMulIdx) {
707 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
708 // If MulOp occurs in OtherMul, we can fold the two multiplies
709 // together.
710 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
711 OMulOp != e; ++OMulOp)
712 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
713 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
714 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
715 if (Mul->getNumOperands() != 2) {
716 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
717 MulOps.erase(MulOps.begin()+MulOp);
718 InnerMul1 = SCEVMulExpr::get(MulOps);
719 }
720 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
721 if (OtherMul->getNumOperands() != 2) {
722 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
723 OtherMul->op_end());
724 MulOps.erase(MulOps.begin()+OMulOp);
725 InnerMul2 = SCEVMulExpr::get(MulOps);
726 }
727 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
728 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
729 if (Ops.size() == 2) return OuterMul;
730 Ops.erase(Ops.begin()+Idx);
731 Ops.erase(Ops.begin()+OtherMulIdx-1);
732 Ops.push_back(OuterMul);
733 return SCEVAddExpr::get(Ops);
734 }
735 }
736 }
737 }
738
739 // If there are any add recurrences in the operands list, see if any other
740 // added values are loop invariant. If so, we can fold them into the
741 // recurrence.
742 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
743 ++Idx;
744
745 // Scan over all recurrences, trying to fold loop invariants into them.
746 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
747 // Scan all of the other operands to this add and add them to the vector if
748 // they are loop invariant w.r.t. the recurrence.
749 std::vector<SCEVHandle> LIOps;
750 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
751 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
752 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
753 LIOps.push_back(Ops[i]);
754 Ops.erase(Ops.begin()+i);
755 --i; --e;
756 }
757
758 // If we found some loop invariants, fold them into the recurrence.
759 if (!LIOps.empty()) {
760 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
761 LIOps.push_back(AddRec->getStart());
762
763 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
764 AddRecOps[0] = SCEVAddExpr::get(LIOps);
765
766 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
767 // If all of the other operands were loop invariant, we are done.
768 if (Ops.size() == 1) return NewRec;
769
770 // Otherwise, add the folded AddRec by the non-liv parts.
771 for (unsigned i = 0;; ++i)
772 if (Ops[i] == AddRec) {
773 Ops[i] = NewRec;
774 break;
775 }
776 return SCEVAddExpr::get(Ops);
777 }
778
779 // Okay, if there weren't any loop invariants to be folded, check to see if
780 // there are multiple AddRec's with the same loop induction variable being
781 // added together. If so, we can fold them.
782 for (unsigned OtherIdx = Idx+1;
783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
784 if (OtherIdx != Idx) {
785 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
786 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
787 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
788 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
789 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
790 if (i >= NewOps.size()) {
791 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
792 OtherAddRec->op_end());
793 break;
794 }
795 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
796 }
797 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
798
799 if (Ops.size() == 2) return NewAddRec;
800
801 Ops.erase(Ops.begin()+Idx);
802 Ops.erase(Ops.begin()+OtherIdx-1);
803 Ops.push_back(NewAddRec);
804 return SCEVAddExpr::get(Ops);
805 }
806 }
807
808 // Otherwise couldn't fold anything into this recurrence. Move onto the
809 // next one.
810 }
811
812 // Okay, it looks like we really DO need an add expr. Check to see if we
813 // already have one, otherwise create a new one.
814 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
815 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
816 SCEVOps)];
817 if (Result == 0) Result = new SCEVAddExpr(Ops);
818 return Result;
819}
820
821
822SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
823 assert(!Ops.empty() && "Cannot get empty mul!");
824
825 // Sort by complexity, this groups all similar expression types together.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000826 GroupByComplexity(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000827
828 // If there are any constants, fold them together.
829 unsigned Idx = 0;
830 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
831
832 // C1*(C2+V) -> C1*C2 + C1*V
833 if (Ops.size() == 2)
834 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
835 if (Add->getNumOperands() == 2 &&
836 isa<SCEVConstant>(Add->getOperand(0)))
837 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
838 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
839
840
841 ++Idx;
842 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
843 // We found two constants, fold them together!
844 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
845 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
846 Ops[0] = SCEVConstant::get(CI);
847 Ops.erase(Ops.begin()+1); // Erase the folded element
848 if (Ops.size() == 1) return Ops[0];
Chris Lattnerf05d2b32005-02-26 18:50:19 +0000849 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +0000850 } else {
851 // If we couldn't fold the expression, move to the next constant. Note
852 // that this is impossible to happen in practice because we always
853 // constant fold constant ints to constant ints.
854 ++Idx;
855 }
856 }
857
858 // If we are left with a constant one being multiplied, strip it off.
859 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
860 Ops.erase(Ops.begin());
861 --Idx;
862 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
863 // If we have a multiply of zero, it will always be zero.
864 return Ops[0];
865 }
866 }
867
868 // Skip over the add expression until we get to a multiply.
869 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
870 ++Idx;
871
872 if (Ops.size() == 1)
873 return Ops[0];
Misha Brukman01808ca2005-04-21 21:13:18 +0000874
Chris Lattnerd934c702004-04-02 20:23:17 +0000875 // If there are mul operands inline them all into this expression.
876 if (Idx < Ops.size()) {
877 bool DeletedMul = false;
878 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
879 // If we have an mul, expand the mul operands onto the end of the operands
880 // list.
881 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
882 Ops.erase(Ops.begin()+Idx);
883 DeletedMul = true;
884 }
885
886 // If we deleted at least one mul, we added operands to the end of the list,
887 // and they are not necessarily sorted. Recurse to resort and resimplify
888 // any operands we just aquired.
889 if (DeletedMul)
890 return get(Ops);
891 }
892
893 // If there are any add recurrences in the operands list, see if any other
894 // added values are loop invariant. If so, we can fold them into the
895 // recurrence.
896 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
897 ++Idx;
898
899 // Scan over all recurrences, trying to fold loop invariants into them.
900 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
901 // Scan all of the other operands to this mul and add them to the vector if
902 // they are loop invariant w.r.t. the recurrence.
903 std::vector<SCEVHandle> LIOps;
904 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
905 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
906 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
907 LIOps.push_back(Ops[i]);
908 Ops.erase(Ops.begin()+i);
909 --i; --e;
910 }
911
912 // If we found some loop invariants, fold them into the recurrence.
913 if (!LIOps.empty()) {
914 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
915 std::vector<SCEVHandle> NewOps;
916 NewOps.reserve(AddRec->getNumOperands());
917 if (LIOps.size() == 1) {
918 SCEV *Scale = LIOps[0];
919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
920 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
921 } else {
922 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
923 std::vector<SCEVHandle> MulOps(LIOps);
924 MulOps.push_back(AddRec->getOperand(i));
925 NewOps.push_back(SCEVMulExpr::get(MulOps));
926 }
927 }
928
929 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
930
931 // If all of the other operands were loop invariant, we are done.
932 if (Ops.size() == 1) return NewRec;
933
934 // Otherwise, multiply the folded AddRec by the non-liv parts.
935 for (unsigned i = 0;; ++i)
936 if (Ops[i] == AddRec) {
937 Ops[i] = NewRec;
938 break;
939 }
940 return SCEVMulExpr::get(Ops);
941 }
942
943 // Okay, if there weren't any loop invariants to be folded, check to see if
944 // there are multiple AddRec's with the same loop induction variable being
945 // multiplied together. If so, we can fold them.
946 for (unsigned OtherIdx = Idx+1;
947 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
948 if (OtherIdx != Idx) {
949 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
950 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
951 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
952 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
953 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
954 G->getStart());
955 SCEVHandle B = F->getStepRecurrence();
956 SCEVHandle D = G->getStepRecurrence();
957 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
958 SCEVMulExpr::get(G, B),
959 SCEVMulExpr::get(B, D));
960 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
961 F->getLoop());
962 if (Ops.size() == 2) return NewAddRec;
963
964 Ops.erase(Ops.begin()+Idx);
965 Ops.erase(Ops.begin()+OtherIdx-1);
966 Ops.push_back(NewAddRec);
967 return SCEVMulExpr::get(Ops);
968 }
969 }
970
971 // Otherwise couldn't fold anything into this recurrence. Move onto the
972 // next one.
973 }
974
975 // Okay, it looks like we really DO need an mul expr. Check to see if we
976 // already have one, otherwise create a new one.
977 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
978 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
979 SCEVOps)];
Chris Lattnera27dd472004-12-04 20:54:32 +0000980 if (Result == 0)
981 Result = new SCEVMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000982 return Result;
983}
984
Chris Lattner98e96042006-04-01 04:48:52 +0000985SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000986 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
987 if (RHSC->getValue()->equalsInt(1))
Chris Lattner98e96042006-04-01 04:48:52 +0000988 return LHS; // X /s 1 --> x
Chris Lattnerd934c702004-04-02 20:23:17 +0000989 if (RHSC->getValue()->isAllOnesValue())
Chris Lattner98e96042006-04-01 04:48:52 +0000990 return SCEV::getNegativeSCEV(LHS); // X /s -1 --> -x
Chris Lattnerd934c702004-04-02 20:23:17 +0000991
992 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
993 Constant *LHSCV = LHSC->getValue();
994 Constant *RHSCV = RHSC->getValue();
Chris Lattner98e96042006-04-01 04:48:52 +0000995 if (LHSCV->getType()->isUnsigned())
Chris Lattnerd934c702004-04-02 20:23:17 +0000996 LHSCV = ConstantExpr::getCast(LHSCV,
Chris Lattner98e96042006-04-01 04:48:52 +0000997 LHSCV->getType()->getSignedVersion());
998 if (RHSCV->getType()->isUnsigned())
Chris Lattnerd934c702004-04-02 20:23:17 +0000999 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
1000 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
1001 }
1002 }
1003
1004 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1005
Chris Lattner98e96042006-04-01 04:48:52 +00001006 SCEVSDivExpr *&Result = SCEVSDivs[std::make_pair(LHS, RHS)];
1007 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00001008 return Result;
1009}
1010
1011
1012/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1013/// specified loop. Simplify the expression as much as possible.
1014SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1015 const SCEVHandle &Step, const Loop *L) {
1016 std::vector<SCEVHandle> Operands;
1017 Operands.push_back(Start);
1018 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1019 if (StepChrec->getLoop() == L) {
1020 Operands.insert(Operands.end(), StepChrec->op_begin(),
1021 StepChrec->op_end());
1022 return get(Operands, L);
1023 }
1024
1025 Operands.push_back(Step);
1026 return get(Operands, L);
1027}
1028
1029/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1030/// specified loop. Simplify the expression as much as possible.
1031SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1032 const Loop *L) {
1033 if (Operands.size() == 1) return Operands[0];
1034
1035 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1036 if (StepC->getValue()->isNullValue()) {
1037 Operands.pop_back();
1038 return get(Operands, L); // { X,+,0 } --> X
1039 }
1040
1041 SCEVAddRecExpr *&Result =
1042 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1043 Operands.end()))];
1044 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1045 return Result;
1046}
1047
Chris Lattnerb4f681b2004-04-15 15:07:24 +00001048SCEVHandle SCEVUnknown::get(Value *V) {
1049 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1050 return SCEVConstant::get(CI);
1051 SCEVUnknown *&Result = SCEVUnknowns[V];
1052 if (Result == 0) Result = new SCEVUnknown(V);
1053 return Result;
1054}
1055
Chris Lattnerd934c702004-04-02 20:23:17 +00001056
1057//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00001058// ScalarEvolutionsImpl Definition and Implementation
1059//===----------------------------------------------------------------------===//
1060//
1061/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1062/// evolution code.
1063///
1064namespace {
1065 struct ScalarEvolutionsImpl {
1066 /// F - The function we are analyzing.
1067 ///
1068 Function &F;
1069
1070 /// LI - The loop information for the function we are currently analyzing.
1071 ///
1072 LoopInfo &LI;
1073
1074 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1075 /// things.
1076 SCEVHandle UnknownValue;
1077
1078 /// Scalars - This is a cache of the scalars we have analyzed so far.
1079 ///
1080 std::map<Value*, SCEVHandle> Scalars;
1081
1082 /// IterationCounts - Cache the iteration count of the loops for this
1083 /// function as they are computed.
1084 std::map<const Loop*, SCEVHandle> IterationCounts;
1085
Chris Lattnerdd730472004-04-17 22:58:41 +00001086 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1087 /// the PHI instructions that we attempt to compute constant evolutions for.
1088 /// This allows us to avoid potentially expensive recomputation of these
1089 /// properties. An instruction maps to null if we are unable to compute its
1090 /// exit value.
1091 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman01808ca2005-04-21 21:13:18 +00001092
Chris Lattnerd934c702004-04-02 20:23:17 +00001093 public:
1094 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1095 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1096
1097 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1098 /// expression and create a new one.
1099 SCEVHandle getSCEV(Value *V);
1100
Chris Lattnerb310ac4a2005-08-09 23:36:33 +00001101 /// hasSCEV - Return true if the SCEV for this value has already been
1102 /// computed.
1103 bool hasSCEV(Value *V) const {
1104 return Scalars.count(V);
1105 }
1106
1107 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1108 /// the specified value.
1109 void setSCEV(Value *V, const SCEVHandle &H) {
1110 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1111 assert(isNew && "This entry already existed!");
1112 }
1113
1114
Chris Lattnerd934c702004-04-02 20:23:17 +00001115 /// getSCEVAtScope - Compute the value of the specified expression within
1116 /// the indicated loop (which may be null to indicate in no loop). If the
1117 /// expression cannot be evaluated, return UnknownValue itself.
1118 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1119
1120
1121 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1122 /// an analyzable loop-invariant iteration count.
1123 bool hasLoopInvariantIterationCount(const Loop *L);
1124
1125 /// getIterationCount - If the specified loop has a predictable iteration
1126 /// count, return it. Note that it is not valid to call this method on a
1127 /// loop without a loop-invariant iteration count.
1128 SCEVHandle getIterationCount(const Loop *L);
1129
1130 /// deleteInstructionFromRecords - This method should be called by the
1131 /// client before it removes an instruction from the program, to make sure
1132 /// that no dangling references are left around.
1133 void deleteInstructionFromRecords(Instruction *I);
1134
1135 private:
1136 /// createSCEV - We know that there is no SCEV for the specified value.
1137 /// Analyze the expression.
1138 SCEVHandle createSCEV(Value *V);
1139 SCEVHandle createNodeForCast(CastInst *CI);
1140
1141 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1142 /// SCEVs.
1143 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001144
1145 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1146 /// for the specified instruction and replaces any references to the
1147 /// symbolic value SymName with the specified value. This is used during
1148 /// PHI resolution.
1149 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1150 const SCEVHandle &SymName,
1151 const SCEVHandle &NewVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00001152
1153 /// ComputeIterationCount - Compute the number of times the specified loop
1154 /// will iterate.
1155 SCEVHandle ComputeIterationCount(const Loop *L);
1156
Chris Lattnerec901cc2004-10-12 01:49:27 +00001157 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1158 /// 'setcc load X, cst', try to se if we can compute the trip count.
1159 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1160 Constant *RHS,
1161 const Loop *L,
1162 unsigned SetCCOpcode);
1163
Chris Lattner4021d1a2004-04-17 18:36:24 +00001164 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1165 /// constant number of times (the condition evolves only from constants),
1166 /// try to evaluate a few iterations of the loop until we get the exit
1167 /// condition gets a value of ExitWhen (true or false). If we cannot
1168 /// evaluate the trip count of the loop, return UnknownValue.
1169 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1170 bool ExitWhen);
1171
Chris Lattnerd934c702004-04-02 20:23:17 +00001172 /// HowFarToZero - Return the number of times a backedge comparing the
1173 /// specified value to zero will execute. If not computable, return
Chris Lattner587a75b2005-08-15 23:33:51 +00001174 /// UnknownValue.
Chris Lattnerd934c702004-04-02 20:23:17 +00001175 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1176
1177 /// HowFarToNonZero - Return the number of times a backedge checking the
1178 /// specified value for nonzero will execute. If not computable, return
Chris Lattner587a75b2005-08-15 23:33:51 +00001179 /// UnknownValue.
Chris Lattnerd934c702004-04-02 20:23:17 +00001180 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattnerdd730472004-04-17 22:58:41 +00001181
Chris Lattner587a75b2005-08-15 23:33:51 +00001182 /// HowManyLessThans - Return the number of times a backedge containing the
1183 /// specified less-than comparison will execute. If not computable, return
1184 /// UnknownValue.
1185 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1186
Chris Lattnerdd730472004-04-17 22:58:41 +00001187 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1188 /// in the header of its containing loop, we know the loop executes a
1189 /// constant number of times, and the PHI node is just a recurrence
1190 /// involving constants, fold it.
1191 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1192 const Loop *L);
Chris Lattnerd934c702004-04-02 20:23:17 +00001193 };
1194}
1195
1196//===----------------------------------------------------------------------===//
1197// Basic SCEV Analysis and PHI Idiom Recognition Code
1198//
1199
1200/// deleteInstructionFromRecords - This method should be called by the
1201/// client before it removes an instruction from the program, to make sure
1202/// that no dangling references are left around.
1203void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1204 Scalars.erase(I);
Chris Lattnerdd730472004-04-17 22:58:41 +00001205 if (PHINode *PN = dyn_cast<PHINode>(I))
1206 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00001207}
1208
1209
1210/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1211/// expression and create a new one.
1212SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1213 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1214
1215 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1216 if (I != Scalars.end()) return I->second;
1217 SCEVHandle S = createSCEV(V);
1218 Scalars.insert(std::make_pair(V, S));
1219 return S;
1220}
1221
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001222/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1223/// the specified instruction and replaces any references to the symbolic value
1224/// SymName with the specified value. This is used during PHI resolution.
1225void ScalarEvolutionsImpl::
1226ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1227 const SCEVHandle &NewVal) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001228 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001229 if (SI == Scalars.end()) return;
Chris Lattnerd934c702004-04-02 20:23:17 +00001230
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001231 SCEVHandle NV =
1232 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1233 if (NV == SI->second) return; // No change.
1234
1235 SI->second = NV; // Update the scalars map!
1236
1237 // Any instruction values that use this instruction might also need to be
1238 // updated!
1239 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1240 UI != E; ++UI)
1241 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1242}
Chris Lattnerd934c702004-04-02 20:23:17 +00001243
1244/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1245/// a loop header, making it a potential recurrence, or it doesn't.
1246///
1247SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1248 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1249 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1250 if (L->getHeader() == PN->getParent()) {
1251 // If it lives in the loop header, it has two incoming values, one
1252 // from outside the loop, and one from inside.
1253 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1254 unsigned BackEdge = IncomingEdge^1;
Misha Brukman01808ca2005-04-21 21:13:18 +00001255
Chris Lattnerd934c702004-04-02 20:23:17 +00001256 // While we are analyzing this PHI node, handle its value symbolically.
1257 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1258 assert(Scalars.find(PN) == Scalars.end() &&
1259 "PHI node already processed?");
1260 Scalars.insert(std::make_pair(PN, SymbolicName));
1261
1262 // Using this symbolic name for the PHI, analyze the value coming around
1263 // the back-edge.
1264 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1265
1266 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1267 // has a special value for the first iteration of the loop.
1268
1269 // If the value coming around the backedge is an add with the symbolic
1270 // value we just inserted, then we found a simple induction variable!
1271 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1272 // If there is a single occurrence of the symbolic value, replace it
1273 // with a recurrence.
1274 unsigned FoundIndex = Add->getNumOperands();
1275 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1276 if (Add->getOperand(i) == SymbolicName)
1277 if (FoundIndex == e) {
1278 FoundIndex = i;
1279 break;
1280 }
1281
1282 if (FoundIndex != Add->getNumOperands()) {
1283 // Create an add with everything but the specified operand.
1284 std::vector<SCEVHandle> Ops;
1285 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1286 if (i != FoundIndex)
1287 Ops.push_back(Add->getOperand(i));
1288 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1289
1290 // This is not a valid addrec if the step amount is varying each
1291 // loop iteration, but is not itself an addrec in this loop.
1292 if (Accum->isLoopInvariant(L) ||
1293 (isa<SCEVAddRecExpr>(Accum) &&
1294 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1295 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1296 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1297
1298 // Okay, for the entire analysis of this edge we assumed the PHI
1299 // to be symbolic. We now need to go back and update all of the
1300 // entries for the scalars that use the PHI (except for the PHI
1301 // itself) to use the new analyzed value instead of the "symbolic"
1302 // value.
Chris Lattner7b0fbe72005-02-13 04:37:18 +00001303 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00001304 return PHISCEV;
1305 }
1306 }
1307 }
1308
1309 return SymbolicName;
1310 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001311
Chris Lattnerd934c702004-04-02 20:23:17 +00001312 // If it's not a loop phi, we can't handle it yet.
1313 return SCEVUnknown::get(PN);
1314}
1315
1316/// createNodeForCast - Handle the various forms of casts that we support.
1317///
1318SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1319 const Type *SrcTy = CI->getOperand(0)->getType();
1320 const Type *DestTy = CI->getType();
Misha Brukman01808ca2005-04-21 21:13:18 +00001321
Chris Lattnerd934c702004-04-02 20:23:17 +00001322 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1323 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1324 return getSCEV(CI->getOperand(0));
Misha Brukman01808ca2005-04-21 21:13:18 +00001325
Chris Lattnerd934c702004-04-02 20:23:17 +00001326 if (SrcTy->isInteger() && DestTy->isInteger()) {
1327 // Otherwise, if this is a truncating integer cast, we can represent this
1328 // cast.
1329 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1330 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1331 CI->getType()->getUnsignedVersion());
1332 if (SrcTy->isUnsigned() &&
1333 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1334 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1335 CI->getType()->getUnsignedVersion());
1336 }
1337
1338 // If this is an sign or zero extending cast and we can prove that the value
1339 // will never overflow, we could do similar transformations.
1340
1341 // Otherwise, we can't handle this cast!
1342 return SCEVUnknown::get(CI);
1343}
1344
1345
1346/// createSCEV - We know that there is no SCEV for the specified value.
1347/// Analyze the expression.
1348///
1349SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1350 if (Instruction *I = dyn_cast<Instruction>(V)) {
1351 switch (I->getOpcode()) {
1352 case Instruction::Add:
1353 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1354 getSCEV(I->getOperand(1)));
1355 case Instruction::Mul:
1356 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1357 getSCEV(I->getOperand(1)));
1358 case Instruction::Div:
Chris Lattner98e96042006-04-01 04:48:52 +00001359 if (V->getType()->isInteger() && V->getType()->isSigned())
1360 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
Chris Lattnerd934c702004-04-02 20:23:17 +00001361 getSCEV(I->getOperand(1)));
1362 break;
1363
1364 case Instruction::Sub:
Chris Lattneradb043c2005-03-09 05:34:41 +00001365 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1366 getSCEV(I->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001367
1368 case Instruction::Shl:
1369 // Turn shift left of a constant amount into a multiply.
1370 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1371 Constant *X = ConstantInt::get(V->getType(), 1);
1372 X = ConstantExpr::getShl(X, SA);
1373 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1374 }
1375 break;
1376
Chris Lattnerd934c702004-04-02 20:23:17 +00001377 case Instruction::Cast:
1378 return createNodeForCast(cast<CastInst>(I));
1379
1380 case Instruction::PHI:
1381 return createNodeForPHI(cast<PHINode>(I));
1382
1383 default: // We cannot analyze this expression.
1384 break;
1385 }
1386 }
1387
1388 return SCEVUnknown::get(V);
1389}
1390
1391
1392
1393//===----------------------------------------------------------------------===//
1394// Iteration Count Computation Code
1395//
1396
1397/// getIterationCount - If the specified loop has a predictable iteration
1398/// count, return it. Note that it is not valid to call this method on a
1399/// loop without a loop-invariant iteration count.
1400SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1401 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1402 if (I == IterationCounts.end()) {
1403 SCEVHandle ItCount = ComputeIterationCount(L);
1404 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1405 if (ItCount != UnknownValue) {
1406 assert(ItCount->isLoopInvariant(L) &&
1407 "Computed trip count isn't loop invariant for loop!");
1408 ++NumTripCountsComputed;
1409 } else if (isa<PHINode>(L->getHeader()->begin())) {
1410 // Only count loops that have phi nodes as not being computable.
1411 ++NumTripCountsNotComputed;
1412 }
1413 }
1414 return I->second;
1415}
1416
1417/// ComputeIterationCount - Compute the number of times the specified loop
1418/// will iterate.
1419SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1420 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00001421 std::vector<BasicBlock*> ExitBlocks;
1422 L->getExitBlocks(ExitBlocks);
1423 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattnerd934c702004-04-02 20:23:17 +00001424
1425 // Okay, there is one exit block. Try to find the condition that causes the
1426 // loop to be exited.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00001427 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00001428
1429 BasicBlock *ExitingBlock = 0;
1430 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1431 PI != E; ++PI)
1432 if (L->contains(*PI)) {
1433 if (ExitingBlock == 0)
1434 ExitingBlock = *PI;
1435 else
1436 return UnknownValue; // More than one block exiting!
1437 }
1438 assert(ExitingBlock && "No exits from loop, something is broken!");
1439
1440 // Okay, we've computed the exiting block. See what condition causes us to
1441 // exit.
1442 //
1443 // FIXME: we should be able to handle switch instructions (with a single exit)
1444 // FIXME: We should handle cast of int to bool as well
1445 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1446 if (ExitBr == 0) return UnknownValue;
1447 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1448 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner4021d1a2004-04-17 18:36:24 +00001449 if (ExitCond == 0) // Not a setcc
1450 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1451 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattnerd934c702004-04-02 20:23:17 +00001452
Chris Lattnerec901cc2004-10-12 01:49:27 +00001453 // If the condition was exit on true, convert the condition to exit on false.
1454 Instruction::BinaryOps Cond;
1455 if (ExitBr->getSuccessor(1) == ExitBlock)
1456 Cond = ExitCond->getOpcode();
1457 else
1458 Cond = ExitCond->getInverseCondition();
1459
1460 // Handle common loops like: for (X = "string"; *X; ++X)
1461 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1462 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1463 SCEVHandle ItCnt =
1464 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1465 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1466 }
1467
Chris Lattnerd934c702004-04-02 20:23:17 +00001468 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1469 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1470
1471 // Try to evaluate any dependencies out of the loop.
1472 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1473 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1474 Tmp = getSCEVAtScope(RHS, L);
1475 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1476
Chris Lattnerd934c702004-04-02 20:23:17 +00001477 // At this point, we would like to compute how many iterations of the loop the
1478 // predicate will return true for these inputs.
1479 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1480 // If there is a constant, force it into the RHS.
1481 std::swap(LHS, RHS);
1482 Cond = SetCondInst::getSwappedCondition(Cond);
1483 }
1484
1485 // FIXME: think about handling pointer comparisons! i.e.:
1486 // while (P != P+100) ++P;
1487
1488 // If we have a comparison of a chrec against a constant, try to use value
1489 // ranges to answer this query.
1490 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1491 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1492 if (AddRec->getLoop() == L) {
1493 // Form the comparison range using the constant of the correct type so
1494 // that the ConstantRange class knows to do a signed or unsigned
1495 // comparison.
1496 ConstantInt *CompVal = RHSC->getValue();
1497 const Type *RealTy = ExitCond->getOperand(0)->getType();
1498 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1499 if (CompVal) {
1500 // Form the constant range.
1501 ConstantRange CompRange(Cond, CompVal);
Misha Brukman01808ca2005-04-21 21:13:18 +00001502
Chris Lattnerd934c702004-04-02 20:23:17 +00001503 // Now that we have it, if it's signed, convert it to an unsigned
1504 // range.
1505 if (CompRange.getLower()->getType()->isSigned()) {
1506 const Type *NewTy = RHSC->getValue()->getType();
1507 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1508 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1509 CompRange = ConstantRange(NewL, NewU);
1510 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001511
Chris Lattnerd934c702004-04-02 20:23:17 +00001512 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1513 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1514 }
1515 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001516
Chris Lattnerd934c702004-04-02 20:23:17 +00001517 switch (Cond) {
1518 case Instruction::SetNE: // while (X != Y)
1519 // Convert to: while (X-Y != 0)
Chris Lattner4021d1a2004-04-17 18:36:24 +00001520 if (LHS->getType()->isInteger()) {
Chris Lattneradb043c2005-03-09 05:34:41 +00001521 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner4021d1a2004-04-17 18:36:24 +00001522 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1523 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001524 break;
1525 case Instruction::SetEQ:
1526 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner4021d1a2004-04-17 18:36:24 +00001527 if (LHS->getType()->isInteger()) {
Chris Lattneradb043c2005-03-09 05:34:41 +00001528 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner4021d1a2004-04-17 18:36:24 +00001529 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1530 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001531 break;
Chris Lattner587a75b2005-08-15 23:33:51 +00001532 case Instruction::SetLT:
1533 if (LHS->getType()->isInteger() &&
1534 ExitCond->getOperand(0)->getType()->isSigned()) {
1535 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1536 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1537 }
1538 break;
1539 case Instruction::SetGT:
1540 if (LHS->getType()->isInteger() &&
1541 ExitCond->getOperand(0)->getType()->isSigned()) {
1542 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1543 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1544 }
1545 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00001546 default:
Chris Lattner09169212004-04-02 20:26:46 +00001547#if 0
Chris Lattnerd934c702004-04-02 20:23:17 +00001548 std::cerr << "ComputeIterationCount ";
1549 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1550 std::cerr << "[unsigned] ";
1551 std::cerr << *LHS << " "
1552 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00001553#endif
Chris Lattner0defaa12004-04-03 00:43:03 +00001554 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00001555 }
Chris Lattner4021d1a2004-04-17 18:36:24 +00001556
1557 return ComputeIterationCountExhaustively(L, ExitCond,
1558 ExitBr->getSuccessor(0) == ExitBlock);
1559}
1560
Chris Lattnerec901cc2004-10-12 01:49:27 +00001561static ConstantInt *
1562EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1563 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1564 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1565 assert(isa<SCEVConstant>(Val) &&
1566 "Evaluation of SCEV at constant didn't fold correctly?");
1567 return cast<SCEVConstant>(Val)->getValue();
1568}
1569
1570/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1571/// and a GEP expression (missing the pointer index) indexing into it, return
1572/// the addressed element of the initializer or null if the index expression is
1573/// invalid.
1574static Constant *
Misha Brukman01808ca2005-04-21 21:13:18 +00001575GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattnerec901cc2004-10-12 01:49:27 +00001576 const std::vector<ConstantInt*> &Indices) {
1577 Constant *Init = GV->getInitializer();
1578 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1579 uint64_t Idx = Indices[i]->getRawValue();
1580 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1581 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1582 Init = cast<Constant>(CS->getOperand(Idx));
1583 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1584 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1585 Init = cast<Constant>(CA->getOperand(Idx));
1586 } else if (isa<ConstantAggregateZero>(Init)) {
1587 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1588 assert(Idx < STy->getNumElements() && "Bad struct index!");
1589 Init = Constant::getNullValue(STy->getElementType(Idx));
1590 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1591 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1592 Init = Constant::getNullValue(ATy->getElementType());
1593 } else {
1594 assert(0 && "Unknown constant aggregate type!");
1595 }
1596 return 0;
1597 } else {
1598 return 0; // Unknown initializer type
1599 }
1600 }
1601 return Init;
1602}
1603
1604/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1605/// 'setcc load X, cst', try to se if we can compute the trip count.
1606SCEVHandle ScalarEvolutionsImpl::
Misha Brukman01808ca2005-04-21 21:13:18 +00001607ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattnerec901cc2004-10-12 01:49:27 +00001608 const Loop *L, unsigned SetCCOpcode) {
1609 if (LI->isVolatile()) return UnknownValue;
1610
1611 // Check to see if the loaded pointer is a getelementptr of a global.
1612 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1613 if (!GEP) return UnknownValue;
1614
1615 // Make sure that it is really a constant global we are gepping, with an
1616 // initializer, and make sure the first IDX is really 0.
1617 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1618 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1619 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1620 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1621 return UnknownValue;
1622
1623 // Okay, we allow one non-constant index into the GEP instruction.
1624 Value *VarIdx = 0;
1625 std::vector<ConstantInt*> Indexes;
1626 unsigned VarIdxNum = 0;
1627 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1628 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1629 Indexes.push_back(CI);
1630 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1631 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1632 VarIdx = GEP->getOperand(i);
1633 VarIdxNum = i-2;
1634 Indexes.push_back(0);
1635 }
1636
1637 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1638 // Check to see if X is a loop variant variable value now.
1639 SCEVHandle Idx = getSCEV(VarIdx);
1640 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1641 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1642
1643 // We can only recognize very limited forms of loop index expressions, in
1644 // particular, only affine AddRec's like {C1,+,C2}.
1645 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1646 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1647 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1648 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1649 return UnknownValue;
1650
1651 unsigned MaxSteps = MaxBruteForceIterations;
1652 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1653 ConstantUInt *ItCst =
1654 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1655 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1656
1657 // Form the GEP offset.
1658 Indexes[VarIdxNum] = Val;
1659
1660 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1661 if (Result == 0) break; // Cannot compute!
1662
1663 // Evaluate the condition for this iteration.
1664 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1665 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1666 if (Result == ConstantBool::False) {
1667#if 0
1668 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1669 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1670 << "***\n";
1671#endif
1672 ++NumArrayLenItCounts;
1673 return SCEVConstant::get(ItCst); // Found terminating iteration!
1674 }
1675 }
1676 return UnknownValue;
1677}
1678
1679
Chris Lattnerdd730472004-04-17 22:58:41 +00001680/// CanConstantFold - Return true if we can constant fold an instruction of the
1681/// specified type, assuming that all operands were constants.
1682static bool CanConstantFold(const Instruction *I) {
1683 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1684 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1685 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00001686
Chris Lattnerdd730472004-04-17 22:58:41 +00001687 if (const CallInst *CI = dyn_cast<CallInst>(I))
1688 if (const Function *F = CI->getCalledFunction())
1689 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1690 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00001691}
1692
Chris Lattnerdd730472004-04-17 22:58:41 +00001693/// ConstantFold - Constant fold an instruction of the specified type with the
1694/// specified constant operands. This function may modify the operands vector.
1695static Constant *ConstantFold(const Instruction *I,
1696 std::vector<Constant*> &Operands) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00001697 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1698 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1699
1700 switch (I->getOpcode()) {
1701 case Instruction::Cast:
1702 return ConstantExpr::getCast(Operands[0], I->getType());
1703 case Instruction::Select:
1704 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1705 case Instruction::Call:
Reid Spencer30d69a52004-07-18 00:18:30 +00001706 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00001707 Operands.erase(Operands.begin());
Reid Spencer30d69a52004-07-18 00:18:30 +00001708 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner4021d1a2004-04-17 18:36:24 +00001709 }
1710
1711 return 0;
1712 case Instruction::GetElementPtr:
1713 Constant *Base = Operands[0];
1714 Operands.erase(Operands.begin());
1715 return ConstantExpr::getGetElementPtr(Base, Operands);
1716 }
1717 return 0;
1718}
1719
1720
Chris Lattnerdd730472004-04-17 22:58:41 +00001721/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1722/// in the loop that V is derived from. We allow arbitrary operations along the
1723/// way, but the operands of an operation must either be constants or a value
1724/// derived from a constant PHI. If this expression does not fit with these
1725/// constraints, return null.
1726static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1727 // If this is not an instruction, or if this is an instruction outside of the
1728 // loop, it can't be derived from a loop PHI.
1729 Instruction *I = dyn_cast<Instruction>(V);
1730 if (I == 0 || !L->contains(I->getParent())) return 0;
1731
1732 if (PHINode *PN = dyn_cast<PHINode>(I))
1733 if (L->getHeader() == I->getParent())
1734 return PN;
1735 else
1736 // We don't currently keep track of the control flow needed to evaluate
1737 // PHIs, so we cannot handle PHIs inside of loops.
1738 return 0;
1739
1740 // If we won't be able to constant fold this expression even if the operands
1741 // are constants, return early.
1742 if (!CanConstantFold(I)) return 0;
Misha Brukman01808ca2005-04-21 21:13:18 +00001743
Chris Lattnerdd730472004-04-17 22:58:41 +00001744 // Otherwise, we can evaluate this instruction if all of its operands are
1745 // constant or derived from a PHI node themselves.
1746 PHINode *PHI = 0;
1747 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1748 if (!(isa<Constant>(I->getOperand(Op)) ||
1749 isa<GlobalValue>(I->getOperand(Op)))) {
1750 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1751 if (P == 0) return 0; // Not evolving from PHI
1752 if (PHI == 0)
1753 PHI = P;
1754 else if (PHI != P)
1755 return 0; // Evolving from multiple different PHIs.
1756 }
1757
1758 // This is a expression evolving from a constant PHI!
1759 return PHI;
1760}
1761
1762/// EvaluateExpression - Given an expression that passes the
1763/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1764/// in the loop has the value PHIVal. If we can't fold this expression for some
1765/// reason, return null.
1766static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1767 if (isa<PHINode>(V)) return PHIVal;
Chris Lattnerdd730472004-04-17 22:58:41 +00001768 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencer30d69a52004-07-18 00:18:30 +00001769 return GV;
1770 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattnerdd730472004-04-17 22:58:41 +00001771 Instruction *I = cast<Instruction>(V);
1772
1773 std::vector<Constant*> Operands;
1774 Operands.resize(I->getNumOperands());
1775
1776 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1777 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1778 if (Operands[i] == 0) return 0;
1779 }
1780
1781 return ConstantFold(I, Operands);
1782}
1783
1784/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1785/// in the header of its containing loop, we know the loop executes a
1786/// constant number of times, and the PHI node is just a recurrence
1787/// involving constants, fold it.
1788Constant *ScalarEvolutionsImpl::
1789getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1790 std::map<PHINode*, Constant*>::iterator I =
1791 ConstantEvolutionLoopExitValue.find(PN);
1792 if (I != ConstantEvolutionLoopExitValue.end())
1793 return I->second;
1794
Misha Brukman01808ca2005-04-21 21:13:18 +00001795 if (Its > MaxBruteForceIterations)
Chris Lattnerdd730472004-04-17 22:58:41 +00001796 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1797
1798 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1799
1800 // Since the loop is canonicalized, the PHI node must have two entries. One
1801 // entry must be a constant (coming in from outside of the loop), and the
1802 // second must be derived from the same PHI.
1803 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1804 Constant *StartCST =
1805 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1806 if (StartCST == 0)
1807 return RetVal = 0; // Must be a constant.
1808
1809 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1810 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1811 if (PN2 != PN)
1812 return RetVal = 0; // Not derived from same PHI.
1813
1814 // Execute the loop symbolically to determine the exit value.
1815 unsigned IterationNum = 0;
1816 unsigned NumIterations = Its;
1817 if (NumIterations != Its)
1818 return RetVal = 0; // More than 2^32 iterations??
1819
1820 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1821 if (IterationNum == NumIterations)
1822 return RetVal = PHIVal; // Got exit value!
1823
1824 // Compute the value of the PHI node for the next iteration.
1825 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1826 if (NextPHI == PHIVal)
1827 return RetVal = NextPHI; // Stopped evolving!
1828 if (NextPHI == 0)
1829 return 0; // Couldn't evaluate!
1830 PHIVal = NextPHI;
1831 }
1832}
1833
Chris Lattner4021d1a2004-04-17 18:36:24 +00001834/// ComputeIterationCountExhaustively - If the trip is known to execute a
1835/// constant number of times (the condition evolves only from constants),
1836/// try to evaluate a few iterations of the loop until we get the exit
1837/// condition gets a value of ExitWhen (true or false). If we cannot
1838/// evaluate the trip count of the loop, return UnknownValue.
1839SCEVHandle ScalarEvolutionsImpl::
1840ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1841 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1842 if (PN == 0) return UnknownValue;
1843
1844 // Since the loop is canonicalized, the PHI node must have two entries. One
1845 // entry must be a constant (coming in from outside of the loop), and the
1846 // second must be derived from the same PHI.
1847 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1848 Constant *StartCST =
1849 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1850 if (StartCST == 0) return UnknownValue; // Must be a constant.
1851
1852 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1853 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1854 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1855
1856 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1857 // the loop symbolically to determine when the condition gets a value of
1858 // "ExitWhen".
1859 unsigned IterationNum = 0;
1860 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1861 for (Constant *PHIVal = StartCST;
1862 IterationNum != MaxIterations; ++IterationNum) {
1863 ConstantBool *CondVal =
1864 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1865 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattnerdd730472004-04-17 22:58:41 +00001866
Chris Lattner4021d1a2004-04-17 18:36:24 +00001867 if (CondVal->getValue() == ExitWhen) {
Chris Lattnerdd730472004-04-17 22:58:41 +00001868 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner4021d1a2004-04-17 18:36:24 +00001869 ++NumBruteForceTripCountsComputed;
1870 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1871 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001872
Chris Lattnerdd730472004-04-17 22:58:41 +00001873 // Compute the value of the PHI node for the next iteration.
1874 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1875 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner4021d1a2004-04-17 18:36:24 +00001876 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattnerdd730472004-04-17 22:58:41 +00001877 PHIVal = NextPHI;
Chris Lattner4021d1a2004-04-17 18:36:24 +00001878 }
1879
1880 // Too many iterations were needed to evaluate.
Chris Lattnerd934c702004-04-02 20:23:17 +00001881 return UnknownValue;
1882}
1883
1884/// getSCEVAtScope - Compute the value of the specified expression within the
1885/// indicated loop (which may be null to indicate in no loop). If the
1886/// expression cannot be evaluated, return UnknownValue.
1887SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1888 // FIXME: this should be turned into a virtual method on SCEV!
1889
Chris Lattnerdd730472004-04-17 22:58:41 +00001890 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00001891
Chris Lattnerdd730472004-04-17 22:58:41 +00001892 // If this instruction is evolves from a constant-evolving PHI, compute the
1893 // exit value from the loop without using SCEVs.
1894 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1895 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1896 const Loop *LI = this->LI[I->getParent()];
1897 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1898 if (PHINode *PN = dyn_cast<PHINode>(I))
1899 if (PN->getParent() == LI->getHeader()) {
1900 // Okay, there is no closed form solution for the PHI node. Check
1901 // to see if the loop that contains it has a known iteration count.
1902 // If so, we may be able to force computation of the exit value.
1903 SCEVHandle IterationCount = getIterationCount(LI);
1904 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1905 // Okay, we know how many times the containing loop executes. If
1906 // this is a constant evolving PHI node, get the final value at
1907 // the specified iteration number.
1908 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1909 ICC->getValue()->getRawValue(),
1910 LI);
1911 if (RV) return SCEVUnknown::get(RV);
1912 }
1913 }
1914
1915 // Okay, this is a some expression that we cannot symbolically evaluate
1916 // into a SCEV. Check to see if it's possible to symbolically evaluate
1917 // the arguments into constants, and if see, try to constant propagate the
1918 // result. This is particularly useful for computing loop exit values.
1919 if (CanConstantFold(I)) {
1920 std::vector<Constant*> Operands;
1921 Operands.reserve(I->getNumOperands());
1922 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1923 Value *Op = I->getOperand(i);
1924 if (Constant *C = dyn_cast<Constant>(Op)) {
1925 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00001926 } else {
1927 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1928 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1929 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1930 Op->getType()));
1931 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1932 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1933 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1934 else
1935 return V;
1936 } else {
1937 return V;
1938 }
1939 }
1940 }
1941 return SCEVUnknown::get(ConstantFold(I, Operands));
1942 }
1943 }
1944
1945 // This is some other type of SCEVUnknown, just return it.
1946 return V;
1947 }
1948
Chris Lattnerd934c702004-04-02 20:23:17 +00001949 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1950 // Avoid performing the look-up in the common case where the specified
1951 // expression has no loop-variant portions.
1952 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1953 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1954 if (OpAtScope != Comm->getOperand(i)) {
1955 if (OpAtScope == UnknownValue) return UnknownValue;
1956 // Okay, at least one of these operands is loop variant but might be
1957 // foldable. Build a new instance of the folded commutative expression.
Chris Lattnerdd730472004-04-17 22:58:41 +00001958 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00001959 NewOps.push_back(OpAtScope);
1960
1961 for (++i; i != e; ++i) {
1962 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1963 if (OpAtScope == UnknownValue) return UnknownValue;
1964 NewOps.push_back(OpAtScope);
1965 }
1966 if (isa<SCEVAddExpr>(Comm))
1967 return SCEVAddExpr::get(NewOps);
1968 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1969 return SCEVMulExpr::get(NewOps);
1970 }
1971 }
1972 // If we got here, all operands are loop invariant.
1973 return Comm;
1974 }
1975
Chris Lattner98e96042006-04-01 04:48:52 +00001976 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
1977 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00001978 if (LHS == UnknownValue) return LHS;
Chris Lattner98e96042006-04-01 04:48:52 +00001979 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00001980 if (RHS == UnknownValue) return RHS;
Chris Lattner98e96042006-04-01 04:48:52 +00001981 if (LHS == Div->getLHS() && RHS == Div->getRHS())
1982 return Div; // must be loop invariant
1983 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00001984 }
1985
1986 // If this is a loop recurrence for a loop that does not contain L, then we
1987 // are dealing with the final value computed by the loop.
1988 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1989 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1990 // To evaluate this recurrence, we need to know how many times the AddRec
1991 // loop iterates. Compute this now.
1992 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1993 if (IterationCount == UnknownValue) return UnknownValue;
1994 IterationCount = getTruncateOrZeroExtend(IterationCount,
1995 AddRec->getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00001996
Chris Lattnerd934c702004-04-02 20:23:17 +00001997 // If the value is affine, simplify the expression evaluation to just
1998 // Start + Step*IterationCount.
1999 if (AddRec->isAffine())
2000 return SCEVAddExpr::get(AddRec->getStart(),
2001 SCEVMulExpr::get(IterationCount,
2002 AddRec->getOperand(1)));
2003
2004 // Otherwise, evaluate it the hard way.
2005 return AddRec->evaluateAtIteration(IterationCount);
2006 }
2007 return UnknownValue;
2008 }
2009
2010 //assert(0 && "Unknown SCEV type!");
2011 return UnknownValue;
2012}
2013
2014
2015/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2016/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2017/// might be the same) or two SCEVCouldNotCompute objects.
2018///
2019static std::pair<SCEVHandle,SCEVHandle>
2020SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2021 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2022 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2023 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2024 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00002025
Chris Lattnerd934c702004-04-02 20:23:17 +00002026 // We currently can only solve this if the coefficients are constants.
2027 if (!L || !M || !N) {
2028 SCEV *CNC = new SCEVCouldNotCompute();
2029 return std::make_pair(CNC, CNC);
2030 }
2031
2032 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
Misha Brukman01808ca2005-04-21 21:13:18 +00002033
Chris Lattnerd934c702004-04-02 20:23:17 +00002034 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2035 Constant *C = L->getValue();
2036 // The B coefficient is M-N/2
2037 Constant *B = ConstantExpr::getSub(M->getValue(),
2038 ConstantExpr::getDiv(N->getValue(),
2039 Two));
2040 // The A coefficient is N/2
2041 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00002042
Chris Lattnerd934c702004-04-02 20:23:17 +00002043 // Compute the B^2-4ac term.
2044 Constant *SqrtTerm =
2045 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2046 ConstantExpr::getMul(A, C));
2047 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2048
2049 // Compute floor(sqrt(B^2-4ac))
2050 ConstantUInt *SqrtVal =
2051 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2052 SqrtTerm->getType()->getUnsignedVersion()));
2053 uint64_t SqrtValV = SqrtVal->getValue();
Chris Lattner43df5072004-10-25 18:40:08 +00002054 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002055 // The square root might not be precise for arbitrary 64-bit integer
2056 // values. Do some sanity checks to ensure it's correct.
2057 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2058 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2059 SCEV *CNC = new SCEVCouldNotCompute();
2060 return std::make_pair(CNC, CNC);
2061 }
2062
2063 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2064 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00002065
Chris Lattnerd934c702004-04-02 20:23:17 +00002066 Constant *NegB = ConstantExpr::getNeg(B);
2067 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00002068
Chris Lattnerd934c702004-04-02 20:23:17 +00002069 // The divisions must be performed as signed divisions.
2070 const Type *SignedTy = NegB->getType()->getSignedVersion();
2071 NegB = ConstantExpr::getCast(NegB, SignedTy);
2072 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2073 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
Misha Brukman01808ca2005-04-21 21:13:18 +00002074
Chris Lattnerd934c702004-04-02 20:23:17 +00002075 Constant *Solution1 =
2076 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2077 Constant *Solution2 =
2078 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2079 return std::make_pair(SCEVUnknown::get(Solution1),
2080 SCEVUnknown::get(Solution2));
2081}
2082
2083/// HowFarToZero - Return the number of times a backedge comparing the specified
2084/// value to zero will execute. If not computable, return UnknownValue
2085SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2086 // If the value is a constant
2087 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2088 // If the value is already zero, the branch will execute zero times.
2089 if (C->getValue()->isNullValue()) return C;
2090 return UnknownValue; // Otherwise it will loop infinitely.
2091 }
2092
2093 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2094 if (!AddRec || AddRec->getLoop() != L)
2095 return UnknownValue;
2096
2097 if (AddRec->isAffine()) {
2098 // If this is an affine expression the execution count of this branch is
2099 // equal to:
2100 //
2101 // (0 - Start/Step) iff Start % Step == 0
2102 //
2103 // Get the initial value for the loop.
2104 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner6faf3942004-10-11 04:07:27 +00002105 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002106 SCEVHandle Step = AddRec->getOperand(1);
2107
2108 Step = getSCEVAtScope(Step, L->getParentLoop());
2109
2110 // Figure out if Start % Step == 0.
2111 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2112 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2113 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattneradb043c2005-03-09 05:34:41 +00002114 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattnerd934c702004-04-02 20:23:17 +00002115 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2116 return Start; // 0 - Start/-1 == Start
2117
2118 // Check to see if Start is divisible by SC with no remainder.
2119 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2120 ConstantInt *StartCC = StartC->getValue();
2121 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2122 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2123 if (Rem->isNullValue()) {
2124 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2125 return SCEVUnknown::get(Result);
2126 }
2127 }
2128 }
2129 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2130 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2131 // the quadratic equation to solve it.
2132 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2133 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2134 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2135 if (R1) {
Chris Lattner09169212004-04-02 20:26:46 +00002136#if 0
Chris Lattnerd934c702004-04-02 20:23:17 +00002137 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2138 << " sol#2: " << *R2 << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00002139#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002140 // Pick the smallest positive root value.
2141 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2142 if (ConstantBool *CB =
2143 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2144 R2->getValue()))) {
2145 if (CB != ConstantBool::True)
2146 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00002147
Chris Lattnerd934c702004-04-02 20:23:17 +00002148 // We can only use this value if the chrec ends up with an exact zero
2149 // value at this index. When solving for "X*X != 5", for example, we
2150 // should not accept a root of 2.
2151 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2152 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2153 if (EvalVal->getValue()->isNullValue())
2154 return R1; // We found a quadratic root!
2155 }
2156 }
2157 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002158
Chris Lattnerd934c702004-04-02 20:23:17 +00002159 return UnknownValue;
2160}
2161
2162/// HowFarToNonZero - Return the number of times a backedge checking the
2163/// specified value for nonzero will execute. If not computable, return
2164/// UnknownValue
2165SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2166 // Loops that look like: while (X == 0) are very strange indeed. We don't
2167 // handle them yet except for the trivial case. This could be expanded in the
2168 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00002169
Chris Lattnerd934c702004-04-02 20:23:17 +00002170 // If the value is a constant, check to see if it is known to be non-zero
2171 // already. If so, the backedge will execute zero times.
2172 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2173 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2174 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2175 if (NonZero == ConstantBool::True)
2176 return getSCEV(Zero);
2177 return UnknownValue; // Otherwise it will loop infinitely.
2178 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002179
Chris Lattnerd934c702004-04-02 20:23:17 +00002180 // We could implement others, but I really doubt anyone writes loops like
2181 // this, and if they did, they would already be constant folded.
2182 return UnknownValue;
2183}
2184
Chris Lattner587a75b2005-08-15 23:33:51 +00002185/// HowManyLessThans - Return the number of times a backedge containing the
2186/// specified less-than comparison will execute. If not computable, return
2187/// UnknownValue.
2188SCEVHandle ScalarEvolutionsImpl::
2189HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2190 // Only handle: "ADDREC < LoopInvariant".
2191 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2192
2193 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2194 if (!AddRec || AddRec->getLoop() != L)
2195 return UnknownValue;
2196
2197 if (AddRec->isAffine()) {
2198 // FORNOW: We only support unit strides.
2199 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2200 if (AddRec->getOperand(1) != One)
2201 return UnknownValue;
2202
2203 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2204 // know that m is >= n on input to the loop. If it is, the condition return
2205 // true zero times. What we really should return, for full generality, is
2206 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2207 // canonical loop form: most do-loops will have a check that dominates the
2208 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2209 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2210
2211 // Search for the check.
2212 BasicBlock *Preheader = L->getLoopPreheader();
2213 BasicBlock *PreheaderDest = L->getHeader();
2214 if (Preheader == 0) return UnknownValue;
2215
2216 BranchInst *LoopEntryPredicate =
2217 dyn_cast<BranchInst>(Preheader->getTerminator());
2218 if (!LoopEntryPredicate) return UnknownValue;
2219
2220 // This might be a critical edge broken out. If the loop preheader ends in
2221 // an unconditional branch to the loop, check to see if the preheader has a
2222 // single predecessor, and if so, look for its terminator.
2223 while (LoopEntryPredicate->isUnconditional()) {
2224 PreheaderDest = Preheader;
2225 Preheader = Preheader->getSinglePredecessor();
2226 if (!Preheader) return UnknownValue; // Multiple preds.
2227
2228 LoopEntryPredicate =
2229 dyn_cast<BranchInst>(Preheader->getTerminator());
2230 if (!LoopEntryPredicate) return UnknownValue;
2231 }
2232
2233 // Now that we found a conditional branch that dominates the loop, check to
2234 // see if it is the comparison we are looking for.
2235 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2236 if (!SCI) return UnknownValue;
2237 Value *PreCondLHS = SCI->getOperand(0);
2238 Value *PreCondRHS = SCI->getOperand(1);
2239 Instruction::BinaryOps Cond;
2240 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2241 Cond = SCI->getOpcode();
2242 else
2243 Cond = SCI->getInverseCondition();
2244
2245 switch (Cond) {
2246 case Instruction::SetGT:
2247 std::swap(PreCondLHS, PreCondRHS);
2248 Cond = Instruction::SetLT;
2249 // Fall Through.
2250 case Instruction::SetLT:
2251 if (PreCondLHS->getType()->isInteger() &&
2252 PreCondLHS->getType()->isSigned()) {
2253 if (RHS != getSCEV(PreCondRHS))
2254 return UnknownValue; // Not a comparison against 'm'.
2255
2256 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2257 != getSCEV(PreCondLHS))
2258 return UnknownValue; // Not a comparison against 'n-1'.
2259 break;
2260 } else {
2261 return UnknownValue;
2262 }
2263 default: break;
2264 }
2265
2266 //std::cerr << "Computed Loop Trip Count as: " <<
2267 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2268 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2269 }
2270
2271 return UnknownValue;
2272}
2273
Chris Lattnerd934c702004-04-02 20:23:17 +00002274/// getNumIterationsInRange - Return the number of iterations of this loop that
2275/// produce values in the specified constant range. Another way of looking at
2276/// this is that it returns the first iteration number where the value is not in
2277/// the condition, thus computing the exit count. If the iteration count can't
2278/// be computed, an instance of SCEVCouldNotCompute is returned.
2279SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2280 if (Range.isFullSet()) // Infinite loop.
2281 return new SCEVCouldNotCompute();
2282
2283 // If the start is a non-zero constant, shift the range to simplify things.
2284 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2285 if (!SC->getValue()->isNullValue()) {
2286 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattner05ef97f2004-04-23 21:29:03 +00002287 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattnerd934c702004-04-02 20:23:17 +00002288 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2289 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2290 return ShiftedAddRec->getNumIterationsInRange(
2291 Range.subtract(SC->getValue()));
2292 // This is strange and shouldn't happen.
2293 return new SCEVCouldNotCompute();
2294 }
2295
2296 // The only time we can solve this is when we have all constant indices.
2297 // Otherwise, we cannot determine the overflow conditions.
2298 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2299 if (!isa<SCEVConstant>(getOperand(i)))
2300 return new SCEVCouldNotCompute();
2301
2302
2303 // Okay at this point we know that all elements of the chrec are constants and
2304 // that the start element is zero.
2305
2306 // First check to see if the range contains zero. If not, the first
2307 // iteration exits.
2308 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2309 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman01808ca2005-04-21 21:13:18 +00002310
Chris Lattnerd934c702004-04-02 20:23:17 +00002311 if (isAffine()) {
2312 // If this is an affine expression then we have this situation:
2313 // Solve {0,+,A} in Range === Ax in Range
2314
2315 // Since we know that zero is in the range, we know that the upper value of
2316 // the range must be the first possible exit value. Also note that we
2317 // already checked for a full range.
2318 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2319 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2320 ConstantInt *One = ConstantInt::get(getType(), 1);
2321
2322 // The exit value should be (Upper+A-1)/A.
2323 Constant *ExitValue = Upper;
2324 if (A != One) {
2325 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2326 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2327 }
2328 assert(isa<ConstantInt>(ExitValue) &&
2329 "Constant folding of integers not implemented?");
2330
2331 // Evaluate at the exit value. If we really did fall out of the valid
2332 // range, then we computed our trip count, otherwise wrap around or other
2333 // things must have happened.
2334 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2335 if (Range.contains(Val))
2336 return new SCEVCouldNotCompute(); // Something strange happened
2337
2338 // Ensure that the previous value is in the range. This is a sanity check.
2339 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2340 ConstantExpr::getSub(ExitValue, One))) &&
2341 "Linear scev computation is off in a bad way!");
2342 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2343 } else if (isQuadratic()) {
2344 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2345 // quadratic equation to solve it. To do this, we must frame our problem in
2346 // terms of figuring out when zero is crossed, instead of when
2347 // Range.getUpper() is crossed.
2348 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattneradb043c2005-03-09 05:34:41 +00002349 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattnerd934c702004-04-02 20:23:17 +00002350 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2351
2352 // Next, solve the constructed addrec
2353 std::pair<SCEVHandle,SCEVHandle> Roots =
2354 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2355 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2356 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2357 if (R1) {
2358 // Pick the smallest positive root value.
2359 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2360 if (ConstantBool *CB =
2361 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2362 R2->getValue()))) {
2363 if (CB != ConstantBool::True)
2364 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00002365
Chris Lattnerd934c702004-04-02 20:23:17 +00002366 // Make sure the root is not off by one. The returned iteration should
2367 // not be in the range, but the previous one should be. When solving
2368 // for "X*X < 5", for example, we should not return a root of 2.
2369 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2370 R1->getValue());
2371 if (Range.contains(R1Val)) {
2372 // The next iteration must be out of the range...
2373 Constant *NextVal =
2374 ConstantExpr::getAdd(R1->getValue(),
2375 ConstantInt::get(R1->getType(), 1));
Misha Brukman01808ca2005-04-21 21:13:18 +00002376
Chris Lattnerd934c702004-04-02 20:23:17 +00002377 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2378 if (!Range.contains(R1Val))
2379 return SCEVUnknown::get(NextVal);
2380 return new SCEVCouldNotCompute(); // Something strange happened
2381 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002382
Chris Lattnerd934c702004-04-02 20:23:17 +00002383 // If R1 was not in the range, then it is a good return value. Make
2384 // sure that R1-1 WAS in the range though, just in case.
2385 Constant *NextVal =
2386 ConstantExpr::getSub(R1->getValue(),
2387 ConstantInt::get(R1->getType(), 1));
2388 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2389 if (Range.contains(R1Val))
2390 return R1;
2391 return new SCEVCouldNotCompute(); // Something strange happened
2392 }
2393 }
2394 }
2395
2396 // Fallback, if this is a general polynomial, figure out the progression
2397 // through brute force: evaluate until we find an iteration that fails the
2398 // test. This is likely to be slow, but getting an accurate trip count is
2399 // incredibly important, we will be able to simplify the exit test a lot, and
2400 // we are almost guaranteed to get a trip count in this case.
2401 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2402 ConstantInt *One = ConstantInt::get(getType(), 1);
2403 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2404 do {
2405 ++NumBruteForceEvaluations;
2406 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2407 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2408 return new SCEVCouldNotCompute();
2409
2410 // Check to see if we found the value!
2411 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2412 return SCEVConstant::get(TestVal);
2413
2414 // Increment to test the next index.
2415 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2416 } while (TestVal != EndVal);
Misha Brukman01808ca2005-04-21 21:13:18 +00002417
Chris Lattnerd934c702004-04-02 20:23:17 +00002418 return new SCEVCouldNotCompute();
2419}
2420
2421
2422
2423//===----------------------------------------------------------------------===//
2424// ScalarEvolution Class Implementation
2425//===----------------------------------------------------------------------===//
2426
2427bool ScalarEvolution::runOnFunction(Function &F) {
2428 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2429 return false;
2430}
2431
2432void ScalarEvolution::releaseMemory() {
2433 delete (ScalarEvolutionsImpl*)Impl;
2434 Impl = 0;
2435}
2436
2437void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2438 AU.setPreservesAll();
Chris Lattnerd934c702004-04-02 20:23:17 +00002439 AU.addRequiredTransitive<LoopInfo>();
2440}
2441
2442SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2443 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2444}
2445
Chris Lattnerb310ac4a2005-08-09 23:36:33 +00002446/// hasSCEV - Return true if the SCEV for this value has already been
2447/// computed.
2448bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner35c0e2e2005-08-10 00:59:40 +00002449 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnerb310ac4a2005-08-09 23:36:33 +00002450}
2451
2452
2453/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2454/// the specified value.
2455void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2456 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2457}
2458
2459
Chris Lattnerd934c702004-04-02 20:23:17 +00002460SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2461 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2462}
2463
2464bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2465 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2466}
2467
2468SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2469 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2470}
2471
2472void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2473 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2474}
2475
Misha Brukman01808ca2005-04-21 21:13:18 +00002476static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00002477 const Loop *L) {
2478 // Print all inner loops first
2479 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2480 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00002481
Chris Lattnerd934c702004-04-02 20:23:17 +00002482 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00002483
2484 std::vector<BasicBlock*> ExitBlocks;
2485 L->getExitBlocks(ExitBlocks);
2486 if (ExitBlocks.size() != 1)
Chris Lattnerd934c702004-04-02 20:23:17 +00002487 std::cerr << "<multiple exits> ";
2488
2489 if (SE->hasLoopInvariantIterationCount(L)) {
2490 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2491 } else {
2492 std::cerr << "Unpredictable iteration count. ";
2493 }
2494
2495 std::cerr << "\n";
2496}
2497
Reid Spencer90839362004-12-07 04:03:45 +00002498void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00002499 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2500 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2501
2502 OS << "Classifying expressions for: " << F.getName() << "\n";
2503 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002504 if (I->getType()->isInteger()) {
2505 OS << *I;
Chris Lattnerd934c702004-04-02 20:23:17 +00002506 OS << " --> ";
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002507 SCEVHandle SV = getSCEV(&*I);
Chris Lattnerd934c702004-04-02 20:23:17 +00002508 SV->print(OS);
2509 OS << "\t\t";
Misha Brukman01808ca2005-04-21 21:13:18 +00002510
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002511 if ((*I).getType()->isIntegral()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002512 ConstantRange Bounds = SV->getValueRange();
2513 if (!Bounds.isFullSet())
2514 OS << "Bounds: " << Bounds << " ";
2515 }
2516
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002517 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002518 OS << "Exits: ";
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002519 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +00002520 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2521 OS << "<<Unknown>>";
2522 } else {
2523 OS << *ExitValue;
2524 }
2525 }
2526
2527
2528 OS << "\n";
2529 }
2530
2531 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2532 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2533 PrintLoopInfo(OS, this, *I);
2534}
2535