blob: 2601277cd8c11be684b13bb9ad8eff416c5bf142 [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"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Analysis/LoopInfo.h"
68#include "llvm/Assembly/Writer.h"
69#include "llvm/Transforms/Scalar.h"
Chris Lattner7980fb92004-04-17 18:36:24 +000070#include "llvm/Transforms/Utils/Local.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000071#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>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000077#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000078using namespace llvm;
79
80namespace {
81 RegisterAnalysis<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +000082 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +000083
84 Statistic<>
85 NumBruteForceEvaluations("scalar-evolution",
Chris Lattner673e02b2004-10-12 01:49:27 +000086 "Number of brute force evaluations needed to "
87 "calculate high-order polynomial exit values");
88 Statistic<>
89 NumArrayLenItCounts("scalar-evolution",
90 "Number of trip counts computed with array length");
Chris Lattner53e677a2004-04-02 20:23:17 +000091 Statistic<>
92 NumTripCountsComputed("scalar-evolution",
93 "Number of loops with predictable loop counts");
94 Statistic<>
95 NumTripCountsNotComputed("scalar-evolution",
96 "Number of loops without predictable loop counts");
Chris Lattner7980fb92004-04-17 18:36:24 +000097 Statistic<>
98 NumBruteForceTripCountsComputed("scalar-evolution",
99 "Number of loops with trip counts computed by force");
100
101 cl::opt<unsigned>
102 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
103 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
104 cl::init(100));
Chris Lattner53e677a2004-04-02 20:23:17 +0000105}
106
107//===----------------------------------------------------------------------===//
108// SCEV class definitions
109//===----------------------------------------------------------------------===//
110
111//===----------------------------------------------------------------------===//
112// Implementation of the SCEV class.
113//
Chris Lattner53e677a2004-04-02 20:23:17 +0000114SCEV::~SCEV() {}
115void SCEV::dump() const {
116 print(std::cerr);
117}
118
119/// getValueRange - Return the tightest constant bounds that this value is
120/// known to have. This method is only valid on integer SCEV objects.
121ConstantRange SCEV::getValueRange() const {
122 const Type *Ty = getType();
123 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
124 Ty = Ty->getUnsignedVersion();
125 // Default to a full range if no better information is available.
126 return ConstantRange(getType());
127}
128
129
130SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
131
132bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
133 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000134 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000135}
136
137const Type *SCEVCouldNotCompute::getType() const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return false;
145}
146
Chris Lattner4dc534c2005-02-13 04:37:18 +0000147SCEVHandle SCEVCouldNotCompute::
148replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
149 const SCEVHandle &Conc) const {
150 return this;
151}
152
Chris Lattner53e677a2004-04-02 20:23:17 +0000153void SCEVCouldNotCompute::print(std::ostream &OS) const {
154 OS << "***COULDNOTCOMPUTE***";
155}
156
157bool SCEVCouldNotCompute::classof(const SCEV *S) {
158 return S->getSCEVType() == scCouldNotCompute;
159}
160
161
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000162// SCEVConstants - Only allow the creation of one SCEVConstant for any
163// particular value. Don't use a SCEVHandle here, or else the object will
164// never be deleted!
165static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000166
Chris Lattner53e677a2004-04-02 20:23:17 +0000167
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000168SCEVConstant::~SCEVConstant() {
169 SCEVConstants.erase(V);
170}
Chris Lattner53e677a2004-04-02 20:23:17 +0000171
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000172SCEVHandle SCEVConstant::get(ConstantInt *V) {
173 // Make sure that SCEVConstant instances are all unsigned.
174 if (V->getType()->isSigned()) {
175 const Type *NewTy = V->getType()->getUnsignedVersion();
176 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
177 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000178
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000179 SCEVConstant *&R = SCEVConstants[V];
180 if (R == 0) R = new SCEVConstant(V);
181 return R;
182}
Chris Lattner53e677a2004-04-02 20:23:17 +0000183
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184ConstantRange SCEVConstant::getValueRange() const {
185 return ConstantRange(V);
186}
Chris Lattner53e677a2004-04-02 20:23:17 +0000187
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190void SCEVConstant::print(std::ostream &OS) const {
191 WriteAsOperand(OS, V, false);
192}
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000194// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
195// particular input. Don't use a SCEVHandle here, or else the object will
196// never be deleted!
197static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000198
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
200 : SCEV(scTruncate), Op(op), Ty(ty) {
201 assert(Op->getType()->isInteger() && Ty->isInteger() &&
202 Ty->isUnsigned() &&
203 "Cannot truncate non-integer value!");
204 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
205 "This is not a truncating conversion!");
206}
Chris Lattner53e677a2004-04-02 20:23:17 +0000207
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000208SCEVTruncateExpr::~SCEVTruncateExpr() {
209 SCEVTruncates.erase(std::make_pair(Op, Ty));
210}
Chris Lattner53e677a2004-04-02 20:23:17 +0000211
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000212ConstantRange SCEVTruncateExpr::getValueRange() const {
213 return getOperand()->getValueRange().truncate(getType());
214}
Chris Lattner53e677a2004-04-02 20:23:17 +0000215
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216void SCEVTruncateExpr::print(std::ostream &OS) const {
217 OS << "(truncate " << *Op << " to " << *Ty << ")";
218}
219
220// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
221// particular input. Don't use a SCEVHandle here, or else the object will never
222// be deleted!
223static std::map<std::pair<SCEV*, const Type*>,
224 SCEVZeroExtendExpr*> SCEVZeroExtends;
225
226SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Chris Lattner2352fec2005-02-17 16:54:16 +0000227 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000228 assert(Op->getType()->isInteger() && Ty->isInteger() &&
229 Ty->isUnsigned() &&
230 "Cannot zero extend non-integer value!");
231 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
232 "This is not an extending conversion!");
233}
234
235SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
236 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
237}
238
239ConstantRange SCEVZeroExtendExpr::getValueRange() const {
240 return getOperand()->getValueRange().zeroExtend(getType());
241}
242
243void SCEVZeroExtendExpr::print(std::ostream &OS) const {
244 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
245}
246
247// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
248// particular input. Don't use a SCEVHandle here, or else the object will never
249// be deleted!
250static std::map<std::pair<unsigned, std::vector<SCEV*> >,
251 SCEVCommutativeExpr*> SCEVCommExprs;
252
253SCEVCommutativeExpr::~SCEVCommutativeExpr() {
254 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
255 std::vector<SCEV*>(Operands.begin(),
256 Operands.end())));
257}
258
259void SCEVCommutativeExpr::print(std::ostream &OS) const {
260 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
261 const char *OpStr = getOperationStr();
262 OS << "(" << *Operands[0];
263 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
264 OS << OpStr << *Operands[i];
265 OS << ")";
266}
267
Chris Lattner4dc534c2005-02-13 04:37:18 +0000268SCEVHandle SCEVCommutativeExpr::
269replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
270 const SCEVHandle &Conc) const {
271 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
272 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
273 if (H != getOperand(i)) {
274 std::vector<SCEVHandle> NewOps;
275 NewOps.reserve(getNumOperands());
276 for (unsigned j = 0; j != i; ++j)
277 NewOps.push_back(getOperand(j));
278 NewOps.push_back(H);
279 for (++i; i != e; ++i)
280 NewOps.push_back(getOperand(i)->
281 replaceSymbolicValuesWithConcrete(Sym, Conc));
282
283 if (isa<SCEVAddExpr>(this))
284 return SCEVAddExpr::get(NewOps);
285 else if (isa<SCEVMulExpr>(this))
286 return SCEVMulExpr::get(NewOps);
287 else
288 assert(0 && "Unknown commutative expr!");
289 }
290 }
291 return this;
292}
293
294
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000295// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
296// input. Don't use a SCEVHandle here, or else the object will never be
297// deleted!
298static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
299
300SCEVUDivExpr::~SCEVUDivExpr() {
301 SCEVUDivs.erase(std::make_pair(LHS, RHS));
302}
303
304void SCEVUDivExpr::print(std::ostream &OS) const {
305 OS << "(" << *LHS << " /u " << *RHS << ")";
306}
307
308const Type *SCEVUDivExpr::getType() const {
309 const Type *Ty = LHS->getType();
310 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
311 return Ty;
312}
313
314// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
315// particular input. Don't use a SCEVHandle here, or else the object will never
316// be deleted!
317static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
318 SCEVAddRecExpr*> SCEVAddRecExprs;
319
320SCEVAddRecExpr::~SCEVAddRecExpr() {
321 SCEVAddRecExprs.erase(std::make_pair(L,
322 std::vector<SCEV*>(Operands.begin(),
323 Operands.end())));
324}
325
Chris Lattner4dc534c2005-02-13 04:37:18 +0000326SCEVHandle SCEVAddRecExpr::
327replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
328 const SCEVHandle &Conc) const {
329 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
330 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
331 if (H != getOperand(i)) {
332 std::vector<SCEVHandle> NewOps;
333 NewOps.reserve(getNumOperands());
334 for (unsigned j = 0; j != i; ++j)
335 NewOps.push_back(getOperand(j));
336 NewOps.push_back(H);
337 for (++i; i != e; ++i)
338 NewOps.push_back(getOperand(i)->
339 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000340
Chris Lattner4dc534c2005-02-13 04:37:18 +0000341 return get(NewOps, L);
342 }
343 }
344 return this;
345}
346
347
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000348bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
349 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
350 // contain L.
351 return !QueryLoop->contains(L->getHeader());
Chris Lattner53e677a2004-04-02 20:23:17 +0000352}
353
354
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000355void SCEVAddRecExpr::print(std::ostream &OS) const {
356 OS << "{" << *Operands[0];
357 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
358 OS << ",+," << *Operands[i];
359 OS << "}<" << L->getHeader()->getName() + ">";
360}
Chris Lattner53e677a2004-04-02 20:23:17 +0000361
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000362// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
363// value. Don't use a SCEVHandle here, or else the object will never be
364// deleted!
365static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000366
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000367SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000368
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000369bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
370 // All non-instruction values are loop invariant. All instructions are loop
371 // invariant if they are not contained in the specified loop.
372 if (Instruction *I = dyn_cast<Instruction>(V))
373 return !L->contains(I->getParent());
374 return true;
375}
Chris Lattner53e677a2004-04-02 20:23:17 +0000376
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000377const Type *SCEVUnknown::getType() const {
378 return V->getType();
379}
Chris Lattner53e677a2004-04-02 20:23:17 +0000380
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000381void SCEVUnknown::print(std::ostream &OS) const {
382 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000383}
384
Chris Lattner8d741b82004-06-20 06:23:15 +0000385//===----------------------------------------------------------------------===//
386// SCEV Utilities
387//===----------------------------------------------------------------------===//
388
389namespace {
390 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
391 /// than the complexity of the RHS. This comparator is used to canonicalize
392 /// expressions.
393 struct SCEVComplexityCompare {
394 bool operator()(SCEV *LHS, SCEV *RHS) {
395 return LHS->getSCEVType() < RHS->getSCEVType();
396 }
397 };
398}
399
400/// GroupByComplexity - Given a list of SCEV objects, order them by their
401/// complexity, and group objects of the same complexity together by value.
402/// When this routine is finished, we know that any duplicates in the vector are
403/// consecutive and that complexity is monotonically increasing.
404///
405/// Note that we go take special precautions to ensure that we get determinstic
406/// results from this routine. In other words, we don't want the results of
407/// this to depend on where the addresses of various SCEV objects happened to
408/// land in memory.
409///
410static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
411 if (Ops.size() < 2) return; // Noop
412 if (Ops.size() == 2) {
413 // This is the common case, which also happens to be trivially simple.
414 // Special case it.
415 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
416 std::swap(Ops[0], Ops[1]);
417 return;
418 }
419
420 // Do the rough sort by complexity.
421 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
422
423 // Now that we are sorted by complexity, group elements of the same
424 // complexity. Note that this is, at worst, N^2, but the vector is likely to
425 // be extremely short in practice. Note that we take this approach because we
426 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000427 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000428 SCEV *S = Ops[i];
429 unsigned Complexity = S->getSCEVType();
430
431 // If there are any objects of the same complexity and same value as this
432 // one, group them.
433 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
434 if (Ops[j] == S) { // Found a duplicate.
435 // Move it to immediately after i'th element.
436 std::swap(Ops[i+1], Ops[j]);
437 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000438 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000439 }
440 }
441 }
442}
443
Chris Lattner53e677a2004-04-02 20:23:17 +0000444
Chris Lattner53e677a2004-04-02 20:23:17 +0000445
446//===----------------------------------------------------------------------===//
447// Simple SCEV method implementations
448//===----------------------------------------------------------------------===//
449
450/// getIntegerSCEV - Given an integer or FP type, create a constant for the
451/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000452SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000453 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000454 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000455 C = Constant::getNullValue(Ty);
456 else if (Ty->isFloatingPoint())
457 C = ConstantFP::get(Ty, Val);
458 else if (Ty->isSigned())
459 C = ConstantSInt::get(Ty, Val);
460 else {
461 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
462 C = ConstantExpr::getCast(C, Ty);
463 }
464 return SCEVUnknown::get(C);
465}
466
467/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
468/// input value to the specified type. If the type must be extended, it is zero
469/// extended.
470static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
471 const Type *SrcTy = V->getType();
472 assert(SrcTy->isInteger() && Ty->isInteger() &&
473 "Cannot truncate or zero extend with non-integer arguments!");
474 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
475 return V; // No conversion
476 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
477 return SCEVTruncateExpr::get(V, Ty);
478 return SCEVZeroExtendExpr::get(V, Ty);
479}
480
481/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
482///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000483SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000484 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
485 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000486
Chris Lattnerb06432c2004-04-23 21:29:03 +0000487 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000488}
489
490/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
491///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000492SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000493 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000494 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000495}
496
497
Chris Lattner53e677a2004-04-02 20:23:17 +0000498/// PartialFact - Compute V!/(V-NumSteps)!
499static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
500 // Handle this case efficiently, it is common to have constant iteration
501 // counts while computing loop exit values.
502 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
503 uint64_t Val = SC->getValue()->getRawValue();
504 uint64_t Result = 1;
505 for (; NumSteps; --NumSteps)
506 Result *= Val-(NumSteps-1);
507 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
508 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
509 }
510
511 const Type *Ty = V->getType();
512 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000513 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000514
Chris Lattner53e677a2004-04-02 20:23:17 +0000515 SCEVHandle Result = V;
516 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000517 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000518 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000519 return Result;
520}
521
522
523/// evaluateAtIteration - Return the value of this chain of recurrences at
524/// the specified iteration number. We can evaluate this recurrence by
525/// multiplying each element in the chain by the binomial coefficient
526/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
527///
528/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
529///
530/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
531/// Is the binomial equation safe using modular arithmetic??
532///
533SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
534 SCEVHandle Result = getStart();
535 int Divisor = 1;
536 const Type *Ty = It->getType();
537 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
538 SCEVHandle BC = PartialFact(It, i);
539 Divisor *= i;
540 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000541 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000542 Result = SCEVAddExpr::get(Result, Val);
543 }
544 return Result;
545}
546
547
548//===----------------------------------------------------------------------===//
549// SCEV Expression folder implementations
550//===----------------------------------------------------------------------===//
551
552SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
553 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
554 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
555
556 // If the input value is a chrec scev made out of constants, truncate
557 // all of the constants.
558 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
559 std::vector<SCEVHandle> Operands;
560 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
561 // FIXME: This should allow truncation of other expression types!
562 if (isa<SCEVConstant>(AddRec->getOperand(i)))
563 Operands.push_back(get(AddRec->getOperand(i), Ty));
564 else
565 break;
566 if (Operands.size() == AddRec->getNumOperands())
567 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
568 }
569
570 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
571 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
572 return Result;
573}
574
575SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
576 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
577 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
578
579 // FIXME: If the input value is a chrec scev, and we can prove that the value
580 // did not overflow the old, smaller, value, we can zero extend all of the
581 // operands (often constants). This would allow analysis of something like
582 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
583
584 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
585 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
586 return Result;
587}
588
589// get - Get a canonical add expression, or something simpler if possible.
590SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
591 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000592 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000593
594 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000595 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000596
597 // If there are any constants, fold them together.
598 unsigned Idx = 0;
599 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
600 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000601 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000602 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
603 // We found two constants, fold them together!
604 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
605 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
606 Ops[0] = SCEVConstant::get(CI);
607 Ops.erase(Ops.begin()+1); // Erase the folded element
608 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000609 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000610 } else {
611 // If we couldn't fold the expression, move to the next constant. Note
612 // that this is impossible to happen in practice because we always
613 // constant fold constant ints to constant ints.
614 ++Idx;
615 }
616 }
617
618 // If we are left with a constant zero being added, strip it off.
619 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
620 Ops.erase(Ops.begin());
621 --Idx;
622 }
623 }
624
Chris Lattner627018b2004-04-07 16:16:11 +0000625 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000626
Chris Lattner53e677a2004-04-02 20:23:17 +0000627 // Okay, check to see if the same value occurs in the operand list twice. If
628 // so, merge them together into an multiply expression. Since we sorted the
629 // list, these values are required to be adjacent.
630 const Type *Ty = Ops[0]->getType();
631 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
632 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
633 // Found a match, merge the two values into a multiply, and add any
634 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000635 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000636 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
637 if (Ops.size() == 2)
638 return Mul;
639 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
640 Ops.push_back(Mul);
641 return SCEVAddExpr::get(Ops);
642 }
643
644 // Okay, now we know the first non-constant operand. If there are add
645 // operands they would be next.
646 if (Idx < Ops.size()) {
647 bool DeletedAdd = false;
648 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
649 // If we have an add, expand the add operands onto the end of the operands
650 // list.
651 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
652 Ops.erase(Ops.begin()+Idx);
653 DeletedAdd = true;
654 }
655
656 // If we deleted at least one add, we added operands to the end of the list,
657 // and they are not necessarily sorted. Recurse to resort and resimplify
658 // any operands we just aquired.
659 if (DeletedAdd)
660 return get(Ops);
661 }
662
663 // Skip over the add expression until we get to a multiply.
664 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
665 ++Idx;
666
667 // If we are adding something to a multiply expression, make sure the
668 // something is not already an operand of the multiply. If so, merge it into
669 // the multiply.
670 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
671 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
672 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
673 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
674 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000675 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000676 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
677 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
678 if (Mul->getNumOperands() != 2) {
679 // If the multiply has more than two operands, we must get the
680 // Y*Z term.
681 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
682 MulOps.erase(MulOps.begin()+MulOp);
683 InnerMul = SCEVMulExpr::get(MulOps);
684 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000685 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000686 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
687 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
688 if (Ops.size() == 2) return OuterMul;
689 if (AddOp < Idx) {
690 Ops.erase(Ops.begin()+AddOp);
691 Ops.erase(Ops.begin()+Idx-1);
692 } else {
693 Ops.erase(Ops.begin()+Idx);
694 Ops.erase(Ops.begin()+AddOp-1);
695 }
696 Ops.push_back(OuterMul);
697 return SCEVAddExpr::get(Ops);
698 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000699
Chris Lattner53e677a2004-04-02 20:23:17 +0000700 // Check this multiply against other multiplies being added together.
701 for (unsigned OtherMulIdx = Idx+1;
702 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
703 ++OtherMulIdx) {
704 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
705 // If MulOp occurs in OtherMul, we can fold the two multiplies
706 // together.
707 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
708 OMulOp != e; ++OMulOp)
709 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
710 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
711 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
712 if (Mul->getNumOperands() != 2) {
713 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
714 MulOps.erase(MulOps.begin()+MulOp);
715 InnerMul1 = SCEVMulExpr::get(MulOps);
716 }
717 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
718 if (OtherMul->getNumOperands() != 2) {
719 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
720 OtherMul->op_end());
721 MulOps.erase(MulOps.begin()+OMulOp);
722 InnerMul2 = SCEVMulExpr::get(MulOps);
723 }
724 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
725 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
726 if (Ops.size() == 2) return OuterMul;
727 Ops.erase(Ops.begin()+Idx);
728 Ops.erase(Ops.begin()+OtherMulIdx-1);
729 Ops.push_back(OuterMul);
730 return SCEVAddExpr::get(Ops);
731 }
732 }
733 }
734 }
735
736 // If there are any add recurrences in the operands list, see if any other
737 // added values are loop invariant. If so, we can fold them into the
738 // recurrence.
739 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
740 ++Idx;
741
742 // Scan over all recurrences, trying to fold loop invariants into them.
743 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
744 // Scan all of the other operands to this add and add them to the vector if
745 // they are loop invariant w.r.t. the recurrence.
746 std::vector<SCEVHandle> LIOps;
747 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
748 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
749 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
750 LIOps.push_back(Ops[i]);
751 Ops.erase(Ops.begin()+i);
752 --i; --e;
753 }
754
755 // If we found some loop invariants, fold them into the recurrence.
756 if (!LIOps.empty()) {
757 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
758 LIOps.push_back(AddRec->getStart());
759
760 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
761 AddRecOps[0] = SCEVAddExpr::get(LIOps);
762
763 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
764 // If all of the other operands were loop invariant, we are done.
765 if (Ops.size() == 1) return NewRec;
766
767 // Otherwise, add the folded AddRec by the non-liv parts.
768 for (unsigned i = 0;; ++i)
769 if (Ops[i] == AddRec) {
770 Ops[i] = NewRec;
771 break;
772 }
773 return SCEVAddExpr::get(Ops);
774 }
775
776 // Okay, if there weren't any loop invariants to be folded, check to see if
777 // there are multiple AddRec's with the same loop induction variable being
778 // added together. If so, we can fold them.
779 for (unsigned OtherIdx = Idx+1;
780 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
781 if (OtherIdx != Idx) {
782 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
783 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
784 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
785 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
786 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
787 if (i >= NewOps.size()) {
788 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
789 OtherAddRec->op_end());
790 break;
791 }
792 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
793 }
794 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
795
796 if (Ops.size() == 2) return NewAddRec;
797
798 Ops.erase(Ops.begin()+Idx);
799 Ops.erase(Ops.begin()+OtherIdx-1);
800 Ops.push_back(NewAddRec);
801 return SCEVAddExpr::get(Ops);
802 }
803 }
804
805 // Otherwise couldn't fold anything into this recurrence. Move onto the
806 // next one.
807 }
808
809 // Okay, it looks like we really DO need an add expr. Check to see if we
810 // already have one, otherwise create a new one.
811 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
812 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
813 SCEVOps)];
814 if (Result == 0) Result = new SCEVAddExpr(Ops);
815 return Result;
816}
817
818
819SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
820 assert(!Ops.empty() && "Cannot get empty mul!");
821
822 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000823 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000824
825 // If there are any constants, fold them together.
826 unsigned Idx = 0;
827 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
828
829 // C1*(C2+V) -> C1*C2 + C1*V
830 if (Ops.size() == 2)
831 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
832 if (Add->getNumOperands() == 2 &&
833 isa<SCEVConstant>(Add->getOperand(0)))
834 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
835 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
836
837
838 ++Idx;
839 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
840 // We found two constants, fold them together!
841 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
842 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
843 Ops[0] = SCEVConstant::get(CI);
844 Ops.erase(Ops.begin()+1); // Erase the folded element
845 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000846 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000847 } else {
848 // If we couldn't fold the expression, move to the next constant. Note
849 // that this is impossible to happen in practice because we always
850 // constant fold constant ints to constant ints.
851 ++Idx;
852 }
853 }
854
855 // If we are left with a constant one being multiplied, strip it off.
856 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
857 Ops.erase(Ops.begin());
858 --Idx;
859 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
860 // If we have a multiply of zero, it will always be zero.
861 return Ops[0];
862 }
863 }
864
865 // Skip over the add expression until we get to a multiply.
866 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
867 ++Idx;
868
869 if (Ops.size() == 1)
870 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000871
Chris Lattner53e677a2004-04-02 20:23:17 +0000872 // If there are mul operands inline them all into this expression.
873 if (Idx < Ops.size()) {
874 bool DeletedMul = false;
875 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
876 // If we have an mul, expand the mul operands onto the end of the operands
877 // list.
878 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
879 Ops.erase(Ops.begin()+Idx);
880 DeletedMul = true;
881 }
882
883 // If we deleted at least one mul, we added operands to the end of the list,
884 // and they are not necessarily sorted. Recurse to resort and resimplify
885 // any operands we just aquired.
886 if (DeletedMul)
887 return get(Ops);
888 }
889
890 // If there are any add recurrences in the operands list, see if any other
891 // added values are loop invariant. If so, we can fold them into the
892 // recurrence.
893 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
894 ++Idx;
895
896 // Scan over all recurrences, trying to fold loop invariants into them.
897 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
898 // Scan all of the other operands to this mul and add them to the vector if
899 // they are loop invariant w.r.t. the recurrence.
900 std::vector<SCEVHandle> LIOps;
901 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
902 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
903 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
904 LIOps.push_back(Ops[i]);
905 Ops.erase(Ops.begin()+i);
906 --i; --e;
907 }
908
909 // If we found some loop invariants, fold them into the recurrence.
910 if (!LIOps.empty()) {
911 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
912 std::vector<SCEVHandle> NewOps;
913 NewOps.reserve(AddRec->getNumOperands());
914 if (LIOps.size() == 1) {
915 SCEV *Scale = LIOps[0];
916 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
917 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
918 } else {
919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
920 std::vector<SCEVHandle> MulOps(LIOps);
921 MulOps.push_back(AddRec->getOperand(i));
922 NewOps.push_back(SCEVMulExpr::get(MulOps));
923 }
924 }
925
926 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
927
928 // If all of the other operands were loop invariant, we are done.
929 if (Ops.size() == 1) return NewRec;
930
931 // Otherwise, multiply the folded AddRec by the non-liv parts.
932 for (unsigned i = 0;; ++i)
933 if (Ops[i] == AddRec) {
934 Ops[i] = NewRec;
935 break;
936 }
937 return SCEVMulExpr::get(Ops);
938 }
939
940 // Okay, if there weren't any loop invariants to be folded, check to see if
941 // there are multiple AddRec's with the same loop induction variable being
942 // multiplied together. If so, we can fold them.
943 for (unsigned OtherIdx = Idx+1;
944 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
945 if (OtherIdx != Idx) {
946 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
947 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
948 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
949 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
950 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
951 G->getStart());
952 SCEVHandle B = F->getStepRecurrence();
953 SCEVHandle D = G->getStepRecurrence();
954 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
955 SCEVMulExpr::get(G, B),
956 SCEVMulExpr::get(B, D));
957 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
958 F->getLoop());
959 if (Ops.size() == 2) return NewAddRec;
960
961 Ops.erase(Ops.begin()+Idx);
962 Ops.erase(Ops.begin()+OtherIdx-1);
963 Ops.push_back(NewAddRec);
964 return SCEVMulExpr::get(Ops);
965 }
966 }
967
968 // Otherwise couldn't fold anything into this recurrence. Move onto the
969 // next one.
970 }
971
972 // Okay, it looks like we really DO need an mul expr. Check to see if we
973 // already have one, otherwise create a new one.
974 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
975 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
976 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000977 if (Result == 0)
978 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000979 return Result;
980}
981
982SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
983 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
984 if (RHSC->getValue()->equalsInt(1))
985 return LHS; // X /u 1 --> x
986 if (RHSC->getValue()->isAllOnesValue())
Chris Lattnerbac5b462005-03-09 05:34:41 +0000987 return SCEV::getNegativeSCEV(LHS); // X /u -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000988
989 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
990 Constant *LHSCV = LHSC->getValue();
991 Constant *RHSCV = RHSC->getValue();
992 if (LHSCV->getType()->isSigned())
993 LHSCV = ConstantExpr::getCast(LHSCV,
994 LHSCV->getType()->getUnsignedVersion());
995 if (RHSCV->getType()->isSigned())
996 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
997 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
998 }
999 }
1000
1001 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1002
1003 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
1004 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1005 return Result;
1006}
1007
1008
1009/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1010/// specified loop. Simplify the expression as much as possible.
1011SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1012 const SCEVHandle &Step, const Loop *L) {
1013 std::vector<SCEVHandle> Operands;
1014 Operands.push_back(Start);
1015 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1016 if (StepChrec->getLoop() == L) {
1017 Operands.insert(Operands.end(), StepChrec->op_begin(),
1018 StepChrec->op_end());
1019 return get(Operands, L);
1020 }
1021
1022 Operands.push_back(Step);
1023 return get(Operands, L);
1024}
1025
1026/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1027/// specified loop. Simplify the expression as much as possible.
1028SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1029 const Loop *L) {
1030 if (Operands.size() == 1) return Operands[0];
1031
1032 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1033 if (StepC->getValue()->isNullValue()) {
1034 Operands.pop_back();
1035 return get(Operands, L); // { X,+,0 } --> X
1036 }
1037
1038 SCEVAddRecExpr *&Result =
1039 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1040 Operands.end()))];
1041 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1042 return Result;
1043}
1044
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001045SCEVHandle SCEVUnknown::get(Value *V) {
1046 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1047 return SCEVConstant::get(CI);
1048 SCEVUnknown *&Result = SCEVUnknowns[V];
1049 if (Result == 0) Result = new SCEVUnknown(V);
1050 return Result;
1051}
1052
Chris Lattner53e677a2004-04-02 20:23:17 +00001053
1054//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001055// ScalarEvolutionsImpl Definition and Implementation
1056//===----------------------------------------------------------------------===//
1057//
1058/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1059/// evolution code.
1060///
1061namespace {
1062 struct ScalarEvolutionsImpl {
1063 /// F - The function we are analyzing.
1064 ///
1065 Function &F;
1066
1067 /// LI - The loop information for the function we are currently analyzing.
1068 ///
1069 LoopInfo &LI;
1070
1071 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1072 /// things.
1073 SCEVHandle UnknownValue;
1074
1075 /// Scalars - This is a cache of the scalars we have analyzed so far.
1076 ///
1077 std::map<Value*, SCEVHandle> Scalars;
1078
1079 /// IterationCounts - Cache the iteration count of the loops for this
1080 /// function as they are computed.
1081 std::map<const Loop*, SCEVHandle> IterationCounts;
1082
Chris Lattner3221ad02004-04-17 22:58:41 +00001083 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1084 /// the PHI instructions that we attempt to compute constant evolutions for.
1085 /// This allows us to avoid potentially expensive recomputation of these
1086 /// properties. An instruction maps to null if we are unable to compute its
1087 /// exit value.
1088 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001089
Chris Lattner53e677a2004-04-02 20:23:17 +00001090 public:
1091 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1092 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1093
1094 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1095 /// expression and create a new one.
1096 SCEVHandle getSCEV(Value *V);
1097
Chris Lattnera0740fb2005-08-09 23:36:33 +00001098 /// hasSCEV - Return true if the SCEV for this value has already been
1099 /// computed.
1100 bool hasSCEV(Value *V) const {
1101 return Scalars.count(V);
1102 }
1103
1104 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1105 /// the specified value.
1106 void setSCEV(Value *V, const SCEVHandle &H) {
1107 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1108 assert(isNew && "This entry already existed!");
1109 }
1110
1111
Chris Lattner53e677a2004-04-02 20:23:17 +00001112 /// getSCEVAtScope - Compute the value of the specified expression within
1113 /// the indicated loop (which may be null to indicate in no loop). If the
1114 /// expression cannot be evaluated, return UnknownValue itself.
1115 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1116
1117
1118 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1119 /// an analyzable loop-invariant iteration count.
1120 bool hasLoopInvariantIterationCount(const Loop *L);
1121
1122 /// getIterationCount - If the specified loop has a predictable iteration
1123 /// count, return it. Note that it is not valid to call this method on a
1124 /// loop without a loop-invariant iteration count.
1125 SCEVHandle getIterationCount(const Loop *L);
1126
1127 /// deleteInstructionFromRecords - This method should be called by the
1128 /// client before it removes an instruction from the program, to make sure
1129 /// that no dangling references are left around.
1130 void deleteInstructionFromRecords(Instruction *I);
1131
1132 private:
1133 /// createSCEV - We know that there is no SCEV for the specified value.
1134 /// Analyze the expression.
1135 SCEVHandle createSCEV(Value *V);
1136 SCEVHandle createNodeForCast(CastInst *CI);
1137
1138 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1139 /// SCEVs.
1140 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001141
1142 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1143 /// for the specified instruction and replaces any references to the
1144 /// symbolic value SymName with the specified value. This is used during
1145 /// PHI resolution.
1146 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1147 const SCEVHandle &SymName,
1148 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001149
1150 /// ComputeIterationCount - Compute the number of times the specified loop
1151 /// will iterate.
1152 SCEVHandle ComputeIterationCount(const Loop *L);
1153
Chris Lattner673e02b2004-10-12 01:49:27 +00001154 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1155 /// 'setcc load X, cst', try to se if we can compute the trip count.
1156 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1157 Constant *RHS,
1158 const Loop *L,
1159 unsigned SetCCOpcode);
1160
Chris Lattner7980fb92004-04-17 18:36:24 +00001161 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1162 /// constant number of times (the condition evolves only from constants),
1163 /// try to evaluate a few iterations of the loop until we get the exit
1164 /// condition gets a value of ExitWhen (true or false). If we cannot
1165 /// evaluate the trip count of the loop, return UnknownValue.
1166 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1167 bool ExitWhen);
1168
Chris Lattner53e677a2004-04-02 20:23:17 +00001169 /// HowFarToZero - Return the number of times a backedge comparing the
1170 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001171 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001172 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1173
1174 /// HowFarToNonZero - Return the number of times a backedge checking the
1175 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001176 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001177 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001178
Chris Lattnerdb25de42005-08-15 23:33:51 +00001179 /// HowManyLessThans - Return the number of times a backedge containing the
1180 /// specified less-than comparison will execute. If not computable, return
1181 /// UnknownValue.
1182 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1183
Chris Lattner3221ad02004-04-17 22:58:41 +00001184 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1185 /// in the header of its containing loop, we know the loop executes a
1186 /// constant number of times, and the PHI node is just a recurrence
1187 /// involving constants, fold it.
1188 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1189 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001190 };
1191}
1192
1193//===----------------------------------------------------------------------===//
1194// Basic SCEV Analysis and PHI Idiom Recognition Code
1195//
1196
1197/// deleteInstructionFromRecords - This method should be called by the
1198/// client before it removes an instruction from the program, to make sure
1199/// that no dangling references are left around.
1200void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1201 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001202 if (PHINode *PN = dyn_cast<PHINode>(I))
1203 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001204}
1205
1206
1207/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1208/// expression and create a new one.
1209SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1210 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1211
1212 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1213 if (I != Scalars.end()) return I->second;
1214 SCEVHandle S = createSCEV(V);
1215 Scalars.insert(std::make_pair(V, S));
1216 return S;
1217}
1218
Chris Lattner4dc534c2005-02-13 04:37:18 +00001219/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1220/// the specified instruction and replaces any references to the symbolic value
1221/// SymName with the specified value. This is used during PHI resolution.
1222void ScalarEvolutionsImpl::
1223ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1224 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001225 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001226 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001227
Chris Lattner4dc534c2005-02-13 04:37:18 +00001228 SCEVHandle NV =
1229 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1230 if (NV == SI->second) return; // No change.
1231
1232 SI->second = NV; // Update the scalars map!
1233
1234 // Any instruction values that use this instruction might also need to be
1235 // updated!
1236 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1237 UI != E; ++UI)
1238 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1239}
Chris Lattner53e677a2004-04-02 20:23:17 +00001240
1241/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1242/// a loop header, making it a potential recurrence, or it doesn't.
1243///
1244SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1245 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1246 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1247 if (L->getHeader() == PN->getParent()) {
1248 // If it lives in the loop header, it has two incoming values, one
1249 // from outside the loop, and one from inside.
1250 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1251 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001252
Chris Lattner53e677a2004-04-02 20:23:17 +00001253 // While we are analyzing this PHI node, handle its value symbolically.
1254 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1255 assert(Scalars.find(PN) == Scalars.end() &&
1256 "PHI node already processed?");
1257 Scalars.insert(std::make_pair(PN, SymbolicName));
1258
1259 // Using this symbolic name for the PHI, analyze the value coming around
1260 // the back-edge.
1261 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1262
1263 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1264 // has a special value for the first iteration of the loop.
1265
1266 // If the value coming around the backedge is an add with the symbolic
1267 // value we just inserted, then we found a simple induction variable!
1268 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1269 // If there is a single occurrence of the symbolic value, replace it
1270 // with a recurrence.
1271 unsigned FoundIndex = Add->getNumOperands();
1272 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1273 if (Add->getOperand(i) == SymbolicName)
1274 if (FoundIndex == e) {
1275 FoundIndex = i;
1276 break;
1277 }
1278
1279 if (FoundIndex != Add->getNumOperands()) {
1280 // Create an add with everything but the specified operand.
1281 std::vector<SCEVHandle> Ops;
1282 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1283 if (i != FoundIndex)
1284 Ops.push_back(Add->getOperand(i));
1285 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1286
1287 // This is not a valid addrec if the step amount is varying each
1288 // loop iteration, but is not itself an addrec in this loop.
1289 if (Accum->isLoopInvariant(L) ||
1290 (isa<SCEVAddRecExpr>(Accum) &&
1291 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1292 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1293 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1294
1295 // Okay, for the entire analysis of this edge we assumed the PHI
1296 // to be symbolic. We now need to go back and update all of the
1297 // entries for the scalars that use the PHI (except for the PHI
1298 // itself) to use the new analyzed value instead of the "symbolic"
1299 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001300 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001301 return PHISCEV;
1302 }
1303 }
1304 }
1305
1306 return SymbolicName;
1307 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001308
Chris Lattner53e677a2004-04-02 20:23:17 +00001309 // If it's not a loop phi, we can't handle it yet.
1310 return SCEVUnknown::get(PN);
1311}
1312
1313/// createNodeForCast - Handle the various forms of casts that we support.
1314///
1315SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1316 const Type *SrcTy = CI->getOperand(0)->getType();
1317 const Type *DestTy = CI->getType();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001318
Chris Lattner53e677a2004-04-02 20:23:17 +00001319 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1320 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1321 return getSCEV(CI->getOperand(0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001322
Chris Lattner53e677a2004-04-02 20:23:17 +00001323 if (SrcTy->isInteger() && DestTy->isInteger()) {
1324 // Otherwise, if this is a truncating integer cast, we can represent this
1325 // cast.
1326 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1327 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1328 CI->getType()->getUnsignedVersion());
1329 if (SrcTy->isUnsigned() &&
1330 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1331 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1332 CI->getType()->getUnsignedVersion());
1333 }
1334
1335 // If this is an sign or zero extending cast and we can prove that the value
1336 // will never overflow, we could do similar transformations.
1337
1338 // Otherwise, we can't handle this cast!
1339 return SCEVUnknown::get(CI);
1340}
1341
1342
1343/// createSCEV - We know that there is no SCEV for the specified value.
1344/// Analyze the expression.
1345///
1346SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1347 if (Instruction *I = dyn_cast<Instruction>(V)) {
1348 switch (I->getOpcode()) {
1349 case Instruction::Add:
1350 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1351 getSCEV(I->getOperand(1)));
1352 case Instruction::Mul:
1353 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1354 getSCEV(I->getOperand(1)));
1355 case Instruction::Div:
1356 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1357 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1358 getSCEV(I->getOperand(1)));
1359 break;
1360
1361 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001362 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1363 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001364
1365 case Instruction::Shl:
1366 // Turn shift left of a constant amount into a multiply.
1367 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1368 Constant *X = ConstantInt::get(V->getType(), 1);
1369 X = ConstantExpr::getShl(X, SA);
1370 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1371 }
1372 break;
1373
1374 case Instruction::Shr:
1375 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1376 if (V->getType()->isUnsigned()) {
1377 Constant *X = ConstantInt::get(V->getType(), 1);
1378 X = ConstantExpr::getShl(X, SA);
1379 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1380 }
1381 break;
1382
1383 case Instruction::Cast:
1384 return createNodeForCast(cast<CastInst>(I));
1385
1386 case Instruction::PHI:
1387 return createNodeForPHI(cast<PHINode>(I));
1388
1389 default: // We cannot analyze this expression.
1390 break;
1391 }
1392 }
1393
1394 return SCEVUnknown::get(V);
1395}
1396
1397
1398
1399//===----------------------------------------------------------------------===//
1400// Iteration Count Computation Code
1401//
1402
1403/// getIterationCount - If the specified loop has a predictable iteration
1404/// count, return it. Note that it is not valid to call this method on a
1405/// loop without a loop-invariant iteration count.
1406SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1407 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1408 if (I == IterationCounts.end()) {
1409 SCEVHandle ItCount = ComputeIterationCount(L);
1410 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1411 if (ItCount != UnknownValue) {
1412 assert(ItCount->isLoopInvariant(L) &&
1413 "Computed trip count isn't loop invariant for loop!");
1414 ++NumTripCountsComputed;
1415 } else if (isa<PHINode>(L->getHeader()->begin())) {
1416 // Only count loops that have phi nodes as not being computable.
1417 ++NumTripCountsNotComputed;
1418 }
1419 }
1420 return I->second;
1421}
1422
1423/// ComputeIterationCount - Compute the number of times the specified loop
1424/// will iterate.
1425SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1426 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001427 std::vector<BasicBlock*> ExitBlocks;
1428 L->getExitBlocks(ExitBlocks);
1429 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001430
1431 // Okay, there is one exit block. Try to find the condition that causes the
1432 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001433 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001434
1435 BasicBlock *ExitingBlock = 0;
1436 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1437 PI != E; ++PI)
1438 if (L->contains(*PI)) {
1439 if (ExitingBlock == 0)
1440 ExitingBlock = *PI;
1441 else
1442 return UnknownValue; // More than one block exiting!
1443 }
1444 assert(ExitingBlock && "No exits from loop, something is broken!");
1445
1446 // Okay, we've computed the exiting block. See what condition causes us to
1447 // exit.
1448 //
1449 // FIXME: we should be able to handle switch instructions (with a single exit)
1450 // FIXME: We should handle cast of int to bool as well
1451 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1452 if (ExitBr == 0) return UnknownValue;
1453 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1454 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001455 if (ExitCond == 0) // Not a setcc
1456 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1457 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001458
Chris Lattner673e02b2004-10-12 01:49:27 +00001459 // If the condition was exit on true, convert the condition to exit on false.
1460 Instruction::BinaryOps Cond;
1461 if (ExitBr->getSuccessor(1) == ExitBlock)
1462 Cond = ExitCond->getOpcode();
1463 else
1464 Cond = ExitCond->getInverseCondition();
1465
1466 // Handle common loops like: for (X = "string"; *X; ++X)
1467 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1468 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1469 SCEVHandle ItCnt =
1470 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1471 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1472 }
1473
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1475 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1476
1477 // Try to evaluate any dependencies out of the loop.
1478 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1479 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1480 Tmp = getSCEVAtScope(RHS, L);
1481 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1482
Chris Lattner53e677a2004-04-02 20:23:17 +00001483 // At this point, we would like to compute how many iterations of the loop the
1484 // predicate will return true for these inputs.
1485 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1486 // If there is a constant, force it into the RHS.
1487 std::swap(LHS, RHS);
1488 Cond = SetCondInst::getSwappedCondition(Cond);
1489 }
1490
1491 // FIXME: think about handling pointer comparisons! i.e.:
1492 // while (P != P+100) ++P;
1493
1494 // If we have a comparison of a chrec against a constant, try to use value
1495 // ranges to answer this query.
1496 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1497 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1498 if (AddRec->getLoop() == L) {
1499 // Form the comparison range using the constant of the correct type so
1500 // that the ConstantRange class knows to do a signed or unsigned
1501 // comparison.
1502 ConstantInt *CompVal = RHSC->getValue();
1503 const Type *RealTy = ExitCond->getOperand(0)->getType();
1504 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1505 if (CompVal) {
1506 // Form the constant range.
1507 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001508
Chris Lattner53e677a2004-04-02 20:23:17 +00001509 // Now that we have it, if it's signed, convert it to an unsigned
1510 // range.
1511 if (CompRange.getLower()->getType()->isSigned()) {
1512 const Type *NewTy = RHSC->getValue()->getType();
1513 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1514 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1515 CompRange = ConstantRange(NewL, NewU);
1516 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001517
Chris Lattner53e677a2004-04-02 20:23:17 +00001518 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1519 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1520 }
1521 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001522
Chris Lattner53e677a2004-04-02 20:23:17 +00001523 switch (Cond) {
1524 case Instruction::SetNE: // while (X != Y)
1525 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001526 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001527 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001528 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1529 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001530 break;
1531 case Instruction::SetEQ:
1532 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001533 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001534 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001535 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1536 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001538 case Instruction::SetLT:
1539 if (LHS->getType()->isInteger() &&
1540 ExitCond->getOperand(0)->getType()->isSigned()) {
1541 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1542 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1543 }
1544 break;
1545 case Instruction::SetGT:
1546 if (LHS->getType()->isInteger() &&
1547 ExitCond->getOperand(0)->getType()->isSigned()) {
1548 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1549 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1550 }
1551 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001552 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001553#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00001554 std::cerr << "ComputeIterationCount ";
1555 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1556 std::cerr << "[unsigned] ";
1557 std::cerr << *LHS << " "
1558 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001559#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001560 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001561 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001562
1563 return ComputeIterationCountExhaustively(L, ExitCond,
1564 ExitBr->getSuccessor(0) == ExitBlock);
1565}
1566
Chris Lattner673e02b2004-10-12 01:49:27 +00001567static ConstantInt *
1568EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1569 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1570 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1571 assert(isa<SCEVConstant>(Val) &&
1572 "Evaluation of SCEV at constant didn't fold correctly?");
1573 return cast<SCEVConstant>(Val)->getValue();
1574}
1575
1576/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1577/// and a GEP expression (missing the pointer index) indexing into it, return
1578/// the addressed element of the initializer or null if the index expression is
1579/// invalid.
1580static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001581GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001582 const std::vector<ConstantInt*> &Indices) {
1583 Constant *Init = GV->getInitializer();
1584 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1585 uint64_t Idx = Indices[i]->getRawValue();
1586 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1587 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1588 Init = cast<Constant>(CS->getOperand(Idx));
1589 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1590 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1591 Init = cast<Constant>(CA->getOperand(Idx));
1592 } else if (isa<ConstantAggregateZero>(Init)) {
1593 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1594 assert(Idx < STy->getNumElements() && "Bad struct index!");
1595 Init = Constant::getNullValue(STy->getElementType(Idx));
1596 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1597 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1598 Init = Constant::getNullValue(ATy->getElementType());
1599 } else {
1600 assert(0 && "Unknown constant aggregate type!");
1601 }
1602 return 0;
1603 } else {
1604 return 0; // Unknown initializer type
1605 }
1606 }
1607 return Init;
1608}
1609
1610/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1611/// 'setcc load X, cst', try to se if we can compute the trip count.
1612SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001613ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattner673e02b2004-10-12 01:49:27 +00001614 const Loop *L, unsigned SetCCOpcode) {
1615 if (LI->isVolatile()) return UnknownValue;
1616
1617 // Check to see if the loaded pointer is a getelementptr of a global.
1618 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1619 if (!GEP) return UnknownValue;
1620
1621 // Make sure that it is really a constant global we are gepping, with an
1622 // initializer, and make sure the first IDX is really 0.
1623 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1624 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1625 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1626 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1627 return UnknownValue;
1628
1629 // Okay, we allow one non-constant index into the GEP instruction.
1630 Value *VarIdx = 0;
1631 std::vector<ConstantInt*> Indexes;
1632 unsigned VarIdxNum = 0;
1633 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1634 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1635 Indexes.push_back(CI);
1636 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1637 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1638 VarIdx = GEP->getOperand(i);
1639 VarIdxNum = i-2;
1640 Indexes.push_back(0);
1641 }
1642
1643 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1644 // Check to see if X is a loop variant variable value now.
1645 SCEVHandle Idx = getSCEV(VarIdx);
1646 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1647 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1648
1649 // We can only recognize very limited forms of loop index expressions, in
1650 // particular, only affine AddRec's like {C1,+,C2}.
1651 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1652 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1653 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1654 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1655 return UnknownValue;
1656
1657 unsigned MaxSteps = MaxBruteForceIterations;
1658 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1659 ConstantUInt *ItCst =
1660 ConstantUInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
1661 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1662
1663 // Form the GEP offset.
1664 Indexes[VarIdxNum] = Val;
1665
1666 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1667 if (Result == 0) break; // Cannot compute!
1668
1669 // Evaluate the condition for this iteration.
1670 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1671 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
1672 if (Result == ConstantBool::False) {
1673#if 0
1674 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1675 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1676 << "***\n";
1677#endif
1678 ++NumArrayLenItCounts;
1679 return SCEVConstant::get(ItCst); // Found terminating iteration!
1680 }
1681 }
1682 return UnknownValue;
1683}
1684
1685
Chris Lattner3221ad02004-04-17 22:58:41 +00001686/// CanConstantFold - Return true if we can constant fold an instruction of the
1687/// specified type, assuming that all operands were constants.
1688static bool CanConstantFold(const Instruction *I) {
1689 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1690 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1691 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001692
Chris Lattner3221ad02004-04-17 22:58:41 +00001693 if (const CallInst *CI = dyn_cast<CallInst>(I))
1694 if (const Function *F = CI->getCalledFunction())
1695 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1696 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001697}
1698
Chris Lattner3221ad02004-04-17 22:58:41 +00001699/// ConstantFold - Constant fold an instruction of the specified type with the
1700/// specified constant operands. This function may modify the operands vector.
1701static Constant *ConstantFold(const Instruction *I,
1702 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001703 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1704 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1705
1706 switch (I->getOpcode()) {
1707 case Instruction::Cast:
1708 return ConstantExpr::getCast(Operands[0], I->getType());
1709 case Instruction::Select:
1710 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1711 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001712 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001713 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001714 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001715 }
1716
1717 return 0;
1718 case Instruction::GetElementPtr:
1719 Constant *Base = Operands[0];
1720 Operands.erase(Operands.begin());
1721 return ConstantExpr::getGetElementPtr(Base, Operands);
1722 }
1723 return 0;
1724}
1725
1726
Chris Lattner3221ad02004-04-17 22:58:41 +00001727/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1728/// in the loop that V is derived from. We allow arbitrary operations along the
1729/// way, but the operands of an operation must either be constants or a value
1730/// derived from a constant PHI. If this expression does not fit with these
1731/// constraints, return null.
1732static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1733 // If this is not an instruction, or if this is an instruction outside of the
1734 // loop, it can't be derived from a loop PHI.
1735 Instruction *I = dyn_cast<Instruction>(V);
1736 if (I == 0 || !L->contains(I->getParent())) return 0;
1737
1738 if (PHINode *PN = dyn_cast<PHINode>(I))
1739 if (L->getHeader() == I->getParent())
1740 return PN;
1741 else
1742 // We don't currently keep track of the control flow needed to evaluate
1743 // PHIs, so we cannot handle PHIs inside of loops.
1744 return 0;
1745
1746 // If we won't be able to constant fold this expression even if the operands
1747 // are constants, return early.
1748 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001749
Chris Lattner3221ad02004-04-17 22:58:41 +00001750 // Otherwise, we can evaluate this instruction if all of its operands are
1751 // constant or derived from a PHI node themselves.
1752 PHINode *PHI = 0;
1753 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1754 if (!(isa<Constant>(I->getOperand(Op)) ||
1755 isa<GlobalValue>(I->getOperand(Op)))) {
1756 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1757 if (P == 0) return 0; // Not evolving from PHI
1758 if (PHI == 0)
1759 PHI = P;
1760 else if (PHI != P)
1761 return 0; // Evolving from multiple different PHIs.
1762 }
1763
1764 // This is a expression evolving from a constant PHI!
1765 return PHI;
1766}
1767
1768/// EvaluateExpression - Given an expression that passes the
1769/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1770/// in the loop has the value PHIVal. If we can't fold this expression for some
1771/// reason, return null.
1772static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1773 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001774 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001775 return GV;
1776 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001777 Instruction *I = cast<Instruction>(V);
1778
1779 std::vector<Constant*> Operands;
1780 Operands.resize(I->getNumOperands());
1781
1782 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1783 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1784 if (Operands[i] == 0) return 0;
1785 }
1786
1787 return ConstantFold(I, Operands);
1788}
1789
1790/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1791/// in the header of its containing loop, we know the loop executes a
1792/// constant number of times, and the PHI node is just a recurrence
1793/// involving constants, fold it.
1794Constant *ScalarEvolutionsImpl::
1795getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1796 std::map<PHINode*, Constant*>::iterator I =
1797 ConstantEvolutionLoopExitValue.find(PN);
1798 if (I != ConstantEvolutionLoopExitValue.end())
1799 return I->second;
1800
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001801 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001802 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1803
1804 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1805
1806 // Since the loop is canonicalized, the PHI node must have two entries. One
1807 // entry must be a constant (coming in from outside of the loop), and the
1808 // second must be derived from the same PHI.
1809 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1810 Constant *StartCST =
1811 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1812 if (StartCST == 0)
1813 return RetVal = 0; // Must be a constant.
1814
1815 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1816 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1817 if (PN2 != PN)
1818 return RetVal = 0; // Not derived from same PHI.
1819
1820 // Execute the loop symbolically to determine the exit value.
1821 unsigned IterationNum = 0;
1822 unsigned NumIterations = Its;
1823 if (NumIterations != Its)
1824 return RetVal = 0; // More than 2^32 iterations??
1825
1826 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1827 if (IterationNum == NumIterations)
1828 return RetVal = PHIVal; // Got exit value!
1829
1830 // Compute the value of the PHI node for the next iteration.
1831 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1832 if (NextPHI == PHIVal)
1833 return RetVal = NextPHI; // Stopped evolving!
1834 if (NextPHI == 0)
1835 return 0; // Couldn't evaluate!
1836 PHIVal = NextPHI;
1837 }
1838}
1839
Chris Lattner7980fb92004-04-17 18:36:24 +00001840/// ComputeIterationCountExhaustively - If the trip is known to execute a
1841/// constant number of times (the condition evolves only from constants),
1842/// try to evaluate a few iterations of the loop until we get the exit
1843/// condition gets a value of ExitWhen (true or false). If we cannot
1844/// evaluate the trip count of the loop, return UnknownValue.
1845SCEVHandle ScalarEvolutionsImpl::
1846ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1847 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1848 if (PN == 0) return UnknownValue;
1849
1850 // Since the loop is canonicalized, the PHI node must have two entries. One
1851 // entry must be a constant (coming in from outside of the loop), and the
1852 // second must be derived from the same PHI.
1853 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1854 Constant *StartCST =
1855 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1856 if (StartCST == 0) return UnknownValue; // Must be a constant.
1857
1858 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1859 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1860 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1861
1862 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1863 // the loop symbolically to determine when the condition gets a value of
1864 // "ExitWhen".
1865 unsigned IterationNum = 0;
1866 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1867 for (Constant *PHIVal = StartCST;
1868 IterationNum != MaxIterations; ++IterationNum) {
1869 ConstantBool *CondVal =
1870 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1871 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001872
Chris Lattner7980fb92004-04-17 18:36:24 +00001873 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001874 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001875 ++NumBruteForceTripCountsComputed;
1876 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1877 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001878
Chris Lattner3221ad02004-04-17 22:58:41 +00001879 // Compute the value of the PHI node for the next iteration.
1880 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1881 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001882 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001883 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001884 }
1885
1886 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001887 return UnknownValue;
1888}
1889
1890/// getSCEVAtScope - Compute the value of the specified expression within the
1891/// indicated loop (which may be null to indicate in no loop). If the
1892/// expression cannot be evaluated, return UnknownValue.
1893SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1894 // FIXME: this should be turned into a virtual method on SCEV!
1895
Chris Lattner3221ad02004-04-17 22:58:41 +00001896 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001897
Chris Lattner3221ad02004-04-17 22:58:41 +00001898 // If this instruction is evolves from a constant-evolving PHI, compute the
1899 // exit value from the loop without using SCEVs.
1900 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1901 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1902 const Loop *LI = this->LI[I->getParent()];
1903 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1904 if (PHINode *PN = dyn_cast<PHINode>(I))
1905 if (PN->getParent() == LI->getHeader()) {
1906 // Okay, there is no closed form solution for the PHI node. Check
1907 // to see if the loop that contains it has a known iteration count.
1908 // If so, we may be able to force computation of the exit value.
1909 SCEVHandle IterationCount = getIterationCount(LI);
1910 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1911 // Okay, we know how many times the containing loop executes. If
1912 // this is a constant evolving PHI node, get the final value at
1913 // the specified iteration number.
1914 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1915 ICC->getValue()->getRawValue(),
1916 LI);
1917 if (RV) return SCEVUnknown::get(RV);
1918 }
1919 }
1920
1921 // Okay, this is a some expression that we cannot symbolically evaluate
1922 // into a SCEV. Check to see if it's possible to symbolically evaluate
1923 // the arguments into constants, and if see, try to constant propagate the
1924 // result. This is particularly useful for computing loop exit values.
1925 if (CanConstantFold(I)) {
1926 std::vector<Constant*> Operands;
1927 Operands.reserve(I->getNumOperands());
1928 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1929 Value *Op = I->getOperand(i);
1930 if (Constant *C = dyn_cast<Constant>(Op)) {
1931 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001932 } else {
1933 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1934 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1935 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1936 Op->getType()));
1937 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1938 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1939 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1940 else
1941 return V;
1942 } else {
1943 return V;
1944 }
1945 }
1946 }
1947 return SCEVUnknown::get(ConstantFold(I, Operands));
1948 }
1949 }
1950
1951 // This is some other type of SCEVUnknown, just return it.
1952 return V;
1953 }
1954
Chris Lattner53e677a2004-04-02 20:23:17 +00001955 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1956 // Avoid performing the look-up in the common case where the specified
1957 // expression has no loop-variant portions.
1958 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1959 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1960 if (OpAtScope != Comm->getOperand(i)) {
1961 if (OpAtScope == UnknownValue) return UnknownValue;
1962 // Okay, at least one of these operands is loop variant but might be
1963 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00001964 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00001965 NewOps.push_back(OpAtScope);
1966
1967 for (++i; i != e; ++i) {
1968 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1969 if (OpAtScope == UnknownValue) return UnknownValue;
1970 NewOps.push_back(OpAtScope);
1971 }
1972 if (isa<SCEVAddExpr>(Comm))
1973 return SCEVAddExpr::get(NewOps);
1974 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1975 return SCEVMulExpr::get(NewOps);
1976 }
1977 }
1978 // If we got here, all operands are loop invariant.
1979 return Comm;
1980 }
1981
1982 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1983 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1984 if (LHS == UnknownValue) return LHS;
1985 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1986 if (RHS == UnknownValue) return RHS;
1987 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1988 return UDiv; // must be loop invariant
1989 return SCEVUDivExpr::get(LHS, RHS);
1990 }
1991
1992 // If this is a loop recurrence for a loop that does not contain L, then we
1993 // are dealing with the final value computed by the loop.
1994 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1995 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1996 // To evaluate this recurrence, we need to know how many times the AddRec
1997 // loop iterates. Compute this now.
1998 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1999 if (IterationCount == UnknownValue) return UnknownValue;
2000 IterationCount = getTruncateOrZeroExtend(IterationCount,
2001 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002002
Chris Lattner53e677a2004-04-02 20:23:17 +00002003 // If the value is affine, simplify the expression evaluation to just
2004 // Start + Step*IterationCount.
2005 if (AddRec->isAffine())
2006 return SCEVAddExpr::get(AddRec->getStart(),
2007 SCEVMulExpr::get(IterationCount,
2008 AddRec->getOperand(1)));
2009
2010 // Otherwise, evaluate it the hard way.
2011 return AddRec->evaluateAtIteration(IterationCount);
2012 }
2013 return UnknownValue;
2014 }
2015
2016 //assert(0 && "Unknown SCEV type!");
2017 return UnknownValue;
2018}
2019
2020
2021/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2022/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2023/// might be the same) or two SCEVCouldNotCompute objects.
2024///
2025static std::pair<SCEVHandle,SCEVHandle>
2026SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2027 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2028 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2029 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2030 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002031
Chris Lattner53e677a2004-04-02 20:23:17 +00002032 // We currently can only solve this if the coefficients are constants.
2033 if (!L || !M || !N) {
2034 SCEV *CNC = new SCEVCouldNotCompute();
2035 return std::make_pair(CNC, CNC);
2036 }
2037
2038 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002039
Chris Lattner53e677a2004-04-02 20:23:17 +00002040 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2041 Constant *C = L->getValue();
2042 // The B coefficient is M-N/2
2043 Constant *B = ConstantExpr::getSub(M->getValue(),
2044 ConstantExpr::getDiv(N->getValue(),
2045 Two));
2046 // The A coefficient is N/2
2047 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002048
Chris Lattner53e677a2004-04-02 20:23:17 +00002049 // Compute the B^2-4ac term.
2050 Constant *SqrtTerm =
2051 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2052 ConstantExpr::getMul(A, C));
2053 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2054
2055 // Compute floor(sqrt(B^2-4ac))
2056 ConstantUInt *SqrtVal =
2057 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
2058 SqrtTerm->getType()->getUnsignedVersion()));
2059 uint64_t SqrtValV = SqrtVal->getValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002060 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002061 // The square root might not be precise for arbitrary 64-bit integer
2062 // values. Do some sanity checks to ensure it's correct.
2063 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2064 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2065 SCEV *CNC = new SCEVCouldNotCompute();
2066 return std::make_pair(CNC, CNC);
2067 }
2068
2069 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
2070 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002071
Chris Lattner53e677a2004-04-02 20:23:17 +00002072 Constant *NegB = ConstantExpr::getNeg(B);
2073 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002074
Chris Lattner53e677a2004-04-02 20:23:17 +00002075 // The divisions must be performed as signed divisions.
2076 const Type *SignedTy = NegB->getType()->getSignedVersion();
2077 NegB = ConstantExpr::getCast(NegB, SignedTy);
2078 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2079 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002080
Chris Lattner53e677a2004-04-02 20:23:17 +00002081 Constant *Solution1 =
2082 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
2083 Constant *Solution2 =
2084 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
2085 return std::make_pair(SCEVUnknown::get(Solution1),
2086 SCEVUnknown::get(Solution2));
2087}
2088
2089/// HowFarToZero - Return the number of times a backedge comparing the specified
2090/// value to zero will execute. If not computable, return UnknownValue
2091SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2092 // If the value is a constant
2093 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2094 // If the value is already zero, the branch will execute zero times.
2095 if (C->getValue()->isNullValue()) return C;
2096 return UnknownValue; // Otherwise it will loop infinitely.
2097 }
2098
2099 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2100 if (!AddRec || AddRec->getLoop() != L)
2101 return UnknownValue;
2102
2103 if (AddRec->isAffine()) {
2104 // If this is an affine expression the execution count of this branch is
2105 // equal to:
2106 //
2107 // (0 - Start/Step) iff Start % Step == 0
2108 //
2109 // Get the initial value for the loop.
2110 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002111 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002112 SCEVHandle Step = AddRec->getOperand(1);
2113
2114 Step = getSCEVAtScope(Step, L->getParentLoop());
2115
2116 // Figure out if Start % Step == 0.
2117 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2118 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2119 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002120 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002121 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2122 return Start; // 0 - Start/-1 == Start
2123
2124 // Check to see if Start is divisible by SC with no remainder.
2125 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2126 ConstantInt *StartCC = StartC->getValue();
2127 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2128 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
2129 if (Rem->isNullValue()) {
2130 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
2131 return SCEVUnknown::get(Result);
2132 }
2133 }
2134 }
2135 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2136 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2137 // the quadratic equation to solve it.
2138 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2139 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2140 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2141 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002142#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00002143 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2144 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002145#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002146 // Pick the smallest positive root value.
2147 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2148 if (ConstantBool *CB =
2149 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2150 R2->getValue()))) {
2151 if (CB != ConstantBool::True)
2152 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002153
Chris Lattner53e677a2004-04-02 20:23:17 +00002154 // We can only use this value if the chrec ends up with an exact zero
2155 // value at this index. When solving for "X*X != 5", for example, we
2156 // should not accept a root of 2.
2157 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2158 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2159 if (EvalVal->getValue()->isNullValue())
2160 return R1; // We found a quadratic root!
2161 }
2162 }
2163 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002164
Chris Lattner53e677a2004-04-02 20:23:17 +00002165 return UnknownValue;
2166}
2167
2168/// HowFarToNonZero - Return the number of times a backedge checking the
2169/// specified value for nonzero will execute. If not computable, return
2170/// UnknownValue
2171SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2172 // Loops that look like: while (X == 0) are very strange indeed. We don't
2173 // handle them yet except for the trivial case. This could be expanded in the
2174 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002175
Chris Lattner53e677a2004-04-02 20:23:17 +00002176 // If the value is a constant, check to see if it is known to be non-zero
2177 // already. If so, the backedge will execute zero times.
2178 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2179 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2180 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
2181 if (NonZero == ConstantBool::True)
2182 return getSCEV(Zero);
2183 return UnknownValue; // Otherwise it will loop infinitely.
2184 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002185
Chris Lattner53e677a2004-04-02 20:23:17 +00002186 // We could implement others, but I really doubt anyone writes loops like
2187 // this, and if they did, they would already be constant folded.
2188 return UnknownValue;
2189}
2190
Chris Lattnerdb25de42005-08-15 23:33:51 +00002191/// HowManyLessThans - Return the number of times a backedge containing the
2192/// specified less-than comparison will execute. If not computable, return
2193/// UnknownValue.
2194SCEVHandle ScalarEvolutionsImpl::
2195HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2196 // Only handle: "ADDREC < LoopInvariant".
2197 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2198
2199 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2200 if (!AddRec || AddRec->getLoop() != L)
2201 return UnknownValue;
2202
2203 if (AddRec->isAffine()) {
2204 // FORNOW: We only support unit strides.
2205 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2206 if (AddRec->getOperand(1) != One)
2207 return UnknownValue;
2208
2209 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2210 // know that m is >= n on input to the loop. If it is, the condition return
2211 // true zero times. What we really should return, for full generality, is
2212 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2213 // canonical loop form: most do-loops will have a check that dominates the
2214 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2215 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2216
2217 // Search for the check.
2218 BasicBlock *Preheader = L->getLoopPreheader();
2219 BasicBlock *PreheaderDest = L->getHeader();
2220 if (Preheader == 0) return UnknownValue;
2221
2222 BranchInst *LoopEntryPredicate =
2223 dyn_cast<BranchInst>(Preheader->getTerminator());
2224 if (!LoopEntryPredicate) return UnknownValue;
2225
2226 // This might be a critical edge broken out. If the loop preheader ends in
2227 // an unconditional branch to the loop, check to see if the preheader has a
2228 // single predecessor, and if so, look for its terminator.
2229 while (LoopEntryPredicate->isUnconditional()) {
2230 PreheaderDest = Preheader;
2231 Preheader = Preheader->getSinglePredecessor();
2232 if (!Preheader) return UnknownValue; // Multiple preds.
2233
2234 LoopEntryPredicate =
2235 dyn_cast<BranchInst>(Preheader->getTerminator());
2236 if (!LoopEntryPredicate) return UnknownValue;
2237 }
2238
2239 // Now that we found a conditional branch that dominates the loop, check to
2240 // see if it is the comparison we are looking for.
2241 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2242 if (!SCI) return UnknownValue;
2243 Value *PreCondLHS = SCI->getOperand(0);
2244 Value *PreCondRHS = SCI->getOperand(1);
2245 Instruction::BinaryOps Cond;
2246 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2247 Cond = SCI->getOpcode();
2248 else
2249 Cond = SCI->getInverseCondition();
2250
2251 switch (Cond) {
2252 case Instruction::SetGT:
2253 std::swap(PreCondLHS, PreCondRHS);
2254 Cond = Instruction::SetLT;
2255 // Fall Through.
2256 case Instruction::SetLT:
2257 if (PreCondLHS->getType()->isInteger() &&
2258 PreCondLHS->getType()->isSigned()) {
2259 if (RHS != getSCEV(PreCondRHS))
2260 return UnknownValue; // Not a comparison against 'm'.
2261
2262 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2263 != getSCEV(PreCondLHS))
2264 return UnknownValue; // Not a comparison against 'n-1'.
2265 break;
2266 } else {
2267 return UnknownValue;
2268 }
2269 default: break;
2270 }
2271
2272 //std::cerr << "Computed Loop Trip Count as: " <<
2273 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2274 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2275 }
2276
2277 return UnknownValue;
2278}
2279
Chris Lattner53e677a2004-04-02 20:23:17 +00002280/// getNumIterationsInRange - Return the number of iterations of this loop that
2281/// produce values in the specified constant range. Another way of looking at
2282/// this is that it returns the first iteration number where the value is not in
2283/// the condition, thus computing the exit count. If the iteration count can't
2284/// be computed, an instance of SCEVCouldNotCompute is returned.
2285SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2286 if (Range.isFullSet()) // Infinite loop.
2287 return new SCEVCouldNotCompute();
2288
2289 // If the start is a non-zero constant, shift the range to simplify things.
2290 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2291 if (!SC->getValue()->isNullValue()) {
2292 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002293 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002294 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2295 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2296 return ShiftedAddRec->getNumIterationsInRange(
2297 Range.subtract(SC->getValue()));
2298 // This is strange and shouldn't happen.
2299 return new SCEVCouldNotCompute();
2300 }
2301
2302 // The only time we can solve this is when we have all constant indices.
2303 // Otherwise, we cannot determine the overflow conditions.
2304 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2305 if (!isa<SCEVConstant>(getOperand(i)))
2306 return new SCEVCouldNotCompute();
2307
2308
2309 // Okay at this point we know that all elements of the chrec are constants and
2310 // that the start element is zero.
2311
2312 // First check to see if the range contains zero. If not, the first
2313 // iteration exits.
2314 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2315 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002316
Chris Lattner53e677a2004-04-02 20:23:17 +00002317 if (isAffine()) {
2318 // If this is an affine expression then we have this situation:
2319 // Solve {0,+,A} in Range === Ax in Range
2320
2321 // Since we know that zero is in the range, we know that the upper value of
2322 // the range must be the first possible exit value. Also note that we
2323 // already checked for a full range.
2324 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2325 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2326 ConstantInt *One = ConstantInt::get(getType(), 1);
2327
2328 // The exit value should be (Upper+A-1)/A.
2329 Constant *ExitValue = Upper;
2330 if (A != One) {
2331 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2332 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2333 }
2334 assert(isa<ConstantInt>(ExitValue) &&
2335 "Constant folding of integers not implemented?");
2336
2337 // Evaluate at the exit value. If we really did fall out of the valid
2338 // range, then we computed our trip count, otherwise wrap around or other
2339 // things must have happened.
2340 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2341 if (Range.contains(Val))
2342 return new SCEVCouldNotCompute(); // Something strange happened
2343
2344 // Ensure that the previous value is in the range. This is a sanity check.
2345 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2346 ConstantExpr::getSub(ExitValue, One))) &&
2347 "Linear scev computation is off in a bad way!");
2348 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2349 } else if (isQuadratic()) {
2350 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2351 // quadratic equation to solve it. To do this, we must frame our problem in
2352 // terms of figuring out when zero is crossed, instead of when
2353 // Range.getUpper() is crossed.
2354 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002355 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002356 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2357
2358 // Next, solve the constructed addrec
2359 std::pair<SCEVHandle,SCEVHandle> Roots =
2360 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2361 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2362 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2363 if (R1) {
2364 // Pick the smallest positive root value.
2365 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2366 if (ConstantBool *CB =
2367 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2368 R2->getValue()))) {
2369 if (CB != ConstantBool::True)
2370 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002371
Chris Lattner53e677a2004-04-02 20:23:17 +00002372 // Make sure the root is not off by one. The returned iteration should
2373 // not be in the range, but the previous one should be. When solving
2374 // for "X*X < 5", for example, we should not return a root of 2.
2375 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2376 R1->getValue());
2377 if (Range.contains(R1Val)) {
2378 // The next iteration must be out of the range...
2379 Constant *NextVal =
2380 ConstantExpr::getAdd(R1->getValue(),
2381 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002382
Chris Lattner53e677a2004-04-02 20:23:17 +00002383 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2384 if (!Range.contains(R1Val))
2385 return SCEVUnknown::get(NextVal);
2386 return new SCEVCouldNotCompute(); // Something strange happened
2387 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002388
Chris Lattner53e677a2004-04-02 20:23:17 +00002389 // If R1 was not in the range, then it is a good return value. Make
2390 // sure that R1-1 WAS in the range though, just in case.
2391 Constant *NextVal =
2392 ConstantExpr::getSub(R1->getValue(),
2393 ConstantInt::get(R1->getType(), 1));
2394 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2395 if (Range.contains(R1Val))
2396 return R1;
2397 return new SCEVCouldNotCompute(); // Something strange happened
2398 }
2399 }
2400 }
2401
2402 // Fallback, if this is a general polynomial, figure out the progression
2403 // through brute force: evaluate until we find an iteration that fails the
2404 // test. This is likely to be slow, but getting an accurate trip count is
2405 // incredibly important, we will be able to simplify the exit test a lot, and
2406 // we are almost guaranteed to get a trip count in this case.
2407 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2408 ConstantInt *One = ConstantInt::get(getType(), 1);
2409 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2410 do {
2411 ++NumBruteForceEvaluations;
2412 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2413 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2414 return new SCEVCouldNotCompute();
2415
2416 // Check to see if we found the value!
2417 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2418 return SCEVConstant::get(TestVal);
2419
2420 // Increment to test the next index.
2421 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2422 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002423
Chris Lattner53e677a2004-04-02 20:23:17 +00002424 return new SCEVCouldNotCompute();
2425}
2426
2427
2428
2429//===----------------------------------------------------------------------===//
2430// ScalarEvolution Class Implementation
2431//===----------------------------------------------------------------------===//
2432
2433bool ScalarEvolution::runOnFunction(Function &F) {
2434 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2435 return false;
2436}
2437
2438void ScalarEvolution::releaseMemory() {
2439 delete (ScalarEvolutionsImpl*)Impl;
2440 Impl = 0;
2441}
2442
2443void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2444 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002445 AU.addRequiredTransitive<LoopInfo>();
2446}
2447
2448SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2449 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2450}
2451
Chris Lattnera0740fb2005-08-09 23:36:33 +00002452/// hasSCEV - Return true if the SCEV for this value has already been
2453/// computed.
2454bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002455 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002456}
2457
2458
2459/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2460/// the specified value.
2461void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2462 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2463}
2464
2465
Chris Lattner53e677a2004-04-02 20:23:17 +00002466SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2467 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2468}
2469
2470bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2471 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2472}
2473
2474SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2475 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2476}
2477
2478void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2479 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2480}
2481
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002482static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002483 const Loop *L) {
2484 // Print all inner loops first
2485 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2486 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002487
Chris Lattner53e677a2004-04-02 20:23:17 +00002488 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002489
2490 std::vector<BasicBlock*> ExitBlocks;
2491 L->getExitBlocks(ExitBlocks);
2492 if (ExitBlocks.size() != 1)
Chris Lattner53e677a2004-04-02 20:23:17 +00002493 std::cerr << "<multiple exits> ";
2494
2495 if (SE->hasLoopInvariantIterationCount(L)) {
2496 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2497 } else {
2498 std::cerr << "Unpredictable iteration count. ";
2499 }
2500
2501 std::cerr << "\n";
2502}
2503
Reid Spencerce9653c2004-12-07 04:03:45 +00002504void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002505 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2506 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2507
2508 OS << "Classifying expressions for: " << F.getName() << "\n";
2509 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002510 if (I->getType()->isInteger()) {
2511 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002512 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002513 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002514 SV->print(OS);
2515 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002516
Chris Lattner6ffe5512004-04-27 15:13:33 +00002517 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002518 ConstantRange Bounds = SV->getValueRange();
2519 if (!Bounds.isFullSet())
2520 OS << "Bounds: " << Bounds << " ";
2521 }
2522
Chris Lattner6ffe5512004-04-27 15:13:33 +00002523 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002524 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002525 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002526 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2527 OS << "<<Unknown>>";
2528 } else {
2529 OS << *ExitValue;
2530 }
2531 }
2532
2533
2534 OS << "\n";
2535 }
2536
2537 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2538 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2539 PrintLoopInfo(OS, this, *I);
2540}
2541