blob: ec98adc9e249cd292dfa600d5a4ea01d7167eeeb [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 Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000083#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
98cl::opt<unsigned>
99MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Chris Lattner53e677a2004-04-02 20:23:17 +0000104namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +0000105 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +0000106 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +0000107}
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Chris Lattner53e677a2004-04-02 20:23:17 +0000116SCEV::~SCEV() {}
117void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000118 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000119}
120
121/// getValueRange - Return the tightest constant bounds that this value is
122/// known to have. This method is only valid on integer SCEV objects.
123ConstantRange SCEV::getValueRange() const {
124 const Type *Ty = getType();
125 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
126 Ty = Ty->getUnsignedVersion();
127 // Default to a full range if no better information is available.
128 return ConstantRange(getType());
129}
130
131
132SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
133
134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000136 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000141 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000142}
143
144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
Chris Lattner4dc534c2005-02-13 04:37:18 +0000149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
151 const SCEVHandle &Conc) const {
152 return this;
153}
154
Chris Lattner53e677a2004-04-02 20:23:17 +0000155void SCEVCouldNotCompute::print(std::ostream &OS) const {
156 OS << "***COULDNOTCOMPUTE***";
157}
158
159bool SCEVCouldNotCompute::classof(const SCEV *S) {
160 return S->getSCEVType() == scCouldNotCompute;
161}
162
163
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000164// SCEVConstants - Only allow the creation of one SCEVConstant for any
165// particular value. Don't use a SCEVHandle here, or else the object will
166// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000167static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000168
Chris Lattner53e677a2004-04-02 20:23:17 +0000169
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000170SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000171 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000172}
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000174SCEVHandle SCEVConstant::get(ConstantInt *V) {
175 // Make sure that SCEVConstant instances are all unsigned.
Reid Spencer2e20d392006-12-21 06:43:46 +0000176 // FIXME:Signless. This entire if statement can be removed when integer types
177 // are signless. There won't be a need to bitcast then.
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178 if (V->getType()->isSigned()) {
179 const Type *NewTy = V->getType()->getUnsignedVersion();
Reid Spencer14bab5d2006-12-04 17:05:42 +0000180 V = cast<ConstantInt>(
Reid Spencer7858b332006-12-05 19:14:13 +0000181 ConstantExpr::getBitCast(V, NewTy));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000182 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000183
Chris Lattnerb3364092006-10-04 21:49:37 +0000184 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185 if (R == 0) R = new SCEVConstant(V);
186 return R;
187}
Chris Lattner53e677a2004-04-02 20:23:17 +0000188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189ConstantRange SCEVConstant::getValueRange() const {
190 return ConstantRange(V);
191}
Chris Lattner53e677a2004-04-02 20:23:17 +0000192
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195void SCEVConstant::print(std::ostream &OS) const {
196 WriteAsOperand(OS, V, false);
197}
Chris Lattner53e677a2004-04-02 20:23:17 +0000198
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
200// particular input. Don't use a SCEVHandle here, or else the object will
201// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000202static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
203 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000204
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
206 : SCEV(scTruncate), Op(op), Ty(ty) {
207 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000208 "Cannot truncate non-integer value!");
209 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
210 "This is not a truncating conversion!");
211}
Chris Lattner53e677a2004-04-02 20:23:17 +0000212
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000214 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215}
Chris Lattner53e677a2004-04-02 20:23:17 +0000216
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217ConstantRange SCEVTruncateExpr::getValueRange() const {
218 return getOperand()->getValueRange().truncate(getType());
219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221void SCEVTruncateExpr::print(std::ostream &OS) const {
222 OS << "(truncate " << *Op << " to " << *Ty << ")";
223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000232 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234 "Cannot zero extend non-integer value!");
235 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
236 "This is not an extending conversion!");
237}
238
239SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000240 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000241}
242
243ConstantRange SCEVZeroExtendExpr::getValueRange() const {
244 return getOperand()->getValueRange().zeroExtend(getType());
245}
246
247void SCEVZeroExtendExpr::print(std::ostream &OS) const {
248 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
249}
250
251// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
252// particular input. Don't use a SCEVHandle here, or else the object will never
253// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000254static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
255 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000256
257SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000258 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
259 std::vector<SCEV*>(Operands.begin(),
260 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000261}
262
263void SCEVCommutativeExpr::print(std::ostream &OS) const {
264 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
265 const char *OpStr = getOperationStr();
266 OS << "(" << *Operands[0];
267 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
268 OS << OpStr << *Operands[i];
269 OS << ")";
270}
271
Chris Lattner4dc534c2005-02-13 04:37:18 +0000272SCEVHandle SCEVCommutativeExpr::
273replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
274 const SCEVHandle &Conc) const {
275 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
276 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
277 if (H != getOperand(i)) {
278 std::vector<SCEVHandle> NewOps;
279 NewOps.reserve(getNumOperands());
280 for (unsigned j = 0; j != i; ++j)
281 NewOps.push_back(getOperand(j));
282 NewOps.push_back(H);
283 for (++i; i != e; ++i)
284 NewOps.push_back(getOperand(i)->
285 replaceSymbolicValuesWithConcrete(Sym, Conc));
286
287 if (isa<SCEVAddExpr>(this))
288 return SCEVAddExpr::get(NewOps);
289 else if (isa<SCEVMulExpr>(this))
290 return SCEVMulExpr::get(NewOps);
291 else
292 assert(0 && "Unknown commutative expr!");
293 }
294 }
295 return this;
296}
297
298
Chris Lattner60a05cc2006-04-01 04:48:52 +0000299// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000300// input. Don't use a SCEVHandle here, or else the object will never be
301// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000302static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
303 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000304
Chris Lattner60a05cc2006-04-01 04:48:52 +0000305SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000306 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000307}
308
Chris Lattner60a05cc2006-04-01 04:48:52 +0000309void SCEVSDivExpr::print(std::ostream &OS) const {
310 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000311}
312
Chris Lattner60a05cc2006-04-01 04:48:52 +0000313const Type *SCEVSDivExpr::getType() const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314 const Type *Ty = LHS->getType();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000315 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000316 return Ty;
317}
318
319// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
320// particular input. Don't use a SCEVHandle here, or else the object will never
321// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000322static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
323 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000324
325SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000326 SCEVAddRecExprs->erase(std::make_pair(L,
327 std::vector<SCEV*>(Operands.begin(),
328 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000329}
330
Chris Lattner4dc534c2005-02-13 04:37:18 +0000331SCEVHandle SCEVAddRecExpr::
332replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
333 const SCEVHandle &Conc) const {
334 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
335 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
336 if (H != getOperand(i)) {
337 std::vector<SCEVHandle> NewOps;
338 NewOps.reserve(getNumOperands());
339 for (unsigned j = 0; j != i; ++j)
340 NewOps.push_back(getOperand(j));
341 NewOps.push_back(H);
342 for (++i; i != e; ++i)
343 NewOps.push_back(getOperand(i)->
344 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000345
Chris Lattner4dc534c2005-02-13 04:37:18 +0000346 return get(NewOps, L);
347 }
348 }
349 return this;
350}
351
352
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000353bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
354 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000355 // contain L and if the start is invariant.
356 return !QueryLoop->contains(L->getHeader()) &&
357 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000358}
359
360
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361void SCEVAddRecExpr::print(std::ostream &OS) const {
362 OS << "{" << *Operands[0];
363 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
364 OS << ",+," << *Operands[i];
365 OS << "}<" << L->getHeader()->getName() + ">";
366}
Chris Lattner53e677a2004-04-02 20:23:17 +0000367
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000368// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
369// value. Don't use a SCEVHandle here, or else the object will never be
370// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000371static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000372
Chris Lattnerb3364092006-10-04 21:49:37 +0000373SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000374
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
376 // All non-instruction values are loop invariant. All instructions are loop
377 // invariant if they are not contained in the specified loop.
378 if (Instruction *I = dyn_cast<Instruction>(V))
379 return !L->contains(I->getParent());
380 return true;
381}
Chris Lattner53e677a2004-04-02 20:23:17 +0000382
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000383const Type *SCEVUnknown::getType() const {
384 return V->getType();
385}
Chris Lattner53e677a2004-04-02 20:23:17 +0000386
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000387void SCEVUnknown::print(std::ostream &OS) const {
388 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000389}
390
Chris Lattner8d741b82004-06-20 06:23:15 +0000391//===----------------------------------------------------------------------===//
392// SCEV Utilities
393//===----------------------------------------------------------------------===//
394
395namespace {
396 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
397 /// than the complexity of the RHS. This comparator is used to canonicalize
398 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000399 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000400 bool operator()(SCEV *LHS, SCEV *RHS) {
401 return LHS->getSCEVType() < RHS->getSCEVType();
402 }
403 };
404}
405
406/// GroupByComplexity - Given a list of SCEV objects, order them by their
407/// complexity, and group objects of the same complexity together by value.
408/// When this routine is finished, we know that any duplicates in the vector are
409/// consecutive and that complexity is monotonically increasing.
410///
411/// Note that we go take special precautions to ensure that we get determinstic
412/// results from this routine. In other words, we don't want the results of
413/// this to depend on where the addresses of various SCEV objects happened to
414/// land in memory.
415///
416static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
417 if (Ops.size() < 2) return; // Noop
418 if (Ops.size() == 2) {
419 // This is the common case, which also happens to be trivially simple.
420 // Special case it.
421 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
422 std::swap(Ops[0], Ops[1]);
423 return;
424 }
425
426 // Do the rough sort by complexity.
427 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
428
429 // Now that we are sorted by complexity, group elements of the same
430 // complexity. Note that this is, at worst, N^2, but the vector is likely to
431 // be extremely short in practice. Note that we take this approach because we
432 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000433 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000434 SCEV *S = Ops[i];
435 unsigned Complexity = S->getSCEVType();
436
437 // If there are any objects of the same complexity and same value as this
438 // one, group them.
439 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
440 if (Ops[j] == S) { // Found a duplicate.
441 // Move it to immediately after i'th element.
442 std::swap(Ops[i+1], Ops[j]);
443 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000444 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000445 }
446 }
447 }
448}
449
Chris Lattner53e677a2004-04-02 20:23:17 +0000450
Chris Lattner53e677a2004-04-02 20:23:17 +0000451
452//===----------------------------------------------------------------------===//
453// Simple SCEV method implementations
454//===----------------------------------------------------------------------===//
455
456/// getIntegerSCEV - Given an integer or FP type, create a constant for the
457/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000458SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000459 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000460 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000461 C = Constant::getNullValue(Ty);
462 else if (Ty->isFloatingPoint())
463 C = ConstantFP::get(Ty, Val);
Reid Spencer2e20d392006-12-21 06:43:46 +0000464 /// FIXME:Signless. when integer types are signless, just change this to:
465 /// else
466 /// C = ConstantInt::get(Ty, Val);
467 else if (Ty->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +0000468 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000469 else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000470 C = ConstantInt::get(Ty->getSignedVersion(), Val);
Reid Spencer7858b332006-12-05 19:14:13 +0000471 C = ConstantExpr::getBitCast(C, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000472 }
473 return SCEVUnknown::get(C);
474}
475
476/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
477/// input value to the specified type. If the type must be extended, it is zero
478/// extended.
479static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
480 const Type *SrcTy = V->getType();
481 assert(SrcTy->isInteger() && Ty->isInteger() &&
482 "Cannot truncate or zero extend with non-integer arguments!");
483 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
484 return V; // No conversion
485 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
486 return SCEVTruncateExpr::get(V, Ty);
487 return SCEVZeroExtendExpr::get(V, Ty);
488}
489
490/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
491///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000492SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000493 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
494 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000495
Chris Lattnerb06432c2004-04-23 21:29:03 +0000496 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000497}
498
499/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
500///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000501SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000502 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000503 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000504}
505
506
Chris Lattner53e677a2004-04-02 20:23:17 +0000507/// PartialFact - Compute V!/(V-NumSteps)!
508static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
509 // Handle this case efficiently, it is common to have constant iteration
510 // counts while computing loop exit values.
511 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000512 uint64_t Val = SC->getValue()->getZExtValue();
Chris Lattner53e677a2004-04-02 20:23:17 +0000513 uint64_t Result = 1;
514 for (; NumSteps; --NumSteps)
515 Result *= Val-(NumSteps-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000516 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
Reid Spencer14bab5d2006-12-04 17:05:42 +0000517 return SCEVUnknown::get(
Reid Spencer7858b332006-12-05 19:14:13 +0000518 ConstantExpr::getTruncOrBitCast(Res, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000519 }
520
521 const Type *Ty = V->getType();
522 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000523 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000524
Chris Lattner53e677a2004-04-02 20:23:17 +0000525 SCEVHandle Result = V;
526 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000527 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000528 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000529 return Result;
530}
531
532
533/// evaluateAtIteration - Return the value of this chain of recurrences at
534/// the specified iteration number. We can evaluate this recurrence by
535/// multiplying each element in the chain by the binomial coefficient
536/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
537///
538/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
539///
540/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
541/// Is the binomial equation safe using modular arithmetic??
542///
543SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
544 SCEVHandle Result = getStart();
545 int Divisor = 1;
546 const Type *Ty = It->getType();
547 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
548 SCEVHandle BC = PartialFact(It, i);
549 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000550 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000551 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000552 Result = SCEVAddExpr::get(Result, Val);
553 }
554 return Result;
555}
556
557
558//===----------------------------------------------------------------------===//
559// SCEV Expression folder implementations
560//===----------------------------------------------------------------------===//
561
562SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
563 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000564 return SCEVUnknown::get(
Reid Spencer315d0552006-12-05 22:39:58 +0000565 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000566
567 // If the input value is a chrec scev made out of constants, truncate
568 // all of the constants.
569 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
570 std::vector<SCEVHandle> Operands;
571 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
572 // FIXME: This should allow truncation of other expression types!
573 if (isa<SCEVConstant>(AddRec->getOperand(i)))
574 Operands.push_back(get(AddRec->getOperand(i), Ty));
575 else
576 break;
577 if (Operands.size() == AddRec->getNumOperands())
578 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
579 }
580
Chris Lattnerb3364092006-10-04 21:49:37 +0000581 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000582 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
583 return Result;
584}
585
586SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
587 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000588 return SCEVUnknown::get(
Reid Spencerd977d862006-12-12 23:36:14 +0000589 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000590
591 // FIXME: If the input value is a chrec scev, and we can prove that the value
592 // did not overflow the old, smaller, value, we can zero extend all of the
593 // operands (often constants). This would allow analysis of something like
594 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
595
Chris Lattnerb3364092006-10-04 21:49:37 +0000596 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000597 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
598 return Result;
599}
600
601// get - Get a canonical add expression, or something simpler if possible.
602SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
603 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000604 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000605
606 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000607 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000608
609 // If there are any constants, fold them together.
610 unsigned Idx = 0;
611 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
612 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000613 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000614 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
615 // We found two constants, fold them together!
616 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
617 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
618 Ops[0] = SCEVConstant::get(CI);
619 Ops.erase(Ops.begin()+1); // Erase the folded element
620 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000621 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000622 } else {
623 // If we couldn't fold the expression, move to the next constant. Note
624 // that this is impossible to happen in practice because we always
625 // constant fold constant ints to constant ints.
626 ++Idx;
627 }
628 }
629
630 // If we are left with a constant zero being added, strip it off.
631 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
632 Ops.erase(Ops.begin());
633 --Idx;
634 }
635 }
636
Chris Lattner627018b2004-04-07 16:16:11 +0000637 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000638
Chris Lattner53e677a2004-04-02 20:23:17 +0000639 // Okay, check to see if the same value occurs in the operand list twice. If
640 // so, merge them together into an multiply expression. Since we sorted the
641 // list, these values are required to be adjacent.
642 const Type *Ty = Ops[0]->getType();
643 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
644 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
645 // Found a match, merge the two values into a multiply, and add any
646 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000647 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000648 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
649 if (Ops.size() == 2)
650 return Mul;
651 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
652 Ops.push_back(Mul);
653 return SCEVAddExpr::get(Ops);
654 }
655
656 // Okay, now we know the first non-constant operand. If there are add
657 // operands they would be next.
658 if (Idx < Ops.size()) {
659 bool DeletedAdd = false;
660 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
661 // If we have an add, expand the add operands onto the end of the operands
662 // list.
663 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
664 Ops.erase(Ops.begin()+Idx);
665 DeletedAdd = true;
666 }
667
668 // If we deleted at least one add, we added operands to the end of the list,
669 // and they are not necessarily sorted. Recurse to resort and resimplify
670 // any operands we just aquired.
671 if (DeletedAdd)
672 return get(Ops);
673 }
674
675 // Skip over the add expression until we get to a multiply.
676 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
677 ++Idx;
678
679 // If we are adding something to a multiply expression, make sure the
680 // something is not already an operand of the multiply. If so, merge it into
681 // the multiply.
682 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
683 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
684 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
685 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
686 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000687 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000688 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
689 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
690 if (Mul->getNumOperands() != 2) {
691 // If the multiply has more than two operands, we must get the
692 // Y*Z term.
693 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
694 MulOps.erase(MulOps.begin()+MulOp);
695 InnerMul = SCEVMulExpr::get(MulOps);
696 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000697 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000698 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
699 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
700 if (Ops.size() == 2) return OuterMul;
701 if (AddOp < Idx) {
702 Ops.erase(Ops.begin()+AddOp);
703 Ops.erase(Ops.begin()+Idx-1);
704 } else {
705 Ops.erase(Ops.begin()+Idx);
706 Ops.erase(Ops.begin()+AddOp-1);
707 }
708 Ops.push_back(OuterMul);
709 return SCEVAddExpr::get(Ops);
710 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000711
Chris Lattner53e677a2004-04-02 20:23:17 +0000712 // Check this multiply against other multiplies being added together.
713 for (unsigned OtherMulIdx = Idx+1;
714 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
715 ++OtherMulIdx) {
716 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
717 // If MulOp occurs in OtherMul, we can fold the two multiplies
718 // together.
719 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
720 OMulOp != e; ++OMulOp)
721 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
722 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
723 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
724 if (Mul->getNumOperands() != 2) {
725 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
726 MulOps.erase(MulOps.begin()+MulOp);
727 InnerMul1 = SCEVMulExpr::get(MulOps);
728 }
729 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
730 if (OtherMul->getNumOperands() != 2) {
731 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
732 OtherMul->op_end());
733 MulOps.erase(MulOps.begin()+OMulOp);
734 InnerMul2 = SCEVMulExpr::get(MulOps);
735 }
736 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
737 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
738 if (Ops.size() == 2) return OuterMul;
739 Ops.erase(Ops.begin()+Idx);
740 Ops.erase(Ops.begin()+OtherMulIdx-1);
741 Ops.push_back(OuterMul);
742 return SCEVAddExpr::get(Ops);
743 }
744 }
745 }
746 }
747
748 // If there are any add recurrences in the operands list, see if any other
749 // added values are loop invariant. If so, we can fold them into the
750 // recurrence.
751 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
752 ++Idx;
753
754 // Scan over all recurrences, trying to fold loop invariants into them.
755 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
756 // Scan all of the other operands to this add and add them to the vector if
757 // they are loop invariant w.r.t. the recurrence.
758 std::vector<SCEVHandle> LIOps;
759 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
760 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
761 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
762 LIOps.push_back(Ops[i]);
763 Ops.erase(Ops.begin()+i);
764 --i; --e;
765 }
766
767 // If we found some loop invariants, fold them into the recurrence.
768 if (!LIOps.empty()) {
769 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
770 LIOps.push_back(AddRec->getStart());
771
772 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
773 AddRecOps[0] = SCEVAddExpr::get(LIOps);
774
775 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
776 // If all of the other operands were loop invariant, we are done.
777 if (Ops.size() == 1) return NewRec;
778
779 // Otherwise, add the folded AddRec by the non-liv parts.
780 for (unsigned i = 0;; ++i)
781 if (Ops[i] == AddRec) {
782 Ops[i] = NewRec;
783 break;
784 }
785 return SCEVAddExpr::get(Ops);
786 }
787
788 // Okay, if there weren't any loop invariants to be folded, check to see if
789 // there are multiple AddRec's with the same loop induction variable being
790 // added together. If so, we can fold them.
791 for (unsigned OtherIdx = Idx+1;
792 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
793 if (OtherIdx != Idx) {
794 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
795 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
796 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
797 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
798 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
799 if (i >= NewOps.size()) {
800 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
801 OtherAddRec->op_end());
802 break;
803 }
804 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
805 }
806 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
807
808 if (Ops.size() == 2) return NewAddRec;
809
810 Ops.erase(Ops.begin()+Idx);
811 Ops.erase(Ops.begin()+OtherIdx-1);
812 Ops.push_back(NewAddRec);
813 return SCEVAddExpr::get(Ops);
814 }
815 }
816
817 // Otherwise couldn't fold anything into this recurrence. Move onto the
818 // next one.
819 }
820
821 // Okay, it looks like we really DO need an add expr. Check to see if we
822 // already have one, otherwise create a new one.
823 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000824 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
825 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000826 if (Result == 0) Result = new SCEVAddExpr(Ops);
827 return Result;
828}
829
830
831SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
832 assert(!Ops.empty() && "Cannot get empty mul!");
833
834 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000835 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000836
837 // If there are any constants, fold them together.
838 unsigned Idx = 0;
839 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
840
841 // C1*(C2+V) -> C1*C2 + C1*V
842 if (Ops.size() == 2)
843 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
844 if (Add->getNumOperands() == 2 &&
845 isa<SCEVConstant>(Add->getOperand(0)))
846 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
847 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
848
849
850 ++Idx;
851 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
852 // We found two constants, fold them together!
853 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
854 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
855 Ops[0] = SCEVConstant::get(CI);
856 Ops.erase(Ops.begin()+1); // Erase the folded element
857 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000858 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000859 } else {
860 // If we couldn't fold the expression, move to the next constant. Note
861 // that this is impossible to happen in practice because we always
862 // constant fold constant ints to constant ints.
863 ++Idx;
864 }
865 }
866
867 // If we are left with a constant one being multiplied, strip it off.
868 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
869 Ops.erase(Ops.begin());
870 --Idx;
871 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
872 // If we have a multiply of zero, it will always be zero.
873 return Ops[0];
874 }
875 }
876
877 // Skip over the add expression until we get to a multiply.
878 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
879 ++Idx;
880
881 if (Ops.size() == 1)
882 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000883
Chris Lattner53e677a2004-04-02 20:23:17 +0000884 // If there are mul operands inline them all into this expression.
885 if (Idx < Ops.size()) {
886 bool DeletedMul = false;
887 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
888 // If we have an mul, expand the mul operands onto the end of the operands
889 // list.
890 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
891 Ops.erase(Ops.begin()+Idx);
892 DeletedMul = true;
893 }
894
895 // If we deleted at least one mul, we added operands to the end of the list,
896 // and they are not necessarily sorted. Recurse to resort and resimplify
897 // any operands we just aquired.
898 if (DeletedMul)
899 return get(Ops);
900 }
901
902 // If there are any add recurrences in the operands list, see if any other
903 // added values are loop invariant. If so, we can fold them into the
904 // recurrence.
905 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
906 ++Idx;
907
908 // Scan over all recurrences, trying to fold loop invariants into them.
909 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
910 // Scan all of the other operands to this mul and add them to the vector if
911 // they are loop invariant w.r.t. the recurrence.
912 std::vector<SCEVHandle> LIOps;
913 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
914 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
915 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
916 LIOps.push_back(Ops[i]);
917 Ops.erase(Ops.begin()+i);
918 --i; --e;
919 }
920
921 // If we found some loop invariants, fold them into the recurrence.
922 if (!LIOps.empty()) {
923 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
924 std::vector<SCEVHandle> NewOps;
925 NewOps.reserve(AddRec->getNumOperands());
926 if (LIOps.size() == 1) {
927 SCEV *Scale = LIOps[0];
928 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
929 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
930 } else {
931 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
932 std::vector<SCEVHandle> MulOps(LIOps);
933 MulOps.push_back(AddRec->getOperand(i));
934 NewOps.push_back(SCEVMulExpr::get(MulOps));
935 }
936 }
937
938 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
939
940 // If all of the other operands were loop invariant, we are done.
941 if (Ops.size() == 1) return NewRec;
942
943 // Otherwise, multiply the folded AddRec by the non-liv parts.
944 for (unsigned i = 0;; ++i)
945 if (Ops[i] == AddRec) {
946 Ops[i] = NewRec;
947 break;
948 }
949 return SCEVMulExpr::get(Ops);
950 }
951
952 // Okay, if there weren't any loop invariants to be folded, check to see if
953 // there are multiple AddRec's with the same loop induction variable being
954 // multiplied together. If so, we can fold them.
955 for (unsigned OtherIdx = Idx+1;
956 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
957 if (OtherIdx != Idx) {
958 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
959 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
960 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
961 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
962 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
963 G->getStart());
964 SCEVHandle B = F->getStepRecurrence();
965 SCEVHandle D = G->getStepRecurrence();
966 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
967 SCEVMulExpr::get(G, B),
968 SCEVMulExpr::get(B, D));
969 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
970 F->getLoop());
971 if (Ops.size() == 2) return NewAddRec;
972
973 Ops.erase(Ops.begin()+Idx);
974 Ops.erase(Ops.begin()+OtherIdx-1);
975 Ops.push_back(NewAddRec);
976 return SCEVMulExpr::get(Ops);
977 }
978 }
979
980 // Otherwise couldn't fold anything into this recurrence. Move onto the
981 // next one.
982 }
983
984 // Okay, it looks like we really DO need an mul expr. Check to see if we
985 // already have one, otherwise create a new one.
986 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000987 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
988 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000989 if (Result == 0)
990 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000991 return Result;
992}
993
Chris Lattner60a05cc2006-04-01 04:48:52 +0000994SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000995 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
996 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000997 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000998 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000999 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +00001000
1001 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1002 Constant *LHSCV = LHSC->getValue();
1003 Constant *RHSCV = RHSC->getValue();
Reid Spencer1628cec2006-10-26 06:15:43 +00001004 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001005 }
1006 }
1007
1008 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1009
Chris Lattnerb3364092006-10-04 21:49:37 +00001010 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001011 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001012 return Result;
1013}
1014
1015
1016/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1017/// specified loop. Simplify the expression as much as possible.
1018SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1019 const SCEVHandle &Step, const Loop *L) {
1020 std::vector<SCEVHandle> Operands;
1021 Operands.push_back(Start);
1022 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1023 if (StepChrec->getLoop() == L) {
1024 Operands.insert(Operands.end(), StepChrec->op_begin(),
1025 StepChrec->op_end());
1026 return get(Operands, L);
1027 }
1028
1029 Operands.push_back(Step);
1030 return get(Operands, L);
1031}
1032
1033/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1034/// specified loop. Simplify the expression as much as possible.
1035SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1036 const Loop *L) {
1037 if (Operands.size() == 1) return Operands[0];
1038
1039 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1040 if (StepC->getValue()->isNullValue()) {
1041 Operands.pop_back();
1042 return get(Operands, L); // { X,+,0 } --> X
1043 }
1044
1045 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001046 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1047 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001048 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1049 return Result;
1050}
1051
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001052SCEVHandle SCEVUnknown::get(Value *V) {
1053 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1054 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001055 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001056 if (Result == 0) Result = new SCEVUnknown(V);
1057 return Result;
1058}
1059
Chris Lattner53e677a2004-04-02 20:23:17 +00001060
1061//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001062// ScalarEvolutionsImpl Definition and Implementation
1063//===----------------------------------------------------------------------===//
1064//
1065/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1066/// evolution code.
1067///
1068namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001069 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001070 /// F - The function we are analyzing.
1071 ///
1072 Function &F;
1073
1074 /// LI - The loop information for the function we are currently analyzing.
1075 ///
1076 LoopInfo &LI;
1077
1078 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1079 /// things.
1080 SCEVHandle UnknownValue;
1081
1082 /// Scalars - This is a cache of the scalars we have analyzed so far.
1083 ///
1084 std::map<Value*, SCEVHandle> Scalars;
1085
1086 /// IterationCounts - Cache the iteration count of the loops for this
1087 /// function as they are computed.
1088 std::map<const Loop*, SCEVHandle> IterationCounts;
1089
Chris Lattner3221ad02004-04-17 22:58:41 +00001090 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1091 /// the PHI instructions that we attempt to compute constant evolutions for.
1092 /// This allows us to avoid potentially expensive recomputation of these
1093 /// properties. An instruction maps to null if we are unable to compute its
1094 /// exit value.
1095 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001096
Chris Lattner53e677a2004-04-02 20:23:17 +00001097 public:
1098 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1099 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1100
1101 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1102 /// expression and create a new one.
1103 SCEVHandle getSCEV(Value *V);
1104
Chris Lattnera0740fb2005-08-09 23:36:33 +00001105 /// hasSCEV - Return true if the SCEV for this value has already been
1106 /// computed.
1107 bool hasSCEV(Value *V) const {
1108 return Scalars.count(V);
1109 }
1110
1111 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1112 /// the specified value.
1113 void setSCEV(Value *V, const SCEVHandle &H) {
1114 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1115 assert(isNew && "This entry already existed!");
1116 }
1117
1118
Chris Lattner53e677a2004-04-02 20:23:17 +00001119 /// getSCEVAtScope - Compute the value of the specified expression within
1120 /// the indicated loop (which may be null to indicate in no loop). If the
1121 /// expression cannot be evaluated, return UnknownValue itself.
1122 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1123
1124
1125 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1126 /// an analyzable loop-invariant iteration count.
1127 bool hasLoopInvariantIterationCount(const Loop *L);
1128
1129 /// getIterationCount - If the specified loop has a predictable iteration
1130 /// count, return it. Note that it is not valid to call this method on a
1131 /// loop without a loop-invariant iteration count.
1132 SCEVHandle getIterationCount(const Loop *L);
1133
1134 /// deleteInstructionFromRecords - This method should be called by the
1135 /// client before it removes an instruction from the program, to make sure
1136 /// that no dangling references are left around.
1137 void deleteInstructionFromRecords(Instruction *I);
1138
1139 private:
1140 /// createSCEV - We know that there is no SCEV for the specified value.
1141 /// Analyze the expression.
1142 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001143
1144 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1145 /// SCEVs.
1146 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001147
1148 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1149 /// for the specified instruction and replaces any references to the
1150 /// symbolic value SymName with the specified value. This is used during
1151 /// PHI resolution.
1152 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1153 const SCEVHandle &SymName,
1154 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001155
1156 /// ComputeIterationCount - Compute the number of times the specified loop
1157 /// will iterate.
1158 SCEVHandle ComputeIterationCount(const Loop *L);
1159
Chris Lattner673e02b2004-10-12 01:49:27 +00001160 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1161 /// 'setcc load X, cst', try to se if we can compute the trip count.
1162 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1163 Constant *RHS,
1164 const Loop *L,
1165 unsigned SetCCOpcode);
1166
Chris Lattner7980fb92004-04-17 18:36:24 +00001167 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1168 /// constant number of times (the condition evolves only from constants),
1169 /// try to evaluate a few iterations of the loop until we get the exit
1170 /// condition gets a value of ExitWhen (true or false). If we cannot
1171 /// evaluate the trip count of the loop, return UnknownValue.
1172 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1173 bool ExitWhen);
1174
Chris Lattner53e677a2004-04-02 20:23:17 +00001175 /// HowFarToZero - Return the number of times a backedge comparing the
1176 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001177 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001178 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1179
1180 /// HowFarToNonZero - Return the number of times a backedge checking the
1181 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001182 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001183 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001184
Chris Lattnerdb25de42005-08-15 23:33:51 +00001185 /// HowManyLessThans - Return the number of times a backedge containing the
1186 /// specified less-than comparison will execute. If not computable, return
1187 /// UnknownValue.
1188 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1189
Chris Lattner3221ad02004-04-17 22:58:41 +00001190 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1191 /// in the header of its containing loop, we know the loop executes a
1192 /// constant number of times, and the PHI node is just a recurrence
1193 /// involving constants, fold it.
1194 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1195 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001196 };
1197}
1198
1199//===----------------------------------------------------------------------===//
1200// Basic SCEV Analysis and PHI Idiom Recognition Code
1201//
1202
1203/// deleteInstructionFromRecords - This method should be called by the
1204/// client before it removes an instruction from the program, to make sure
1205/// that no dangling references are left around.
1206void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1207 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001208 if (PHINode *PN = dyn_cast<PHINode>(I))
1209 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001210}
1211
1212
1213/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1214/// expression and create a new one.
1215SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1216 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1217
1218 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1219 if (I != Scalars.end()) return I->second;
1220 SCEVHandle S = createSCEV(V);
1221 Scalars.insert(std::make_pair(V, S));
1222 return S;
1223}
1224
Chris Lattner4dc534c2005-02-13 04:37:18 +00001225/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1226/// the specified instruction and replaces any references to the symbolic value
1227/// SymName with the specified value. This is used during PHI resolution.
1228void ScalarEvolutionsImpl::
1229ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1230 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001231 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001232 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001233
Chris Lattner4dc534c2005-02-13 04:37:18 +00001234 SCEVHandle NV =
1235 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1236 if (NV == SI->second) return; // No change.
1237
1238 SI->second = NV; // Update the scalars map!
1239
1240 // Any instruction values that use this instruction might also need to be
1241 // updated!
1242 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1243 UI != E; ++UI)
1244 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1245}
Chris Lattner53e677a2004-04-02 20:23:17 +00001246
1247/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1248/// a loop header, making it a potential recurrence, or it doesn't.
1249///
1250SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1251 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1252 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1253 if (L->getHeader() == PN->getParent()) {
1254 // If it lives in the loop header, it has two incoming values, one
1255 // from outside the loop, and one from inside.
1256 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1257 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001258
Chris Lattner53e677a2004-04-02 20:23:17 +00001259 // While we are analyzing this PHI node, handle its value symbolically.
1260 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1261 assert(Scalars.find(PN) == Scalars.end() &&
1262 "PHI node already processed?");
1263 Scalars.insert(std::make_pair(PN, SymbolicName));
1264
1265 // Using this symbolic name for the PHI, analyze the value coming around
1266 // the back-edge.
1267 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1268
1269 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1270 // has a special value for the first iteration of the loop.
1271
1272 // If the value coming around the backedge is an add with the symbolic
1273 // value we just inserted, then we found a simple induction variable!
1274 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1275 // If there is a single occurrence of the symbolic value, replace it
1276 // with a recurrence.
1277 unsigned FoundIndex = Add->getNumOperands();
1278 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1279 if (Add->getOperand(i) == SymbolicName)
1280 if (FoundIndex == e) {
1281 FoundIndex = i;
1282 break;
1283 }
1284
1285 if (FoundIndex != Add->getNumOperands()) {
1286 // Create an add with everything but the specified operand.
1287 std::vector<SCEVHandle> Ops;
1288 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1289 if (i != FoundIndex)
1290 Ops.push_back(Add->getOperand(i));
1291 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1292
1293 // This is not a valid addrec if the step amount is varying each
1294 // loop iteration, but is not itself an addrec in this loop.
1295 if (Accum->isLoopInvariant(L) ||
1296 (isa<SCEVAddRecExpr>(Accum) &&
1297 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1298 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1299 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1300
1301 // Okay, for the entire analysis of this edge we assumed the PHI
1302 // to be symbolic. We now need to go back and update all of the
1303 // entries for the scalars that use the PHI (except for the PHI
1304 // itself) to use the new analyzed value instead of the "symbolic"
1305 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001306 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001307 return PHISCEV;
1308 }
1309 }
Chris Lattner97156e72006-04-26 18:34:07 +00001310 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1311 // Otherwise, this could be a loop like this:
1312 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1313 // In this case, j = {1,+,1} and BEValue is j.
1314 // Because the other in-value of i (0) fits the evolution of BEValue
1315 // i really is an addrec evolution.
1316 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1317 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1318
1319 // If StartVal = j.start - j.stride, we can use StartVal as the
1320 // initial step of the addrec evolution.
1321 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1322 AddRec->getOperand(1))) {
1323 SCEVHandle PHISCEV =
1324 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1325
1326 // Okay, for the entire analysis of this edge we assumed the PHI
1327 // to be symbolic. We now need to go back and update all of the
1328 // entries for the scalars that use the PHI (except for the PHI
1329 // itself) to use the new analyzed value instead of the "symbolic"
1330 // value.
1331 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1332 return PHISCEV;
1333 }
1334 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001335 }
1336
1337 return SymbolicName;
1338 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001339
Chris Lattner53e677a2004-04-02 20:23:17 +00001340 // If it's not a loop phi, we can't handle it yet.
1341 return SCEVUnknown::get(PN);
1342}
1343
Chris Lattnera17f0392006-12-12 02:26:09 +00001344/// GetConstantFactor - Determine the largest constant factor that S has. For
1345/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
1346static uint64_t GetConstantFactor(SCEVHandle S) {
1347 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1348 if (uint64_t V = C->getValue()->getZExtValue())
1349 return V;
1350 else // Zero is a multiple of everything.
1351 return 1ULL << (S->getType()->getPrimitiveSizeInBits()-1);
1352 }
1353
1354 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1355 return GetConstantFactor(T->getOperand()) &
1356 T->getType()->getIntegralTypeMask();
1357 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1358 return GetConstantFactor(E->getOperand());
1359
1360 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1361 // The result is the min of all operands.
1362 uint64_t Res = GetConstantFactor(A->getOperand(0));
1363 for (unsigned i = 1, e = A->getNumOperands(); i != e && Res > 1; ++i)
1364 Res = std::min(Res, GetConstantFactor(A->getOperand(i)));
1365 return Res;
1366 }
1367
1368 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1369 // The result is the product of all the operands.
1370 uint64_t Res = GetConstantFactor(M->getOperand(0));
1371 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i)
1372 Res *= GetConstantFactor(M->getOperand(i));
1373 return Res;
1374 }
1375
1376 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001377 // For now, we just handle linear expressions.
1378 if (A->getNumOperands() == 2) {
1379 // We want the GCD between the start and the stride value.
1380 uint64_t Start = GetConstantFactor(A->getOperand(0));
1381 if (Start == 1) return 1;
1382 uint64_t Stride = GetConstantFactor(A->getOperand(1));
1383 return GreatestCommonDivisor64(Start, Stride);
1384 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001385 }
1386
1387 // SCEVSDivExpr, SCEVUnknown.
1388 return 1;
1389}
Chris Lattner53e677a2004-04-02 20:23:17 +00001390
1391/// createSCEV - We know that there is no SCEV for the specified value.
1392/// Analyze the expression.
1393///
1394SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1395 if (Instruction *I = dyn_cast<Instruction>(V)) {
1396 switch (I->getOpcode()) {
1397 case Instruction::Add:
1398 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1399 getSCEV(I->getOperand(1)));
1400 case Instruction::Mul:
1401 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1402 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001403 case Instruction::SDiv:
1404 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1405 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001406 break;
1407
1408 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001409 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1410 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001411 case Instruction::Or:
1412 // If the RHS of the Or is a constant, we may have something like:
1413 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1414 // optimizations will transparently handle this case.
1415 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1416 SCEVHandle LHS = getSCEV(I->getOperand(0));
1417 uint64_t CommonFact = GetConstantFactor(LHS);
1418 assert(CommonFact && "Common factor should at least be 1!");
1419 if (CommonFact > CI->getZExtValue()) {
1420 // If the LHS is a multiple that is larger than the RHS, use +.
1421 return SCEVAddExpr::get(LHS,
1422 getSCEV(I->getOperand(1)));
1423 }
1424 }
1425 break;
1426
Chris Lattner53e677a2004-04-02 20:23:17 +00001427 case Instruction::Shl:
1428 // Turn shift left of a constant amount into a multiply.
1429 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1430 Constant *X = ConstantInt::get(V->getType(), 1);
1431 X = ConstantExpr::getShl(X, SA);
1432 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1433 }
1434 break;
1435
Reid Spencer3da59db2006-11-27 01:05:10 +00001436 case Instruction::Trunc:
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001437 // We don't handle trunc to bool yet.
1438 if (I->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001439 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)),
1440 I->getType()->getUnsignedVersion());
1441 break;
1442
1443 case Instruction::ZExt:
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001444 // We don't handle zext from bool yet.
1445 if (I->getOperand(0)->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001446 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)),
1447 I->getType()->getUnsignedVersion());
1448 break;
1449
1450 case Instruction::BitCast:
1451 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001452 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1453 return getSCEV(I->getOperand(0));
1454 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001455
1456 case Instruction::PHI:
1457 return createNodeForPHI(cast<PHINode>(I));
1458
1459 default: // We cannot analyze this expression.
1460 break;
1461 }
1462 }
1463
1464 return SCEVUnknown::get(V);
1465}
1466
1467
1468
1469//===----------------------------------------------------------------------===//
1470// Iteration Count Computation Code
1471//
1472
1473/// getIterationCount - If the specified loop has a predictable iteration
1474/// count, return it. Note that it is not valid to call this method on a
1475/// loop without a loop-invariant iteration count.
1476SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1477 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1478 if (I == IterationCounts.end()) {
1479 SCEVHandle ItCount = ComputeIterationCount(L);
1480 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1481 if (ItCount != UnknownValue) {
1482 assert(ItCount->isLoopInvariant(L) &&
1483 "Computed trip count isn't loop invariant for loop!");
1484 ++NumTripCountsComputed;
1485 } else if (isa<PHINode>(L->getHeader()->begin())) {
1486 // Only count loops that have phi nodes as not being computable.
1487 ++NumTripCountsNotComputed;
1488 }
1489 }
1490 return I->second;
1491}
1492
1493/// ComputeIterationCount - Compute the number of times the specified loop
1494/// will iterate.
1495SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1496 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001497 std::vector<BasicBlock*> ExitBlocks;
1498 L->getExitBlocks(ExitBlocks);
1499 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001500
1501 // Okay, there is one exit block. Try to find the condition that causes the
1502 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001503 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001504
1505 BasicBlock *ExitingBlock = 0;
1506 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1507 PI != E; ++PI)
1508 if (L->contains(*PI)) {
1509 if (ExitingBlock == 0)
1510 ExitingBlock = *PI;
1511 else
1512 return UnknownValue; // More than one block exiting!
1513 }
1514 assert(ExitingBlock && "No exits from loop, something is broken!");
1515
1516 // Okay, we've computed the exiting block. See what condition causes us to
1517 // exit.
1518 //
1519 // FIXME: we should be able to handle switch instructions (with a single exit)
1520 // FIXME: We should handle cast of int to bool as well
1521 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1522 if (ExitBr == 0) return UnknownValue;
1523 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1524 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001525 if (ExitCond == 0) // Not a setcc
1526 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1527 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001528
Chris Lattner673e02b2004-10-12 01:49:27 +00001529 // If the condition was exit on true, convert the condition to exit on false.
1530 Instruction::BinaryOps Cond;
1531 if (ExitBr->getSuccessor(1) == ExitBlock)
1532 Cond = ExitCond->getOpcode();
1533 else
1534 Cond = ExitCond->getInverseCondition();
1535
1536 // Handle common loops like: for (X = "string"; *X; ++X)
1537 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1538 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1539 SCEVHandle ItCnt =
1540 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1541 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1542 }
1543
Chris Lattner53e677a2004-04-02 20:23:17 +00001544 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1545 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1546
1547 // Try to evaluate any dependencies out of the loop.
1548 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1549 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1550 Tmp = getSCEVAtScope(RHS, L);
1551 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1552
Chris Lattner53e677a2004-04-02 20:23:17 +00001553 // At this point, we would like to compute how many iterations of the loop the
1554 // predicate will return true for these inputs.
1555 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1556 // If there is a constant, force it into the RHS.
1557 std::swap(LHS, RHS);
1558 Cond = SetCondInst::getSwappedCondition(Cond);
1559 }
1560
1561 // FIXME: think about handling pointer comparisons! i.e.:
1562 // while (P != P+100) ++P;
1563
1564 // If we have a comparison of a chrec against a constant, try to use value
1565 // ranges to answer this query.
1566 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1567 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1568 if (AddRec->getLoop() == L) {
1569 // Form the comparison range using the constant of the correct type so
1570 // that the ConstantRange class knows to do a signed or unsigned
1571 // comparison.
1572 ConstantInt *CompVal = RHSC->getValue();
1573 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001574 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001575 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001576 if (CompVal) {
1577 // Form the constant range.
1578 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001579
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 // Now that we have it, if it's signed, convert it to an unsigned
1581 // range.
Reid Spencer2e20d392006-12-21 06:43:46 +00001582 // FIXME:Signless. This entire if statement can go away when
1583 // integers are signless. ConstantRange is already signless.
Chris Lattner53e677a2004-04-02 20:23:17 +00001584 if (CompRange.getLower()->getType()->isSigned()) {
1585 const Type *NewTy = RHSC->getValue()->getType();
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001586 Constant *NewL = ConstantExpr::getBitCast(CompRange.getLower(),
1587 NewTy);
1588 Constant *NewU = ConstantExpr::getBitCast(CompRange.getUpper(),
1589 NewTy);
Chris Lattner53e677a2004-04-02 20:23:17 +00001590 CompRange = ConstantRange(NewL, NewU);
1591 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001592
Chris Lattner53e677a2004-04-02 20:23:17 +00001593 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1594 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1595 }
1596 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001597
Chris Lattner53e677a2004-04-02 20:23:17 +00001598 switch (Cond) {
1599 case Instruction::SetNE: // while (X != Y)
1600 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001601 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001602 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001603 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1604 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 break;
1606 case Instruction::SetEQ:
1607 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001608 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001609 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001610 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1611 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001612 break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001613 case Instruction::SetLT:
1614 if (LHS->getType()->isInteger() &&
1615 ExitCond->getOperand(0)->getType()->isSigned()) {
1616 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1617 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1618 }
1619 break;
1620 case Instruction::SetGT:
1621 if (LHS->getType()->isInteger() &&
1622 ExitCond->getOperand(0)->getType()->isSigned()) {
1623 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1624 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1625 }
1626 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001628#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001629 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001630 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001631 cerr << "[unsigned] ";
1632 cerr << *LHS << " "
1633 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001634#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001635 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001636 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001637
1638 return ComputeIterationCountExhaustively(L, ExitCond,
1639 ExitBr->getSuccessor(0) == ExitBlock);
1640}
1641
Chris Lattner673e02b2004-10-12 01:49:27 +00001642static ConstantInt *
1643EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1644 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1645 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1646 assert(isa<SCEVConstant>(Val) &&
1647 "Evaluation of SCEV at constant didn't fold correctly?");
1648 return cast<SCEVConstant>(Val)->getValue();
1649}
1650
1651/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1652/// and a GEP expression (missing the pointer index) indexing into it, return
1653/// the addressed element of the initializer or null if the index expression is
1654/// invalid.
1655static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001656GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001657 const std::vector<ConstantInt*> &Indices) {
1658 Constant *Init = GV->getInitializer();
1659 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001660 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001661 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1662 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1663 Init = cast<Constant>(CS->getOperand(Idx));
1664 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1665 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1666 Init = cast<Constant>(CA->getOperand(Idx));
1667 } else if (isa<ConstantAggregateZero>(Init)) {
1668 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1669 assert(Idx < STy->getNumElements() && "Bad struct index!");
1670 Init = Constant::getNullValue(STy->getElementType(Idx));
1671 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1672 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1673 Init = Constant::getNullValue(ATy->getElementType());
1674 } else {
1675 assert(0 && "Unknown constant aggregate type!");
1676 }
1677 return 0;
1678 } else {
1679 return 0; // Unknown initializer type
1680 }
1681 }
1682 return Init;
1683}
1684
1685/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1686/// 'setcc load X, cst', try to se if we can compute the trip count.
1687SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001688ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattner673e02b2004-10-12 01:49:27 +00001689 const Loop *L, unsigned SetCCOpcode) {
1690 if (LI->isVolatile()) return UnknownValue;
1691
1692 // Check to see if the loaded pointer is a getelementptr of a global.
1693 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1694 if (!GEP) return UnknownValue;
1695
1696 // Make sure that it is really a constant global we are gepping, with an
1697 // initializer, and make sure the first IDX is really 0.
1698 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1699 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1700 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1701 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1702 return UnknownValue;
1703
1704 // Okay, we allow one non-constant index into the GEP instruction.
1705 Value *VarIdx = 0;
1706 std::vector<ConstantInt*> Indexes;
1707 unsigned VarIdxNum = 0;
1708 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1709 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1710 Indexes.push_back(CI);
1711 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1712 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1713 VarIdx = GEP->getOperand(i);
1714 VarIdxNum = i-2;
1715 Indexes.push_back(0);
1716 }
1717
1718 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1719 // Check to see if X is a loop variant variable value now.
1720 SCEVHandle Idx = getSCEV(VarIdx);
1721 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1722 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1723
1724 // We can only recognize very limited forms of loop index expressions, in
1725 // particular, only affine AddRec's like {C1,+,C2}.
1726 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1727 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1728 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1729 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1730 return UnknownValue;
1731
1732 unsigned MaxSteps = MaxBruteForceIterations;
1733 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001734 ConstantInt *ItCst =
1735 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001736 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1737
1738 // Form the GEP offset.
1739 Indexes[VarIdxNum] = Val;
1740
1741 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1742 if (Result == 0) break; // Cannot compute!
1743
1744 // Evaluate the condition for this iteration.
1745 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1746 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
Chris Lattner003cbf32006-09-28 23:36:21 +00001747 if (cast<ConstantBool>(Result)->getValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001748#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001749 cerr << "\n***\n*** Computed loop count " << *ItCst
1750 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1751 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001752#endif
1753 ++NumArrayLenItCounts;
1754 return SCEVConstant::get(ItCst); // Found terminating iteration!
1755 }
1756 }
1757 return UnknownValue;
1758}
1759
1760
Chris Lattner3221ad02004-04-17 22:58:41 +00001761/// CanConstantFold - Return true if we can constant fold an instruction of the
1762/// specified type, assuming that all operands were constants.
1763static bool CanConstantFold(const Instruction *I) {
1764 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1765 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1766 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001767
Chris Lattner3221ad02004-04-17 22:58:41 +00001768 if (const CallInst *CI = dyn_cast<CallInst>(I))
1769 if (const Function *F = CI->getCalledFunction())
1770 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1771 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001772}
1773
Chris Lattner3221ad02004-04-17 22:58:41 +00001774/// ConstantFold - Constant fold an instruction of the specified type with the
1775/// specified constant operands. This function may modify the operands vector.
1776static Constant *ConstantFold(const Instruction *I,
1777 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001778 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1779 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1780
Reid Spencer3da59db2006-11-27 01:05:10 +00001781 if (isa<CastInst>(I))
1782 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1783
Chris Lattner7980fb92004-04-17 18:36:24 +00001784 switch (I->getOpcode()) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001785 case Instruction::Select:
1786 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1787 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001788 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001789 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001790 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001791 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001792 return 0;
1793 case Instruction::GetElementPtr:
1794 Constant *Base = Operands[0];
1795 Operands.erase(Operands.begin());
1796 return ConstantExpr::getGetElementPtr(Base, Operands);
1797 }
1798 return 0;
1799}
1800
1801
Chris Lattner3221ad02004-04-17 22:58:41 +00001802/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1803/// in the loop that V is derived from. We allow arbitrary operations along the
1804/// way, but the operands of an operation must either be constants or a value
1805/// derived from a constant PHI. If this expression does not fit with these
1806/// constraints, return null.
1807static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1808 // If this is not an instruction, or if this is an instruction outside of the
1809 // loop, it can't be derived from a loop PHI.
1810 Instruction *I = dyn_cast<Instruction>(V);
1811 if (I == 0 || !L->contains(I->getParent())) return 0;
1812
1813 if (PHINode *PN = dyn_cast<PHINode>(I))
1814 if (L->getHeader() == I->getParent())
1815 return PN;
1816 else
1817 // We don't currently keep track of the control flow needed to evaluate
1818 // PHIs, so we cannot handle PHIs inside of loops.
1819 return 0;
1820
1821 // If we won't be able to constant fold this expression even if the operands
1822 // are constants, return early.
1823 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001824
Chris Lattner3221ad02004-04-17 22:58:41 +00001825 // Otherwise, we can evaluate this instruction if all of its operands are
1826 // constant or derived from a PHI node themselves.
1827 PHINode *PHI = 0;
1828 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1829 if (!(isa<Constant>(I->getOperand(Op)) ||
1830 isa<GlobalValue>(I->getOperand(Op)))) {
1831 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1832 if (P == 0) return 0; // Not evolving from PHI
1833 if (PHI == 0)
1834 PHI = P;
1835 else if (PHI != P)
1836 return 0; // Evolving from multiple different PHIs.
1837 }
1838
1839 // This is a expression evolving from a constant PHI!
1840 return PHI;
1841}
1842
1843/// EvaluateExpression - Given an expression that passes the
1844/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1845/// in the loop has the value PHIVal. If we can't fold this expression for some
1846/// reason, return null.
1847static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1848 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001849 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001850 return GV;
1851 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001852 Instruction *I = cast<Instruction>(V);
1853
1854 std::vector<Constant*> Operands;
1855 Operands.resize(I->getNumOperands());
1856
1857 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1858 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1859 if (Operands[i] == 0) return 0;
1860 }
1861
1862 return ConstantFold(I, Operands);
1863}
1864
1865/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1866/// in the header of its containing loop, we know the loop executes a
1867/// constant number of times, and the PHI node is just a recurrence
1868/// involving constants, fold it.
1869Constant *ScalarEvolutionsImpl::
1870getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1871 std::map<PHINode*, Constant*>::iterator I =
1872 ConstantEvolutionLoopExitValue.find(PN);
1873 if (I != ConstantEvolutionLoopExitValue.end())
1874 return I->second;
1875
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001876 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001877 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1878
1879 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1880
1881 // Since the loop is canonicalized, the PHI node must have two entries. One
1882 // entry must be a constant (coming in from outside of the loop), and the
1883 // second must be derived from the same PHI.
1884 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1885 Constant *StartCST =
1886 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1887 if (StartCST == 0)
1888 return RetVal = 0; // Must be a constant.
1889
1890 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1891 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1892 if (PN2 != PN)
1893 return RetVal = 0; // Not derived from same PHI.
1894
1895 // Execute the loop symbolically to determine the exit value.
1896 unsigned IterationNum = 0;
1897 unsigned NumIterations = Its;
1898 if (NumIterations != Its)
1899 return RetVal = 0; // More than 2^32 iterations??
1900
1901 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1902 if (IterationNum == NumIterations)
1903 return RetVal = PHIVal; // Got exit value!
1904
1905 // Compute the value of the PHI node for the next iteration.
1906 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1907 if (NextPHI == PHIVal)
1908 return RetVal = NextPHI; // Stopped evolving!
1909 if (NextPHI == 0)
1910 return 0; // Couldn't evaluate!
1911 PHIVal = NextPHI;
1912 }
1913}
1914
Chris Lattner7980fb92004-04-17 18:36:24 +00001915/// ComputeIterationCountExhaustively - If the trip is known to execute a
1916/// constant number of times (the condition evolves only from constants),
1917/// try to evaluate a few iterations of the loop until we get the exit
1918/// condition gets a value of ExitWhen (true or false). If we cannot
1919/// evaluate the trip count of the loop, return UnknownValue.
1920SCEVHandle ScalarEvolutionsImpl::
1921ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1922 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1923 if (PN == 0) return UnknownValue;
1924
1925 // Since the loop is canonicalized, the PHI node must have two entries. One
1926 // entry must be a constant (coming in from outside of the loop), and the
1927 // second must be derived from the same PHI.
1928 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1929 Constant *StartCST =
1930 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1931 if (StartCST == 0) return UnknownValue; // Must be a constant.
1932
1933 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1934 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1935 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1936
1937 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1938 // the loop symbolically to determine when the condition gets a value of
1939 // "ExitWhen".
1940 unsigned IterationNum = 0;
1941 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1942 for (Constant *PHIVal = StartCST;
1943 IterationNum != MaxIterations; ++IterationNum) {
1944 ConstantBool *CondVal =
1945 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1946 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001947
Chris Lattner7980fb92004-04-17 18:36:24 +00001948 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001949 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001950 ++NumBruteForceTripCountsComputed;
Reid Spencerb83eb642006-10-20 07:07:24 +00001951 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001952 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001953
Chris Lattner3221ad02004-04-17 22:58:41 +00001954 // Compute the value of the PHI node for the next iteration.
1955 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1956 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001957 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001958 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001959 }
1960
1961 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001962 return UnknownValue;
1963}
1964
1965/// getSCEVAtScope - Compute the value of the specified expression within the
1966/// indicated loop (which may be null to indicate in no loop). If the
1967/// expression cannot be evaluated, return UnknownValue.
1968SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1969 // FIXME: this should be turned into a virtual method on SCEV!
1970
Chris Lattner3221ad02004-04-17 22:58:41 +00001971 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001972
Chris Lattner3221ad02004-04-17 22:58:41 +00001973 // If this instruction is evolves from a constant-evolving PHI, compute the
1974 // exit value from the loop without using SCEVs.
1975 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1976 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1977 const Loop *LI = this->LI[I->getParent()];
1978 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1979 if (PHINode *PN = dyn_cast<PHINode>(I))
1980 if (PN->getParent() == LI->getHeader()) {
1981 // Okay, there is no closed form solution for the PHI node. Check
1982 // to see if the loop that contains it has a known iteration count.
1983 // If so, we may be able to force computation of the exit value.
1984 SCEVHandle IterationCount = getIterationCount(LI);
1985 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1986 // Okay, we know how many times the containing loop executes. If
1987 // this is a constant evolving PHI node, get the final value at
1988 // the specified iteration number.
1989 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001990 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001991 LI);
1992 if (RV) return SCEVUnknown::get(RV);
1993 }
1994 }
1995
Reid Spencer09906f32006-12-04 21:33:23 +00001996 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00001997 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00001998 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00001999 // result. This is particularly useful for computing loop exit values.
2000 if (CanConstantFold(I)) {
2001 std::vector<Constant*> Operands;
2002 Operands.reserve(I->getNumOperands());
2003 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2004 Value *Op = I->getOperand(i);
2005 if (Constant *C = dyn_cast<Constant>(Op)) {
2006 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002007 } else {
2008 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2009 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002010 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2011 Op->getType(),
2012 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002013 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2014 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002015 Operands.push_back(ConstantExpr::getIntegerCast(C,
2016 Op->getType(),
2017 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002018 else
2019 return V;
2020 } else {
2021 return V;
2022 }
2023 }
2024 }
2025 return SCEVUnknown::get(ConstantFold(I, Operands));
2026 }
2027 }
2028
2029 // This is some other type of SCEVUnknown, just return it.
2030 return V;
2031 }
2032
Chris Lattner53e677a2004-04-02 20:23:17 +00002033 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2034 // Avoid performing the look-up in the common case where the specified
2035 // expression has no loop-variant portions.
2036 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2037 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2038 if (OpAtScope != Comm->getOperand(i)) {
2039 if (OpAtScope == UnknownValue) return UnknownValue;
2040 // Okay, at least one of these operands is loop variant but might be
2041 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002042 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002043 NewOps.push_back(OpAtScope);
2044
2045 for (++i; i != e; ++i) {
2046 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2047 if (OpAtScope == UnknownValue) return UnknownValue;
2048 NewOps.push_back(OpAtScope);
2049 }
2050 if (isa<SCEVAddExpr>(Comm))
2051 return SCEVAddExpr::get(NewOps);
2052 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2053 return SCEVMulExpr::get(NewOps);
2054 }
2055 }
2056 // If we got here, all operands are loop invariant.
2057 return Comm;
2058 }
2059
Chris Lattner60a05cc2006-04-01 04:48:52 +00002060 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2061 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002062 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002063 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002064 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002065 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2066 return Div; // must be loop invariant
2067 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002068 }
2069
2070 // If this is a loop recurrence for a loop that does not contain L, then we
2071 // are dealing with the final value computed by the loop.
2072 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2073 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2074 // To evaluate this recurrence, we need to know how many times the AddRec
2075 // loop iterates. Compute this now.
2076 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2077 if (IterationCount == UnknownValue) return UnknownValue;
2078 IterationCount = getTruncateOrZeroExtend(IterationCount,
2079 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002080
Chris Lattner53e677a2004-04-02 20:23:17 +00002081 // If the value is affine, simplify the expression evaluation to just
2082 // Start + Step*IterationCount.
2083 if (AddRec->isAffine())
2084 return SCEVAddExpr::get(AddRec->getStart(),
2085 SCEVMulExpr::get(IterationCount,
2086 AddRec->getOperand(1)));
2087
2088 // Otherwise, evaluate it the hard way.
2089 return AddRec->evaluateAtIteration(IterationCount);
2090 }
2091 return UnknownValue;
2092 }
2093
2094 //assert(0 && "Unknown SCEV type!");
2095 return UnknownValue;
2096}
2097
2098
2099/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2100/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2101/// might be the same) or two SCEVCouldNotCompute objects.
2102///
2103static std::pair<SCEVHandle,SCEVHandle>
2104SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2105 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2106 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2107 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2108 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002109
Chris Lattner53e677a2004-04-02 20:23:17 +00002110 // We currently can only solve this if the coefficients are constants.
2111 if (!L || !M || !N) {
2112 SCEV *CNC = new SCEVCouldNotCompute();
2113 return std::make_pair(CNC, CNC);
2114 }
2115
Reid Spencer1628cec2006-10-26 06:15:43 +00002116 Constant *C = L->getValue();
2117 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002118
Chris Lattner53e677a2004-04-02 20:23:17 +00002119 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002120 // The B coefficient is M-N/2
2121 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002122 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002123 Two));
2124 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002125 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002126
Chris Lattner53e677a2004-04-02 20:23:17 +00002127 // Compute the B^2-4ac term.
2128 Constant *SqrtTerm =
2129 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2130 ConstantExpr::getMul(A, C));
2131 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2132
2133 // Compute floor(sqrt(B^2-4ac))
Reid Spencerb83eb642006-10-20 07:07:24 +00002134 ConstantInt *SqrtVal =
Reid Spencerd977d862006-12-12 23:36:14 +00002135 cast<ConstantInt>(ConstantExpr::getBitCast(SqrtTerm,
Chris Lattner53e677a2004-04-02 20:23:17 +00002136 SqrtTerm->getType()->getUnsignedVersion()));
Reid Spencerb83eb642006-10-20 07:07:24 +00002137 uint64_t SqrtValV = SqrtVal->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002138 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002139 // The square root might not be precise for arbitrary 64-bit integer
2140 // values. Do some sanity checks to ensure it's correct.
2141 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2142 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2143 SCEV *CNC = new SCEVCouldNotCompute();
2144 return std::make_pair(CNC, CNC);
2145 }
2146
Reid Spencerb83eb642006-10-20 07:07:24 +00002147 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
Reid Spencerd977d862006-12-12 23:36:14 +00002148 SqrtTerm = ConstantExpr::getTruncOrBitCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002149
Chris Lattner53e677a2004-04-02 20:23:17 +00002150 Constant *NegB = ConstantExpr::getNeg(B);
2151 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002152
Chris Lattner53e677a2004-04-02 20:23:17 +00002153 // The divisions must be performed as signed divisions.
2154 const Type *SignedTy = NegB->getType()->getSignedVersion();
Reid Spencerd977d862006-12-12 23:36:14 +00002155 NegB = ConstantExpr::getBitCast(NegB, SignedTy);
2156 TwoA = ConstantExpr::getBitCast(TwoA, SignedTy);
2157 SqrtTerm = ConstantExpr::getBitCast(SqrtTerm, SignedTy);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002158
Chris Lattner53e677a2004-04-02 20:23:17 +00002159 Constant *Solution1 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002160 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002161 Constant *Solution2 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002162 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002163 return std::make_pair(SCEVUnknown::get(Solution1),
2164 SCEVUnknown::get(Solution2));
2165}
2166
2167/// HowFarToZero - Return the number of times a backedge comparing the specified
2168/// value to zero will execute. If not computable, return UnknownValue
2169SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2170 // If the value is a constant
2171 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2172 // If the value is already zero, the branch will execute zero times.
2173 if (C->getValue()->isNullValue()) return C;
2174 return UnknownValue; // Otherwise it will loop infinitely.
2175 }
2176
2177 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2178 if (!AddRec || AddRec->getLoop() != L)
2179 return UnknownValue;
2180
2181 if (AddRec->isAffine()) {
2182 // If this is an affine expression the execution count of this branch is
2183 // equal to:
2184 //
2185 // (0 - Start/Step) iff Start % Step == 0
2186 //
2187 // Get the initial value for the loop.
2188 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002189 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002190 SCEVHandle Step = AddRec->getOperand(1);
2191
2192 Step = getSCEVAtScope(Step, L->getParentLoop());
2193
2194 // Figure out if Start % Step == 0.
2195 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2196 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2197 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002198 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002199 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2200 return Start; // 0 - Start/-1 == Start
2201
2202 // Check to see if Start is divisible by SC with no remainder.
2203 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2204 ConstantInt *StartCC = StartC->getValue();
2205 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002206 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002207 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002208 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002209 return SCEVUnknown::get(Result);
2210 }
2211 }
2212 }
2213 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2214 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2215 // the quadratic equation to solve it.
2216 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2217 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2218 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2219 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002220#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002221 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2222 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002223#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002224 // Pick the smallest positive root value.
2225 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2226 if (ConstantBool *CB =
2227 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2228 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002229 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002230 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002231
Chris Lattner53e677a2004-04-02 20:23:17 +00002232 // We can only use this value if the chrec ends up with an exact zero
2233 // value at this index. When solving for "X*X != 5", for example, we
2234 // should not accept a root of 2.
2235 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2236 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2237 if (EvalVal->getValue()->isNullValue())
2238 return R1; // We found a quadratic root!
2239 }
2240 }
2241 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002242
Chris Lattner53e677a2004-04-02 20:23:17 +00002243 return UnknownValue;
2244}
2245
2246/// HowFarToNonZero - Return the number of times a backedge checking the
2247/// specified value for nonzero will execute. If not computable, return
2248/// UnknownValue
2249SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2250 // Loops that look like: while (X == 0) are very strange indeed. We don't
2251 // handle them yet except for the trivial case. This could be expanded in the
2252 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002253
Chris Lattner53e677a2004-04-02 20:23:17 +00002254 // If the value is a constant, check to see if it is known to be non-zero
2255 // already. If so, the backedge will execute zero times.
2256 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2257 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2258 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
Chris Lattner003cbf32006-09-28 23:36:21 +00002259 if (NonZero == ConstantBool::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002260 return getSCEV(Zero);
2261 return UnknownValue; // Otherwise it will loop infinitely.
2262 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002263
Chris Lattner53e677a2004-04-02 20:23:17 +00002264 // We could implement others, but I really doubt anyone writes loops like
2265 // this, and if they did, they would already be constant folded.
2266 return UnknownValue;
2267}
2268
Chris Lattnerdb25de42005-08-15 23:33:51 +00002269/// HowManyLessThans - Return the number of times a backedge containing the
2270/// specified less-than comparison will execute. If not computable, return
2271/// UnknownValue.
2272SCEVHandle ScalarEvolutionsImpl::
2273HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2274 // Only handle: "ADDREC < LoopInvariant".
2275 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2276
2277 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2278 if (!AddRec || AddRec->getLoop() != L)
2279 return UnknownValue;
2280
2281 if (AddRec->isAffine()) {
2282 // FORNOW: We only support unit strides.
2283 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2284 if (AddRec->getOperand(1) != One)
2285 return UnknownValue;
2286
2287 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2288 // know that m is >= n on input to the loop. If it is, the condition return
2289 // true zero times. What we really should return, for full generality, is
2290 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2291 // canonical loop form: most do-loops will have a check that dominates the
2292 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2293 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2294
2295 // Search for the check.
2296 BasicBlock *Preheader = L->getLoopPreheader();
2297 BasicBlock *PreheaderDest = L->getHeader();
2298 if (Preheader == 0) return UnknownValue;
2299
2300 BranchInst *LoopEntryPredicate =
2301 dyn_cast<BranchInst>(Preheader->getTerminator());
2302 if (!LoopEntryPredicate) return UnknownValue;
2303
2304 // This might be a critical edge broken out. If the loop preheader ends in
2305 // an unconditional branch to the loop, check to see if the preheader has a
2306 // single predecessor, and if so, look for its terminator.
2307 while (LoopEntryPredicate->isUnconditional()) {
2308 PreheaderDest = Preheader;
2309 Preheader = Preheader->getSinglePredecessor();
2310 if (!Preheader) return UnknownValue; // Multiple preds.
2311
2312 LoopEntryPredicate =
2313 dyn_cast<BranchInst>(Preheader->getTerminator());
2314 if (!LoopEntryPredicate) return UnknownValue;
2315 }
2316
2317 // Now that we found a conditional branch that dominates the loop, check to
2318 // see if it is the comparison we are looking for.
2319 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2320 if (!SCI) return UnknownValue;
2321 Value *PreCondLHS = SCI->getOperand(0);
2322 Value *PreCondRHS = SCI->getOperand(1);
2323 Instruction::BinaryOps Cond;
2324 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2325 Cond = SCI->getOpcode();
2326 else
2327 Cond = SCI->getInverseCondition();
2328
2329 switch (Cond) {
2330 case Instruction::SetGT:
2331 std::swap(PreCondLHS, PreCondRHS);
2332 Cond = Instruction::SetLT;
2333 // Fall Through.
2334 case Instruction::SetLT:
2335 if (PreCondLHS->getType()->isInteger() &&
2336 PreCondLHS->getType()->isSigned()) {
2337 if (RHS != getSCEV(PreCondRHS))
2338 return UnknownValue; // Not a comparison against 'm'.
2339
2340 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2341 != getSCEV(PreCondLHS))
2342 return UnknownValue; // Not a comparison against 'n-1'.
2343 break;
2344 } else {
2345 return UnknownValue;
2346 }
2347 default: break;
2348 }
2349
Bill Wendlinge8156192006-12-07 01:30:32 +00002350 //cerr << "Computed Loop Trip Count as: "
2351 // << *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
Chris Lattnerdb25de42005-08-15 23:33:51 +00002352 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2353 }
2354
2355 return UnknownValue;
2356}
2357
Chris Lattner53e677a2004-04-02 20:23:17 +00002358/// getNumIterationsInRange - Return the number of iterations of this loop that
2359/// produce values in the specified constant range. Another way of looking at
2360/// this is that it returns the first iteration number where the value is not in
2361/// the condition, thus computing the exit count. If the iteration count can't
2362/// be computed, an instance of SCEVCouldNotCompute is returned.
2363SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2364 if (Range.isFullSet()) // Infinite loop.
2365 return new SCEVCouldNotCompute();
2366
2367 // If the start is a non-zero constant, shift the range to simplify things.
2368 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2369 if (!SC->getValue()->isNullValue()) {
2370 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002371 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002372 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2373 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2374 return ShiftedAddRec->getNumIterationsInRange(
2375 Range.subtract(SC->getValue()));
2376 // This is strange and shouldn't happen.
2377 return new SCEVCouldNotCompute();
2378 }
2379
2380 // The only time we can solve this is when we have all constant indices.
2381 // Otherwise, we cannot determine the overflow conditions.
2382 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2383 if (!isa<SCEVConstant>(getOperand(i)))
2384 return new SCEVCouldNotCompute();
2385
2386
2387 // Okay at this point we know that all elements of the chrec are constants and
2388 // that the start element is zero.
2389
2390 // First check to see if the range contains zero. If not, the first
2391 // iteration exits.
2392 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2393 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002394
Chris Lattner53e677a2004-04-02 20:23:17 +00002395 if (isAffine()) {
2396 // If this is an affine expression then we have this situation:
2397 // Solve {0,+,A} in Range === Ax in Range
2398
2399 // Since we know that zero is in the range, we know that the upper value of
2400 // the range must be the first possible exit value. Also note that we
2401 // already checked for a full range.
2402 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2403 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2404 ConstantInt *One = ConstantInt::get(getType(), 1);
2405
2406 // The exit value should be (Upper+A-1)/A.
2407 Constant *ExitValue = Upper;
2408 if (A != One) {
2409 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002410 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002411 }
2412 assert(isa<ConstantInt>(ExitValue) &&
2413 "Constant folding of integers not implemented?");
2414
2415 // Evaluate at the exit value. If we really did fall out of the valid
2416 // range, then we computed our trip count, otherwise wrap around or other
2417 // things must have happened.
2418 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2419 if (Range.contains(Val))
2420 return new SCEVCouldNotCompute(); // Something strange happened
2421
2422 // Ensure that the previous value is in the range. This is a sanity check.
2423 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2424 ConstantExpr::getSub(ExitValue, One))) &&
2425 "Linear scev computation is off in a bad way!");
2426 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2427 } else if (isQuadratic()) {
2428 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2429 // quadratic equation to solve it. To do this, we must frame our problem in
2430 // terms of figuring out when zero is crossed, instead of when
2431 // Range.getUpper() is crossed.
2432 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002433 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002434 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2435
2436 // Next, solve the constructed addrec
2437 std::pair<SCEVHandle,SCEVHandle> Roots =
2438 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2439 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2440 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2441 if (R1) {
2442 // Pick the smallest positive root value.
2443 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2444 if (ConstantBool *CB =
2445 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2446 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002447 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002448 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002449
Chris Lattner53e677a2004-04-02 20:23:17 +00002450 // Make sure the root is not off by one. The returned iteration should
2451 // not be in the range, but the previous one should be. When solving
2452 // for "X*X < 5", for example, we should not return a root of 2.
2453 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2454 R1->getValue());
2455 if (Range.contains(R1Val)) {
2456 // The next iteration must be out of the range...
2457 Constant *NextVal =
2458 ConstantExpr::getAdd(R1->getValue(),
2459 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002460
Chris Lattner53e677a2004-04-02 20:23:17 +00002461 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2462 if (!Range.contains(R1Val))
2463 return SCEVUnknown::get(NextVal);
2464 return new SCEVCouldNotCompute(); // Something strange happened
2465 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002466
Chris Lattner53e677a2004-04-02 20:23:17 +00002467 // If R1 was not in the range, then it is a good return value. Make
2468 // sure that R1-1 WAS in the range though, just in case.
2469 Constant *NextVal =
2470 ConstantExpr::getSub(R1->getValue(),
2471 ConstantInt::get(R1->getType(), 1));
2472 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2473 if (Range.contains(R1Val))
2474 return R1;
2475 return new SCEVCouldNotCompute(); // Something strange happened
2476 }
2477 }
2478 }
2479
2480 // Fallback, if this is a general polynomial, figure out the progression
2481 // through brute force: evaluate until we find an iteration that fails the
2482 // test. This is likely to be slow, but getting an accurate trip count is
2483 // incredibly important, we will be able to simplify the exit test a lot, and
2484 // we are almost guaranteed to get a trip count in this case.
2485 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2486 ConstantInt *One = ConstantInt::get(getType(), 1);
2487 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2488 do {
2489 ++NumBruteForceEvaluations;
2490 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2491 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2492 return new SCEVCouldNotCompute();
2493
2494 // Check to see if we found the value!
2495 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2496 return SCEVConstant::get(TestVal);
2497
2498 // Increment to test the next index.
2499 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2500 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002501
Chris Lattner53e677a2004-04-02 20:23:17 +00002502 return new SCEVCouldNotCompute();
2503}
2504
2505
2506
2507//===----------------------------------------------------------------------===//
2508// ScalarEvolution Class Implementation
2509//===----------------------------------------------------------------------===//
2510
2511bool ScalarEvolution::runOnFunction(Function &F) {
2512 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2513 return false;
2514}
2515
2516void ScalarEvolution::releaseMemory() {
2517 delete (ScalarEvolutionsImpl*)Impl;
2518 Impl = 0;
2519}
2520
2521void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2522 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002523 AU.addRequiredTransitive<LoopInfo>();
2524}
2525
2526SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2527 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2528}
2529
Chris Lattnera0740fb2005-08-09 23:36:33 +00002530/// hasSCEV - Return true if the SCEV for this value has already been
2531/// computed.
2532bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002533 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002534}
2535
2536
2537/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2538/// the specified value.
2539void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2540 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2541}
2542
2543
Chris Lattner53e677a2004-04-02 20:23:17 +00002544SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2545 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2546}
2547
2548bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2549 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2550}
2551
2552SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2553 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2554}
2555
2556void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2557 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2558}
2559
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002560static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002561 const Loop *L) {
2562 // Print all inner loops first
2563 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2564 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002565
Bill Wendlinge8156192006-12-07 01:30:32 +00002566 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002567
2568 std::vector<BasicBlock*> ExitBlocks;
2569 L->getExitBlocks(ExitBlocks);
2570 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002571 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002572
2573 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002574 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002575 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002576 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002577 }
2578
Bill Wendlinge8156192006-12-07 01:30:32 +00002579 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002580}
2581
Reid Spencerce9653c2004-12-07 04:03:45 +00002582void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002583 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2584 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2585
2586 OS << "Classifying expressions for: " << F.getName() << "\n";
2587 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002588 if (I->getType()->isInteger()) {
2589 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002590 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002591 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002592 SV->print(OS);
2593 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002594
Chris Lattner6ffe5512004-04-27 15:13:33 +00002595 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002596 ConstantRange Bounds = SV->getValueRange();
2597 if (!Bounds.isFullSet())
2598 OS << "Bounds: " << Bounds << " ";
2599 }
2600
Chris Lattner6ffe5512004-04-27 15:13:33 +00002601 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002602 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002603 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002604 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2605 OS << "<<Unknown>>";
2606 } else {
2607 OS << *ExitValue;
2608 }
2609 }
2610
2611
2612 OS << "\n";
2613 }
2614
2615 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2616 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2617 PrintLoopInfo(OS, this, *I);
2618}
2619