blob: f8b4ab9be133d4bf457c79644fe5b2f92f54b201 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-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 Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-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 Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-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 Lattner53e677a2004-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 Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000066#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-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 Spencer551ccae2004-09-01 22:55:40 +000074#include "llvm/Support/CommandLine.h"
75#include "llvm/ADT/Statistic.h"
Brian Gaekec5985172004-04-16 15:57:32 +000076#include <cmath>
Chris Lattner72382102006-01-22 23:19:18 +000077#include <iostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000078#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000079using namespace llvm;
80
81namespace {
82 RegisterAnalysis<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +000083 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +000084
85 Statistic<>
86 NumBruteForceEvaluations("scalar-evolution",
Chris Lattner673e02b2004-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 Lattner53e677a2004-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 Lattner7980fb92004-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 Lattnerbed21de2005-09-28 22:30:58 +0000104 cl::desc("Maximum number of iterations SCEV will "
105 "symbolically execute a constant derived loop"),
Chris Lattner7980fb92004-04-17 18:36:24 +0000106 cl::init(100));
Chris Lattner53e677a2004-04-02 20:23:17 +0000107}
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Chris Lattner53e677a2004-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 Brukmanbb2aff12004-04-05 19:00:46 +0000136 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000141 return 0;
Chris Lattner53e677a2004-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 Lattner4dc534c2005-02-13 04:37:18 +0000149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
151 const SCEVHandle &Conc) const {
152 return this;
153}
154
Chris Lattner53e677a2004-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 Lattner0a7f98c2004-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 Brukman2b37d7c2005-04-21 21:13:18 +0000168
Chris Lattner53e677a2004-04-02 20:23:17 +0000169
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000170SCEVConstant::~SCEVConstant() {
171 SCEVConstants.erase(V);
172}
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Chris Lattner0a7f98c2004-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 Brukman2b37d7c2005-04-21 21:13:18 +0000180
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000181 SCEVConstant *&R = SCEVConstants[V];
182 if (R == 0) R = new SCEVConstant(V);
183 return R;
184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000186ConstantRange SCEVConstant::getValueRange() const {
187 return ConstantRange(V);
188}
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000191
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000192void SCEVConstant::print(std::ostream &OS) const {
193 WriteAsOperand(OS, V, false);
194}
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Chris Lattner0a7f98c2004-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 Lattner53e677a2004-04-02 20:23:17 +0000200
Chris Lattner0a7f98c2004-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 Lattner53e677a2004-04-02 20:23:17 +0000209
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210SCEVTruncateExpr::~SCEVTruncateExpr() {
211 SCEVTruncates.erase(std::make_pair(Op, Ty));
212}
Chris Lattner53e677a2004-04-02 20:23:17 +0000213
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214ConstantRange SCEVTruncateExpr::getValueRange() const {
215 return getOperand()->getValueRange().truncate(getType());
216}
Chris Lattner53e677a2004-04-02 20:23:17 +0000217
Chris Lattner0a7f98c2004-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 Lattner2352fec2005-02-17 16:54:16 +0000229 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-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 Lattner4dc534c2005-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 Lattner60a05cc2006-04-01 04:48:52 +0000297// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000298// input. Don't use a SCEVHandle here, or else the object will never be
299// deleted!
Chris Lattner60a05cc2006-04-01 04:48:52 +0000300static std::map<std::pair<SCEV*, SCEV*>, SCEVSDivExpr*> SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000301
Chris Lattner60a05cc2006-04-01 04:48:52 +0000302SCEVSDivExpr::~SCEVSDivExpr() {
303 SCEVSDivs.erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000304}
305
Chris Lattner60a05cc2006-04-01 04:48:52 +0000306void SCEVSDivExpr::print(std::ostream &OS) const {
307 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000308}
309
Chris Lattner60a05cc2006-04-01 04:48:52 +0000310const Type *SCEVSDivExpr::getType() const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000311 const Type *Ty = LHS->getType();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000312 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattner0a7f98c2004-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 Lattner4dc534c2005-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 Brukman2b37d7c2005-04-21 21:13:18 +0000342
Chris Lattner4dc534c2005-02-13 04:37:18 +0000343 return get(NewOps, L);
344 }
345 }
346 return this;
347}
348
349
Chris Lattner0a7f98c2004-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 Lattnerff2006a2005-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 Lattner53e677a2004-04-02 20:23:17 +0000355}
356
357
Chris Lattner0a7f98c2004-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 Lattner53e677a2004-04-02 20:23:17 +0000364
Chris Lattner0a7f98c2004-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 Lattner53e677a2004-04-02 20:23:17 +0000369
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000370SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000371
Chris Lattner0a7f98c2004-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 Lattner53e677a2004-04-02 20:23:17 +0000379
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000380const Type *SCEVUnknown::getType() const {
381 return V->getType();
382}
Chris Lattner53e677a2004-04-02 20:23:17 +0000383
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000384void SCEVUnknown::print(std::ostream &OS) const {
385 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000386}
387
Chris Lattner8d741b82004-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 Lattner2d584522004-06-20 17:01:44 +0000430 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-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 Lattner541ad5e2004-06-20 20:32:16 +0000441 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000442 }
443 }
444 }
445}
446
Chris Lattner53e677a2004-04-02 20:23:17 +0000447
Chris Lattner53e677a2004-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 Lattnerb06432c2004-04-23 21:29:03 +0000455SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000456 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000457 if (Val == 0)
Chris Lattner53e677a2004-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 Lattnerbac5b462005-03-09 05:34:41 +0000486SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000487 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
488 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000489
Chris Lattnerb06432c2004-04-23 21:29:03 +0000490 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000491}
492
493/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
494///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000495SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000496 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000497 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000498}
499
500
Chris Lattner53e677a2004-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 Lattnerb06432c2004-04-23 21:29:03 +0000516 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000517
Chris Lattner53e677a2004-04-02 20:23:17 +0000518 SCEVHandle Result = V;
519 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000520 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000521 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-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 Lattner60a05cc2006-04-01 04:48:52 +0000543 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000544 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-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 Lattner627018b2004-04-07 16:16:11 +0000595 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000596
597 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000598 GroupByComplexity(Ops);
Chris Lattner53e677a2004-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 Lattner627018b2004-04-07 16:16:11 +0000604 assert(Idx < Ops.size());
Chris Lattner53e677a2004-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 Lattner7ffc07d2005-02-26 18:50:19 +0000612 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-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 Lattner627018b2004-04-07 16:16:11 +0000628 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000629
Chris Lattner53e677a2004-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 Lattnerb06432c2004-04-23 21:29:03 +0000638 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-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 Lattner6a1a78a2004-12-04 20:54:32 +0000678 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-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 Lattnerb06432c2004-04-23 21:29:03 +0000688 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-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 Brukman2b37d7c2005-04-21 21:13:18 +0000702
Chris Lattner53e677a2004-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 Lattner8d741b82004-06-20 06:23:15 +0000826 GroupByComplexity(Ops);
Chris Lattner53e677a2004-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 Lattner7ffc07d2005-02-26 18:50:19 +0000849 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-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 Brukman2b37d7c2005-04-21 21:13:18 +0000874
Chris Lattner53e677a2004-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 Lattner6a1a78a2004-12-04 20:54:32 +0000980 if (Result == 0)
981 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000982 return Result;
983}
984
Chris Lattner60a05cc2006-04-01 04:48:52 +0000985SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000986 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
987 if (RHSC->getValue()->equalsInt(1))
Chris Lattner60a05cc2006-04-01 04:48:52 +0000988 return LHS; // X /s 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000989 if (RHSC->getValue()->isAllOnesValue())
Chris Lattner60a05cc2006-04-01 04:48:52 +0000990 return SCEV::getNegativeSCEV(LHS); // X /s -1 --> -x
Chris Lattner53e677a2004-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 Lattner60a05cc2006-04-01 04:48:52 +0000995 if (LHSCV->getType()->isUnsigned())
Chris Lattner53e677a2004-04-02 20:23:17 +0000996 LHSCV = ConstantExpr::getCast(LHSCV,
Chris Lattner60a05cc2006-04-01 04:48:52 +0000997 LHSCV->getType()->getSignedVersion());
998 if (RHSCV->getType()->isUnsigned())
Chris Lattner53e677a2004-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 Lattner60a05cc2006-04-01 04:48:52 +00001006 SCEVSDivExpr *&Result = SCEVSDivs[std::make_pair(LHS, RHS)];
1007 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-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 Lattner0a7f98c2004-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 Lattner53e677a2004-04-02 20:23:17 +00001056
1057//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-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 Lattner3221ad02004-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 Brukman2b37d7c2005-04-21 21:13:18 +00001092
Chris Lattner53e677a2004-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 Lattnera0740fb2005-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 Lattner53e677a2004-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 Lattner4dc534c2005-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 Lattner53e677a2004-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 Lattner673e02b2004-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 Lattner7980fb92004-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 Lattner53e677a2004-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 Lattnerdb25de42005-08-15 23:33:51 +00001174 /// UnknownValue.
Chris Lattner53e677a2004-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 Lattnerdb25de42005-08-15 23:33:51 +00001179 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001180 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001181
Chris Lattnerdb25de42005-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 Lattner3221ad02004-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 Lattner53e677a2004-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 Lattner3221ad02004-04-17 22:58:41 +00001205 if (PHINode *PN = dyn_cast<PHINode>(I))
1206 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-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 Lattner4dc534c2005-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 Lattner53e677a2004-04-02 20:23:17 +00001228 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001229 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001230
Chris Lattner4dc534c2005-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 Lattner53e677a2004-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 Brukman2b37d7c2005-04-21 21:13:18 +00001255
Chris Lattner53e677a2004-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 Lattner4dc534c2005-02-13 04:37:18 +00001303 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001304 return PHISCEV;
1305 }
1306 }
1307 }
1308
1309 return SymbolicName;
1310 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001311
Chris Lattner53e677a2004-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 Brukman2b37d7c2005-04-21 21:13:18 +00001321
Chris Lattner53e677a2004-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 Brukman2b37d7c2005-04-21 21:13:18 +00001325
Chris Lattner53e677a2004-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 Lattner60a05cc2006-04-01 04:48:52 +00001359 if (V->getType()->isInteger() && V->getType()->isSigned())
1360 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
Chris Lattner53e677a2004-04-02 20:23:17 +00001361 getSCEV(I->getOperand(1)));
1362 break;
1363
1364 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001365 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1366 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-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
1377 case Instruction::Shr:
1378 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
Chris Lattner60a05cc2006-04-01 04:48:52 +00001379 if (V->getType()->isSigned()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001380 Constant *X = ConstantInt::get(V->getType(), 1);
1381 X = ConstantExpr::getShl(X, SA);
Chris Lattner60a05cc2006-04-01 04:48:52 +00001382 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
Chris Lattner53e677a2004-04-02 20:23:17 +00001383 }
1384 break;
1385
1386 case Instruction::Cast:
1387 return createNodeForCast(cast<CastInst>(I));
1388
1389 case Instruction::PHI:
1390 return createNodeForPHI(cast<PHINode>(I));
1391
1392 default: // We cannot analyze this expression.
1393 break;
1394 }
1395 }
1396
1397 return SCEVUnknown::get(V);
1398}
1399
1400
1401
1402//===----------------------------------------------------------------------===//
1403// Iteration Count Computation Code
1404//
1405
1406/// getIterationCount - If the specified loop has a predictable iteration
1407/// count, return it. Note that it is not valid to call this method on a
1408/// loop without a loop-invariant iteration count.
1409SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1410 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1411 if (I == IterationCounts.end()) {
1412 SCEVHandle ItCount = ComputeIterationCount(L);
1413 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1414 if (ItCount != UnknownValue) {
1415 assert(ItCount->isLoopInvariant(L) &&
1416 "Computed trip count isn't loop invariant for loop!");
1417 ++NumTripCountsComputed;
1418 } else if (isa<PHINode>(L->getHeader()->begin())) {
1419 // Only count loops that have phi nodes as not being computable.
1420 ++NumTripCountsNotComputed;
1421 }
1422 }
1423 return I->second;
1424}
1425
1426/// ComputeIterationCount - Compute the number of times the specified loop
1427/// will iterate.
1428SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1429 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001430 std::vector<BasicBlock*> ExitBlocks;
1431 L->getExitBlocks(ExitBlocks);
1432 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001433
1434 // Okay, there is one exit block. Try to find the condition that causes the
1435 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001436 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001437
1438 BasicBlock *ExitingBlock = 0;
1439 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1440 PI != E; ++PI)
1441 if (L->contains(*PI)) {
1442 if (ExitingBlock == 0)
1443 ExitingBlock = *PI;
1444 else
1445 return UnknownValue; // More than one block exiting!
1446 }
1447 assert(ExitingBlock && "No exits from loop, something is broken!");
1448
1449 // Okay, we've computed the exiting block. See what condition causes us to
1450 // exit.
1451 //
1452 // FIXME: we should be able to handle switch instructions (with a single exit)
1453 // FIXME: We should handle cast of int to bool as well
1454 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1455 if (ExitBr == 0) return UnknownValue;
1456 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1457 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001458 if (ExitCond == 0) // Not a setcc
1459 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1460 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001461
Chris Lattner673e02b2004-10-12 01:49:27 +00001462 // If the condition was exit on true, convert the condition to exit on false.
1463 Instruction::BinaryOps Cond;
1464 if (ExitBr->getSuccessor(1) == ExitBlock)
1465 Cond = ExitCond->getOpcode();
1466 else
1467 Cond = ExitCond->getInverseCondition();
1468
1469 // Handle common loops like: for (X = "string"; *X; ++X)
1470 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1471 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1472 SCEVHandle ItCnt =
1473 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1474 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1475 }
1476
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1478 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1479
1480 // Try to evaluate any dependencies out of the loop.
1481 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1482 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1483 Tmp = getSCEVAtScope(RHS, L);
1484 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1485
Chris Lattner53e677a2004-04-02 20:23:17 +00001486 // At this point, we would like to compute how many iterations of the loop the
1487 // predicate will return true for these inputs.
1488 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1489 // If there is a constant, force it into the RHS.
1490 std::swap(LHS, RHS);
1491 Cond = SetCondInst::getSwappedCondition(Cond);
1492 }
1493
1494 // FIXME: think about handling pointer comparisons! i.e.:
1495 // while (P != P+100) ++P;
1496
1497 // If we have a comparison of a chrec against a constant, try to use value
1498 // ranges to answer this query.
1499 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1500 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1501 if (AddRec->getLoop() == L) {
1502 // Form the comparison range using the constant of the correct type so
1503 // that the ConstantRange class knows to do a signed or unsigned
1504 // comparison.
1505 ConstantInt *CompVal = RHSC->getValue();
1506 const Type *RealTy = ExitCond->getOperand(0)->getType();
1507 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1508 if (CompVal) {
1509 // Form the constant range.
1510 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001511
Chris Lattner53e677a2004-04-02 20:23:17 +00001512 // Now that we have it, if it's signed, convert it to an unsigned
1513 // range.
1514 if (CompRange.getLower()->getType()->isSigned()) {
1515 const Type *NewTy = RHSC->getValue()->getType();
1516 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1517 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1518 CompRange = ConstantRange(NewL, NewU);
1519 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001520
Chris Lattner53e677a2004-04-02 20:23:17 +00001521 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1522 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1523 }
1524 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001525
Chris Lattner53e677a2004-04-02 20:23:17 +00001526 switch (Cond) {
1527 case Instruction::SetNE: // while (X != Y)
1528 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001529 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001530 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001531 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1532 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001533 break;
1534 case Instruction::SetEQ:
1535 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001536 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001537 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001538 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1539 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001540 break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001541 case Instruction::SetLT:
1542 if (LHS->getType()->isInteger() &&
1543 ExitCond->getOperand(0)->getType()->isSigned()) {
1544 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1545 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1546 }
1547 break;
1548 case Instruction::SetGT:
1549 if (LHS->getType()->isInteger() &&
1550 ExitCond->getOperand(0)->getType()->isSigned()) {
1551 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1552 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1553 }
1554 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001555 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001556#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00001557 std::cerr << "ComputeIterationCount ";
1558 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1559 std::cerr << "[unsigned] ";
1560 std::cerr << *LHS << " "
1561 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001562#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001563 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001564 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001565
1566 return ComputeIterationCountExhaustively(L, ExitCond,
1567 ExitBr->getSuccessor(0) == ExitBlock);
1568}
1569
Chris Lattner673e02b2004-10-12 01:49:27 +00001570static ConstantInt *
1571EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1572 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1573 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1574 assert(isa<SCEVConstant>(Val) &&
1575 "Evaluation of SCEV at constant didn't fold correctly?");
1576 return cast<SCEVConstant>(Val)->getValue();
1577}
1578
1579/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1580/// and a GEP expression (missing the pointer index) indexing into it, return
1581/// the addressed element of the initializer or null if the index expression is
1582/// invalid.
1583static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001584GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001585 const std::vector<ConstantInt*> &Indices) {
1586 Constant *Init = GV->getInitializer();
1587 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1588 uint64_t Idx = Indices[i]->getRawValue();
1589 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1590 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1591 Init = cast<Constant>(CS->getOperand(Idx));
1592 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1593 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1594 Init = cast<Constant>(CA->getOperand(Idx));
1595 } else if (isa<ConstantAggregateZero>(Init)) {
1596 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1597 assert(Idx < STy->getNumElements() && "Bad struct index!");
1598 Init = Constant::getNullValue(STy->getElementType(Idx));
1599 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1600 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1601 Init = Constant::getNullValue(ATy->getElementType());
1602 } else {
1603 assert(0 && "Unknown constant aggregate type!");
1604 }
1605 return 0;
1606 } else {
1607 return 0; // Unknown initializer type
1608 }
1609 }
1610 return Init;
1611}
1612
1613/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1614/// 'setcc load X, cst', try to se if we can compute the trip count.
1615SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001616ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattner673e02b2004-10-12 01:49:27 +00001617 const Loop *L, unsigned SetCCOpcode) {
1618 if (LI->isVolatile()) return UnknownValue;
1619
1620 // Check to see if the loaded pointer is a getelementptr of a global.
1621 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1622 if (!GEP) return UnknownValue;
1623
1624 // Make sure that it is really a constant global we are gepping, with an
1625 // initializer, and make sure the first IDX is really 0.
1626 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1627 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1628 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1629 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1630 return UnknownValue;
1631
1632 // Okay, we allow one non-constant index into the GEP instruction.
1633 Value *VarIdx = 0;
1634 std::vector<ConstantInt*> Indexes;
1635 unsigned VarIdxNum = 0;
1636 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1637 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1638 Indexes.push_back(CI);
1639 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1640 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1641 VarIdx = GEP->getOperand(i);
1642 VarIdxNum = i-2;
1643 Indexes.push_back(0);
1644 }
1645
1646 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1647 // Check to see if X is a loop variant variable value now.
1648 SCEVHandle Idx = getSCEV(VarIdx);
1649 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1650 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1651
1652 // We can only recognize very limited forms of loop index expressions, in
1653 // particular, only affine AddRec's like {C1,+,C2}.
1654 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1655 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1656 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1657 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1658 return UnknownValue;
1659
1660 unsigned MaxSteps = MaxBruteForceIterations;
1661 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1662 ConstantUInt *ItCst =
1663 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1664 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1665
1666 // Form the GEP offset.
1667 Indexes[VarIdxNum] = Val;
1668
1669 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1670 if (Result == 0) break; // Cannot compute!
1671
1672 // Evaluate the condition for this iteration.
1673 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1674 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1675 if (Result == ConstantBool::False) {
1676#if 0
1677 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1678 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1679 << "***\n";
1680#endif
1681 ++NumArrayLenItCounts;
1682 return SCEVConstant::get(ItCst); // Found terminating iteration!
1683 }
1684 }
1685 return UnknownValue;
1686}
1687
1688
Chris Lattner3221ad02004-04-17 22:58:41 +00001689/// CanConstantFold - Return true if we can constant fold an instruction of the
1690/// specified type, assuming that all operands were constants.
1691static bool CanConstantFold(const Instruction *I) {
1692 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1693 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1694 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001695
Chris Lattner3221ad02004-04-17 22:58:41 +00001696 if (const CallInst *CI = dyn_cast<CallInst>(I))
1697 if (const Function *F = CI->getCalledFunction())
1698 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1699 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001700}
1701
Chris Lattner3221ad02004-04-17 22:58:41 +00001702/// ConstantFold - Constant fold an instruction of the specified type with the
1703/// specified constant operands. This function may modify the operands vector.
1704static Constant *ConstantFold(const Instruction *I,
1705 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001706 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1707 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1708
1709 switch (I->getOpcode()) {
1710 case Instruction::Cast:
1711 return ConstantExpr::getCast(Operands[0], I->getType());
1712 case Instruction::Select:
1713 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1714 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001715 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001716 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001717 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001718 }
1719
1720 return 0;
1721 case Instruction::GetElementPtr:
1722 Constant *Base = Operands[0];
1723 Operands.erase(Operands.begin());
1724 return ConstantExpr::getGetElementPtr(Base, Operands);
1725 }
1726 return 0;
1727}
1728
1729
Chris Lattner3221ad02004-04-17 22:58:41 +00001730/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1731/// in the loop that V is derived from. We allow arbitrary operations along the
1732/// way, but the operands of an operation must either be constants or a value
1733/// derived from a constant PHI. If this expression does not fit with these
1734/// constraints, return null.
1735static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1736 // If this is not an instruction, or if this is an instruction outside of the
1737 // loop, it can't be derived from a loop PHI.
1738 Instruction *I = dyn_cast<Instruction>(V);
1739 if (I == 0 || !L->contains(I->getParent())) return 0;
1740
1741 if (PHINode *PN = dyn_cast<PHINode>(I))
1742 if (L->getHeader() == I->getParent())
1743 return PN;
1744 else
1745 // We don't currently keep track of the control flow needed to evaluate
1746 // PHIs, so we cannot handle PHIs inside of loops.
1747 return 0;
1748
1749 // If we won't be able to constant fold this expression even if the operands
1750 // are constants, return early.
1751 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001752
Chris Lattner3221ad02004-04-17 22:58:41 +00001753 // Otherwise, we can evaluate this instruction if all of its operands are
1754 // constant or derived from a PHI node themselves.
1755 PHINode *PHI = 0;
1756 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1757 if (!(isa<Constant>(I->getOperand(Op)) ||
1758 isa<GlobalValue>(I->getOperand(Op)))) {
1759 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1760 if (P == 0) return 0; // Not evolving from PHI
1761 if (PHI == 0)
1762 PHI = P;
1763 else if (PHI != P)
1764 return 0; // Evolving from multiple different PHIs.
1765 }
1766
1767 // This is a expression evolving from a constant PHI!
1768 return PHI;
1769}
1770
1771/// EvaluateExpression - Given an expression that passes the
1772/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1773/// in the loop has the value PHIVal. If we can't fold this expression for some
1774/// reason, return null.
1775static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1776 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001777 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001778 return GV;
1779 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001780 Instruction *I = cast<Instruction>(V);
1781
1782 std::vector<Constant*> Operands;
1783 Operands.resize(I->getNumOperands());
1784
1785 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1786 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1787 if (Operands[i] == 0) return 0;
1788 }
1789
1790 return ConstantFold(I, Operands);
1791}
1792
1793/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1794/// in the header of its containing loop, we know the loop executes a
1795/// constant number of times, and the PHI node is just a recurrence
1796/// involving constants, fold it.
1797Constant *ScalarEvolutionsImpl::
1798getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1799 std::map<PHINode*, Constant*>::iterator I =
1800 ConstantEvolutionLoopExitValue.find(PN);
1801 if (I != ConstantEvolutionLoopExitValue.end())
1802 return I->second;
1803
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001804 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001805 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1806
1807 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1808
1809 // Since the loop is canonicalized, the PHI node must have two entries. One
1810 // entry must be a constant (coming in from outside of the loop), and the
1811 // second must be derived from the same PHI.
1812 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1813 Constant *StartCST =
1814 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1815 if (StartCST == 0)
1816 return RetVal = 0; // Must be a constant.
1817
1818 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1819 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1820 if (PN2 != PN)
1821 return RetVal = 0; // Not derived from same PHI.
1822
1823 // Execute the loop symbolically to determine the exit value.
1824 unsigned IterationNum = 0;
1825 unsigned NumIterations = Its;
1826 if (NumIterations != Its)
1827 return RetVal = 0; // More than 2^32 iterations??
1828
1829 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1830 if (IterationNum == NumIterations)
1831 return RetVal = PHIVal; // Got exit value!
1832
1833 // Compute the value of the PHI node for the next iteration.
1834 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1835 if (NextPHI == PHIVal)
1836 return RetVal = NextPHI; // Stopped evolving!
1837 if (NextPHI == 0)
1838 return 0; // Couldn't evaluate!
1839 PHIVal = NextPHI;
1840 }
1841}
1842
Chris Lattner7980fb92004-04-17 18:36:24 +00001843/// ComputeIterationCountExhaustively - If the trip is known to execute a
1844/// constant number of times (the condition evolves only from constants),
1845/// try to evaluate a few iterations of the loop until we get the exit
1846/// condition gets a value of ExitWhen (true or false). If we cannot
1847/// evaluate the trip count of the loop, return UnknownValue.
1848SCEVHandle ScalarEvolutionsImpl::
1849ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1850 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1851 if (PN == 0) return UnknownValue;
1852
1853 // Since the loop is canonicalized, the PHI node must have two entries. One
1854 // entry must be a constant (coming in from outside of the loop), and the
1855 // second must be derived from the same PHI.
1856 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1857 Constant *StartCST =
1858 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1859 if (StartCST == 0) return UnknownValue; // Must be a constant.
1860
1861 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1862 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1863 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1864
1865 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1866 // the loop symbolically to determine when the condition gets a value of
1867 // "ExitWhen".
1868 unsigned IterationNum = 0;
1869 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1870 for (Constant *PHIVal = StartCST;
1871 IterationNum != MaxIterations; ++IterationNum) {
1872 ConstantBool *CondVal =
1873 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1874 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001875
Chris Lattner7980fb92004-04-17 18:36:24 +00001876 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001877 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001878 ++NumBruteForceTripCountsComputed;
1879 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1880 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001881
Chris Lattner3221ad02004-04-17 22:58:41 +00001882 // Compute the value of the PHI node for the next iteration.
1883 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1884 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001885 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001886 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001887 }
1888
1889 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001890 return UnknownValue;
1891}
1892
1893/// getSCEVAtScope - Compute the value of the specified expression within the
1894/// indicated loop (which may be null to indicate in no loop). If the
1895/// expression cannot be evaluated, return UnknownValue.
1896SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1897 // FIXME: this should be turned into a virtual method on SCEV!
1898
Chris Lattner3221ad02004-04-17 22:58:41 +00001899 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001900
Chris Lattner3221ad02004-04-17 22:58:41 +00001901 // If this instruction is evolves from a constant-evolving PHI, compute the
1902 // exit value from the loop without using SCEVs.
1903 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1904 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1905 const Loop *LI = this->LI[I->getParent()];
1906 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1907 if (PHINode *PN = dyn_cast<PHINode>(I))
1908 if (PN->getParent() == LI->getHeader()) {
1909 // Okay, there is no closed form solution for the PHI node. Check
1910 // to see if the loop that contains it has a known iteration count.
1911 // If so, we may be able to force computation of the exit value.
1912 SCEVHandle IterationCount = getIterationCount(LI);
1913 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1914 // Okay, we know how many times the containing loop executes. If
1915 // this is a constant evolving PHI node, get the final value at
1916 // the specified iteration number.
1917 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1918 ICC->getValue()->getRawValue(),
1919 LI);
1920 if (RV) return SCEVUnknown::get(RV);
1921 }
1922 }
1923
1924 // Okay, this is a some expression that we cannot symbolically evaluate
1925 // into a SCEV. Check to see if it's possible to symbolically evaluate
1926 // the arguments into constants, and if see, try to constant propagate the
1927 // result. This is particularly useful for computing loop exit values.
1928 if (CanConstantFold(I)) {
1929 std::vector<Constant*> Operands;
1930 Operands.reserve(I->getNumOperands());
1931 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1932 Value *Op = I->getOperand(i);
1933 if (Constant *C = dyn_cast<Constant>(Op)) {
1934 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001935 } else {
1936 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1937 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1938 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1939 Op->getType()));
1940 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1941 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1942 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1943 else
1944 return V;
1945 } else {
1946 return V;
1947 }
1948 }
1949 }
1950 return SCEVUnknown::get(ConstantFold(I, Operands));
1951 }
1952 }
1953
1954 // This is some other type of SCEVUnknown, just return it.
1955 return V;
1956 }
1957
Chris Lattner53e677a2004-04-02 20:23:17 +00001958 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1959 // Avoid performing the look-up in the common case where the specified
1960 // expression has no loop-variant portions.
1961 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1962 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1963 if (OpAtScope != Comm->getOperand(i)) {
1964 if (OpAtScope == UnknownValue) return UnknownValue;
1965 // Okay, at least one of these operands is loop variant but might be
1966 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00001967 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00001968 NewOps.push_back(OpAtScope);
1969
1970 for (++i; i != e; ++i) {
1971 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1972 if (OpAtScope == UnknownValue) return UnknownValue;
1973 NewOps.push_back(OpAtScope);
1974 }
1975 if (isa<SCEVAddExpr>(Comm))
1976 return SCEVAddExpr::get(NewOps);
1977 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1978 return SCEVMulExpr::get(NewOps);
1979 }
1980 }
1981 // If we got here, all operands are loop invariant.
1982 return Comm;
1983 }
1984
Chris Lattner60a05cc2006-04-01 04:48:52 +00001985 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
1986 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001987 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00001988 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001989 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00001990 if (LHS == Div->getLHS() && RHS == Div->getRHS())
1991 return Div; // must be loop invariant
1992 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001993 }
1994
1995 // If this is a loop recurrence for a loop that does not contain L, then we
1996 // are dealing with the final value computed by the loop.
1997 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1998 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1999 // To evaluate this recurrence, we need to know how many times the AddRec
2000 // loop iterates. Compute this now.
2001 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2002 if (IterationCount == UnknownValue) return UnknownValue;
2003 IterationCount = getTruncateOrZeroExtend(IterationCount,
2004 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002005
Chris Lattner53e677a2004-04-02 20:23:17 +00002006 // If the value is affine, simplify the expression evaluation to just
2007 // Start + Step*IterationCount.
2008 if (AddRec->isAffine())
2009 return SCEVAddExpr::get(AddRec->getStart(),
2010 SCEVMulExpr::get(IterationCount,
2011 AddRec->getOperand(1)));
2012
2013 // Otherwise, evaluate it the hard way.
2014 return AddRec->evaluateAtIteration(IterationCount);
2015 }
2016 return UnknownValue;
2017 }
2018
2019 //assert(0 && "Unknown SCEV type!");
2020 return UnknownValue;
2021}
2022
2023
2024/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2025/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2026/// might be the same) or two SCEVCouldNotCompute objects.
2027///
2028static std::pair<SCEVHandle,SCEVHandle>
2029SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2030 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2031 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2032 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2033 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002034
Chris Lattner53e677a2004-04-02 20:23:17 +00002035 // We currently can only solve this if the coefficients are constants.
2036 if (!L || !M || !N) {
2037 SCEV *CNC = new SCEVCouldNotCompute();
2038 return std::make_pair(CNC, CNC);
2039 }
2040
2041 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002042
Chris Lattner53e677a2004-04-02 20:23:17 +00002043 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2044 Constant *C = L->getValue();
2045 // The B coefficient is M-N/2
2046 Constant *B = ConstantExpr::getSub(M->getValue(),
2047 ConstantExpr::getDiv(N->getValue(),
2048 Two));
2049 // The A coefficient is N/2
2050 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002051
Chris Lattner53e677a2004-04-02 20:23:17 +00002052 // Compute the B^2-4ac term.
2053 Constant *SqrtTerm =
2054 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2055 ConstantExpr::getMul(A, C));
2056 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2057
2058 // Compute floor(sqrt(B^2-4ac))
2059 ConstantUInt *SqrtVal =
2060 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2061 SqrtTerm->getType()->getUnsignedVersion()));
2062 uint64_t SqrtValV = SqrtVal->getValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002063 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002064 // The square root might not be precise for arbitrary 64-bit integer
2065 // values. Do some sanity checks to ensure it's correct.
2066 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2067 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2068 SCEV *CNC = new SCEVCouldNotCompute();
2069 return std::make_pair(CNC, CNC);
2070 }
2071
2072 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2073 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002074
Chris Lattner53e677a2004-04-02 20:23:17 +00002075 Constant *NegB = ConstantExpr::getNeg(B);
2076 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002077
Chris Lattner53e677a2004-04-02 20:23:17 +00002078 // The divisions must be performed as signed divisions.
2079 const Type *SignedTy = NegB->getType()->getSignedVersion();
2080 NegB = ConstantExpr::getCast(NegB, SignedTy);
2081 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2082 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002083
Chris Lattner53e677a2004-04-02 20:23:17 +00002084 Constant *Solution1 =
2085 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2086 Constant *Solution2 =
2087 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2088 return std::make_pair(SCEVUnknown::get(Solution1),
2089 SCEVUnknown::get(Solution2));
2090}
2091
2092/// HowFarToZero - Return the number of times a backedge comparing the specified
2093/// value to zero will execute. If not computable, return UnknownValue
2094SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2095 // If the value is a constant
2096 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2097 // If the value is already zero, the branch will execute zero times.
2098 if (C->getValue()->isNullValue()) return C;
2099 return UnknownValue; // Otherwise it will loop infinitely.
2100 }
2101
2102 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2103 if (!AddRec || AddRec->getLoop() != L)
2104 return UnknownValue;
2105
2106 if (AddRec->isAffine()) {
2107 // If this is an affine expression the execution count of this branch is
2108 // equal to:
2109 //
2110 // (0 - Start/Step) iff Start % Step == 0
2111 //
2112 // Get the initial value for the loop.
2113 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002114 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002115 SCEVHandle Step = AddRec->getOperand(1);
2116
2117 Step = getSCEVAtScope(Step, L->getParentLoop());
2118
2119 // Figure out if Start % Step == 0.
2120 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2121 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2122 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002123 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002124 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2125 return Start; // 0 - Start/-1 == Start
2126
2127 // Check to see if Start is divisible by SC with no remainder.
2128 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2129 ConstantInt *StartCC = StartC->getValue();
2130 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2131 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2132 if (Rem->isNullValue()) {
2133 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2134 return SCEVUnknown::get(Result);
2135 }
2136 }
2137 }
2138 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2139 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2140 // the quadratic equation to solve it.
2141 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2142 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2143 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2144 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002145#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00002146 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2147 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002148#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002149 // Pick the smallest positive root value.
2150 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2151 if (ConstantBool *CB =
2152 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2153 R2->getValue()))) {
2154 if (CB != ConstantBool::True)
2155 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002156
Chris Lattner53e677a2004-04-02 20:23:17 +00002157 // We can only use this value if the chrec ends up with an exact zero
2158 // value at this index. When solving for "X*X != 5", for example, we
2159 // should not accept a root of 2.
2160 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2161 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2162 if (EvalVal->getValue()->isNullValue())
2163 return R1; // We found a quadratic root!
2164 }
2165 }
2166 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002167
Chris Lattner53e677a2004-04-02 20:23:17 +00002168 return UnknownValue;
2169}
2170
2171/// HowFarToNonZero - Return the number of times a backedge checking the
2172/// specified value for nonzero will execute. If not computable, return
2173/// UnknownValue
2174SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2175 // Loops that look like: while (X == 0) are very strange indeed. We don't
2176 // handle them yet except for the trivial case. This could be expanded in the
2177 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002178
Chris Lattner53e677a2004-04-02 20:23:17 +00002179 // If the value is a constant, check to see if it is known to be non-zero
2180 // already. If so, the backedge will execute zero times.
2181 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2182 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2183 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2184 if (NonZero == ConstantBool::True)
2185 return getSCEV(Zero);
2186 return UnknownValue; // Otherwise it will loop infinitely.
2187 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002188
Chris Lattner53e677a2004-04-02 20:23:17 +00002189 // We could implement others, but I really doubt anyone writes loops like
2190 // this, and if they did, they would already be constant folded.
2191 return UnknownValue;
2192}
2193
Chris Lattnerdb25de42005-08-15 23:33:51 +00002194/// HowManyLessThans - Return the number of times a backedge containing the
2195/// specified less-than comparison will execute. If not computable, return
2196/// UnknownValue.
2197SCEVHandle ScalarEvolutionsImpl::
2198HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2199 // Only handle: "ADDREC < LoopInvariant".
2200 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2201
2202 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2203 if (!AddRec || AddRec->getLoop() != L)
2204 return UnknownValue;
2205
2206 if (AddRec->isAffine()) {
2207 // FORNOW: We only support unit strides.
2208 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2209 if (AddRec->getOperand(1) != One)
2210 return UnknownValue;
2211
2212 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2213 // know that m is >= n on input to the loop. If it is, the condition return
2214 // true zero times. What we really should return, for full generality, is
2215 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2216 // canonical loop form: most do-loops will have a check that dominates the
2217 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2218 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2219
2220 // Search for the check.
2221 BasicBlock *Preheader = L->getLoopPreheader();
2222 BasicBlock *PreheaderDest = L->getHeader();
2223 if (Preheader == 0) return UnknownValue;
2224
2225 BranchInst *LoopEntryPredicate =
2226 dyn_cast<BranchInst>(Preheader->getTerminator());
2227 if (!LoopEntryPredicate) return UnknownValue;
2228
2229 // This might be a critical edge broken out. If the loop preheader ends in
2230 // an unconditional branch to the loop, check to see if the preheader has a
2231 // single predecessor, and if so, look for its terminator.
2232 while (LoopEntryPredicate->isUnconditional()) {
2233 PreheaderDest = Preheader;
2234 Preheader = Preheader->getSinglePredecessor();
2235 if (!Preheader) return UnknownValue; // Multiple preds.
2236
2237 LoopEntryPredicate =
2238 dyn_cast<BranchInst>(Preheader->getTerminator());
2239 if (!LoopEntryPredicate) return UnknownValue;
2240 }
2241
2242 // Now that we found a conditional branch that dominates the loop, check to
2243 // see if it is the comparison we are looking for.
2244 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2245 if (!SCI) return UnknownValue;
2246 Value *PreCondLHS = SCI->getOperand(0);
2247 Value *PreCondRHS = SCI->getOperand(1);
2248 Instruction::BinaryOps Cond;
2249 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2250 Cond = SCI->getOpcode();
2251 else
2252 Cond = SCI->getInverseCondition();
2253
2254 switch (Cond) {
2255 case Instruction::SetGT:
2256 std::swap(PreCondLHS, PreCondRHS);
2257 Cond = Instruction::SetLT;
2258 // Fall Through.
2259 case Instruction::SetLT:
2260 if (PreCondLHS->getType()->isInteger() &&
2261 PreCondLHS->getType()->isSigned()) {
2262 if (RHS != getSCEV(PreCondRHS))
2263 return UnknownValue; // Not a comparison against 'm'.
2264
2265 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2266 != getSCEV(PreCondLHS))
2267 return UnknownValue; // Not a comparison against 'n-1'.
2268 break;
2269 } else {
2270 return UnknownValue;
2271 }
2272 default: break;
2273 }
2274
2275 //std::cerr << "Computed Loop Trip Count as: " <<
2276 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2277 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2278 }
2279
2280 return UnknownValue;
2281}
2282
Chris Lattner53e677a2004-04-02 20:23:17 +00002283/// getNumIterationsInRange - Return the number of iterations of this loop that
2284/// produce values in the specified constant range. Another way of looking at
2285/// this is that it returns the first iteration number where the value is not in
2286/// the condition, thus computing the exit count. If the iteration count can't
2287/// be computed, an instance of SCEVCouldNotCompute is returned.
2288SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2289 if (Range.isFullSet()) // Infinite loop.
2290 return new SCEVCouldNotCompute();
2291
2292 // If the start is a non-zero constant, shift the range to simplify things.
2293 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2294 if (!SC->getValue()->isNullValue()) {
2295 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002296 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002297 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2298 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2299 return ShiftedAddRec->getNumIterationsInRange(
2300 Range.subtract(SC->getValue()));
2301 // This is strange and shouldn't happen.
2302 return new SCEVCouldNotCompute();
2303 }
2304
2305 // The only time we can solve this is when we have all constant indices.
2306 // Otherwise, we cannot determine the overflow conditions.
2307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2308 if (!isa<SCEVConstant>(getOperand(i)))
2309 return new SCEVCouldNotCompute();
2310
2311
2312 // Okay at this point we know that all elements of the chrec are constants and
2313 // that the start element is zero.
2314
2315 // First check to see if the range contains zero. If not, the first
2316 // iteration exits.
2317 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2318 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002319
Chris Lattner53e677a2004-04-02 20:23:17 +00002320 if (isAffine()) {
2321 // If this is an affine expression then we have this situation:
2322 // Solve {0,+,A} in Range === Ax in Range
2323
2324 // Since we know that zero is in the range, we know that the upper value of
2325 // the range must be the first possible exit value. Also note that we
2326 // already checked for a full range.
2327 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2328 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2329 ConstantInt *One = ConstantInt::get(getType(), 1);
2330
2331 // The exit value should be (Upper+A-1)/A.
2332 Constant *ExitValue = Upper;
2333 if (A != One) {
2334 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2335 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2336 }
2337 assert(isa<ConstantInt>(ExitValue) &&
2338 "Constant folding of integers not implemented?");
2339
2340 // Evaluate at the exit value. If we really did fall out of the valid
2341 // range, then we computed our trip count, otherwise wrap around or other
2342 // things must have happened.
2343 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2344 if (Range.contains(Val))
2345 return new SCEVCouldNotCompute(); // Something strange happened
2346
2347 // Ensure that the previous value is in the range. This is a sanity check.
2348 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2349 ConstantExpr::getSub(ExitValue, One))) &&
2350 "Linear scev computation is off in a bad way!");
2351 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2352 } else if (isQuadratic()) {
2353 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2354 // quadratic equation to solve it. To do this, we must frame our problem in
2355 // terms of figuring out when zero is crossed, instead of when
2356 // Range.getUpper() is crossed.
2357 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002358 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002359 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2360
2361 // Next, solve the constructed addrec
2362 std::pair<SCEVHandle,SCEVHandle> Roots =
2363 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2364 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2365 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2366 if (R1) {
2367 // Pick the smallest positive root value.
2368 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2369 if (ConstantBool *CB =
2370 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2371 R2->getValue()))) {
2372 if (CB != ConstantBool::True)
2373 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002374
Chris Lattner53e677a2004-04-02 20:23:17 +00002375 // Make sure the root is not off by one. The returned iteration should
2376 // not be in the range, but the previous one should be. When solving
2377 // for "X*X < 5", for example, we should not return a root of 2.
2378 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2379 R1->getValue());
2380 if (Range.contains(R1Val)) {
2381 // The next iteration must be out of the range...
2382 Constant *NextVal =
2383 ConstantExpr::getAdd(R1->getValue(),
2384 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002385
Chris Lattner53e677a2004-04-02 20:23:17 +00002386 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2387 if (!Range.contains(R1Val))
2388 return SCEVUnknown::get(NextVal);
2389 return new SCEVCouldNotCompute(); // Something strange happened
2390 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002391
Chris Lattner53e677a2004-04-02 20:23:17 +00002392 // If R1 was not in the range, then it is a good return value. Make
2393 // sure that R1-1 WAS in the range though, just in case.
2394 Constant *NextVal =
2395 ConstantExpr::getSub(R1->getValue(),
2396 ConstantInt::get(R1->getType(), 1));
2397 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2398 if (Range.contains(R1Val))
2399 return R1;
2400 return new SCEVCouldNotCompute(); // Something strange happened
2401 }
2402 }
2403 }
2404
2405 // Fallback, if this is a general polynomial, figure out the progression
2406 // through brute force: evaluate until we find an iteration that fails the
2407 // test. This is likely to be slow, but getting an accurate trip count is
2408 // incredibly important, we will be able to simplify the exit test a lot, and
2409 // we are almost guaranteed to get a trip count in this case.
2410 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2411 ConstantInt *One = ConstantInt::get(getType(), 1);
2412 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2413 do {
2414 ++NumBruteForceEvaluations;
2415 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2416 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2417 return new SCEVCouldNotCompute();
2418
2419 // Check to see if we found the value!
2420 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2421 return SCEVConstant::get(TestVal);
2422
2423 // Increment to test the next index.
2424 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2425 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002426
Chris Lattner53e677a2004-04-02 20:23:17 +00002427 return new SCEVCouldNotCompute();
2428}
2429
2430
2431
2432//===----------------------------------------------------------------------===//
2433// ScalarEvolution Class Implementation
2434//===----------------------------------------------------------------------===//
2435
2436bool ScalarEvolution::runOnFunction(Function &F) {
2437 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2438 return false;
2439}
2440
2441void ScalarEvolution::releaseMemory() {
2442 delete (ScalarEvolutionsImpl*)Impl;
2443 Impl = 0;
2444}
2445
2446void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2447 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002448 AU.addRequiredTransitive<LoopInfo>();
2449}
2450
2451SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2452 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2453}
2454
Chris Lattnera0740fb2005-08-09 23:36:33 +00002455/// hasSCEV - Return true if the SCEV for this value has already been
2456/// computed.
2457bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002458 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002459}
2460
2461
2462/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2463/// the specified value.
2464void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2465 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2466}
2467
2468
Chris Lattner53e677a2004-04-02 20:23:17 +00002469SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2470 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2471}
2472
2473bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2474 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2475}
2476
2477SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2478 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2479}
2480
2481void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2482 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2483}
2484
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002485static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002486 const Loop *L) {
2487 // Print all inner loops first
2488 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2489 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002490
Chris Lattner53e677a2004-04-02 20:23:17 +00002491 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002492
2493 std::vector<BasicBlock*> ExitBlocks;
2494 L->getExitBlocks(ExitBlocks);
2495 if (ExitBlocks.size() != 1)
Chris Lattner53e677a2004-04-02 20:23:17 +00002496 std::cerr << "<multiple exits> ";
2497
2498 if (SE->hasLoopInvariantIterationCount(L)) {
2499 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2500 } else {
2501 std::cerr << "Unpredictable iteration count. ";
2502 }
2503
2504 std::cerr << "\n";
2505}
2506
Reid Spencerce9653c2004-12-07 04:03:45 +00002507void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002508 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2509 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2510
2511 OS << "Classifying expressions for: " << F.getName() << "\n";
2512 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002513 if (I->getType()->isInteger()) {
2514 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002515 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002516 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002517 SV->print(OS);
2518 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002519
Chris Lattner6ffe5512004-04-27 15:13:33 +00002520 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002521 ConstantRange Bounds = SV->getValueRange();
2522 if (!Bounds.isFullSet())
2523 OS << "Bounds: " << Bounds << " ";
2524 }
2525
Chris Lattner6ffe5512004-04-27 15:13:33 +00002526 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002527 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002528 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002529 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2530 OS << "<<Unknown>>";
2531 } else {
2532 OS << *ExitValue;
2533 }
2534 }
2535
2536
2537 OS << "\n";
2538 }
2539
2540 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2541 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2542 PrintLoopInfo(OS, this, *I);
2543}
2544