blob: fcfab9e1c9b0827b78a5f7598d8ff9832bbcf15e [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 Spencere4d87aa2006-12-23 06:05:41 +0000180 V = cast<ConstantInt>(ConstantExpr::getBitCast(V, NewTy));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000181 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000182
Chris Lattnerb3364092006-10-04 21:49:37 +0000183 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184 if (R == 0) R = new SCEVConstant(V);
185 return R;
186}
Chris Lattner53e677a2004-04-02 20:23:17 +0000187
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000188ConstantRange SCEVConstant::getValueRange() const {
189 return ConstantRange(V);
190}
Chris Lattner53e677a2004-04-02 20:23:17 +0000191
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000192const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000194void SCEVConstant::print(std::ostream &OS) const {
195 WriteAsOperand(OS, V, false);
196}
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
199// particular input. Don't use a SCEVHandle here, or else the object will
200// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000201static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
202 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000203
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000204SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
205 : SCEV(scTruncate), Op(op), Ty(ty) {
206 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207 "Cannot truncate non-integer value!");
208 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
209 "This is not a truncating conversion!");
210}
Chris Lattner53e677a2004-04-02 20:23:17 +0000211
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000212SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000213 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214}
Chris Lattner53e677a2004-04-02 20:23:17 +0000215
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216ConstantRange SCEVTruncateExpr::getValueRange() const {
217 return getOperand()->getValueRange().truncate(getType());
218}
Chris Lattner53e677a2004-04-02 20:23:17 +0000219
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220void SCEVTruncateExpr::print(std::ostream &OS) const {
221 OS << "(truncate " << *Op << " to " << *Ty << ")";
222}
223
224// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
225// particular input. Don't use a SCEVHandle here, or else the object will never
226// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000227static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
228 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000229
230SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000231 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233 "Cannot zero extend non-integer value!");
234 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
235 "This is not an extending conversion!");
236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000240}
241
242ConstantRange SCEVZeroExtendExpr::getValueRange() const {
243 return getOperand()->getValueRange().zeroExtend(getType());
244}
245
246void SCEVZeroExtendExpr::print(std::ostream &OS) const {
247 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
248}
249
250// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
251// particular input. Don't use a SCEVHandle here, or else the object will never
252// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000253static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
254 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000255
256SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000257 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
258 std::vector<SCEV*>(Operands.begin(),
259 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000260}
261
262void SCEVCommutativeExpr::print(std::ostream &OS) const {
263 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
264 const char *OpStr = getOperationStr();
265 OS << "(" << *Operands[0];
266 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
267 OS << OpStr << *Operands[i];
268 OS << ")";
269}
270
Chris Lattner4dc534c2005-02-13 04:37:18 +0000271SCEVHandle SCEVCommutativeExpr::
272replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
273 const SCEVHandle &Conc) const {
274 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
275 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
276 if (H != getOperand(i)) {
277 std::vector<SCEVHandle> NewOps;
278 NewOps.reserve(getNumOperands());
279 for (unsigned j = 0; j != i; ++j)
280 NewOps.push_back(getOperand(j));
281 NewOps.push_back(H);
282 for (++i; i != e; ++i)
283 NewOps.push_back(getOperand(i)->
284 replaceSymbolicValuesWithConcrete(Sym, Conc));
285
286 if (isa<SCEVAddExpr>(this))
287 return SCEVAddExpr::get(NewOps);
288 else if (isa<SCEVMulExpr>(this))
289 return SCEVMulExpr::get(NewOps);
290 else
291 assert(0 && "Unknown commutative expr!");
292 }
293 }
294 return this;
295}
296
297
Chris Lattner60a05cc2006-04-01 04:48:52 +0000298// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000299// input. Don't use a SCEVHandle here, or else the object will never be
300// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000301static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
302 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000303
Chris Lattner60a05cc2006-04-01 04:48:52 +0000304SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000305 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000306}
307
Chris Lattner60a05cc2006-04-01 04:48:52 +0000308void SCEVSDivExpr::print(std::ostream &OS) const {
309 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000310}
311
Chris Lattner60a05cc2006-04-01 04:48:52 +0000312const Type *SCEVSDivExpr::getType() const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000313 const Type *Ty = LHS->getType();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000314 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315 return Ty;
316}
317
318// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
319// particular input. Don't use a SCEVHandle here, or else the object will never
320// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000321static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
322 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000323
324SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000325 SCEVAddRecExprs->erase(std::make_pair(L,
326 std::vector<SCEV*>(Operands.begin(),
327 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000328}
329
Chris Lattner4dc534c2005-02-13 04:37:18 +0000330SCEVHandle SCEVAddRecExpr::
331replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
332 const SCEVHandle &Conc) const {
333 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
334 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
335 if (H != getOperand(i)) {
336 std::vector<SCEVHandle> NewOps;
337 NewOps.reserve(getNumOperands());
338 for (unsigned j = 0; j != i; ++j)
339 NewOps.push_back(getOperand(j));
340 NewOps.push_back(H);
341 for (++i; i != e; ++i)
342 NewOps.push_back(getOperand(i)->
343 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000344
Chris Lattner4dc534c2005-02-13 04:37:18 +0000345 return get(NewOps, L);
346 }
347 }
348 return this;
349}
350
351
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000352bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
353 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000354 // contain L and if the start is invariant.
355 return !QueryLoop->contains(L->getHeader()) &&
356 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000357}
358
359
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000360void SCEVAddRecExpr::print(std::ostream &OS) const {
361 OS << "{" << *Operands[0];
362 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
363 OS << ",+," << *Operands[i];
364 OS << "}<" << L->getHeader()->getName() + ">";
365}
Chris Lattner53e677a2004-04-02 20:23:17 +0000366
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000367// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
368// value. Don't use a SCEVHandle here, or else the object will never be
369// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000370static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000371
Chris Lattnerb3364092006-10-04 21:49:37 +0000372SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000373
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000374bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
375 // All non-instruction values are loop invariant. All instructions are loop
376 // invariant if they are not contained in the specified loop.
377 if (Instruction *I = dyn_cast<Instruction>(V))
378 return !L->contains(I->getParent());
379 return true;
380}
Chris Lattner53e677a2004-04-02 20:23:17 +0000381
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000382const Type *SCEVUnknown::getType() const {
383 return V->getType();
384}
Chris Lattner53e677a2004-04-02 20:23:17 +0000385
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000386void SCEVUnknown::print(std::ostream &OS) const {
387 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000388}
389
Chris Lattner8d741b82004-06-20 06:23:15 +0000390//===----------------------------------------------------------------------===//
391// SCEV Utilities
392//===----------------------------------------------------------------------===//
393
394namespace {
395 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
396 /// than the complexity of the RHS. This comparator is used to canonicalize
397 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000398 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000399 bool operator()(SCEV *LHS, SCEV *RHS) {
400 return LHS->getSCEVType() < RHS->getSCEVType();
401 }
402 };
403}
404
405/// GroupByComplexity - Given a list of SCEV objects, order them by their
406/// complexity, and group objects of the same complexity together by value.
407/// When this routine is finished, we know that any duplicates in the vector are
408/// consecutive and that complexity is monotonically increasing.
409///
410/// Note that we go take special precautions to ensure that we get determinstic
411/// results from this routine. In other words, we don't want the results of
412/// this to depend on where the addresses of various SCEV objects happened to
413/// land in memory.
414///
415static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
416 if (Ops.size() < 2) return; // Noop
417 if (Ops.size() == 2) {
418 // This is the common case, which also happens to be trivially simple.
419 // Special case it.
420 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
421 std::swap(Ops[0], Ops[1]);
422 return;
423 }
424
425 // Do the rough sort by complexity.
426 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
427
428 // Now that we are sorted by complexity, group elements of the same
429 // complexity. Note that this is, at worst, N^2, but the vector is likely to
430 // be extremely short in practice. Note that we take this approach because we
431 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000432 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000433 SCEV *S = Ops[i];
434 unsigned Complexity = S->getSCEVType();
435
436 // If there are any objects of the same complexity and same value as this
437 // one, group them.
438 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
439 if (Ops[j] == S) { // Found a duplicate.
440 // Move it to immediately after i'th element.
441 std::swap(Ops[i+1], Ops[j]);
442 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000443 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000444 }
445 }
446 }
447}
448
Chris Lattner53e677a2004-04-02 20:23:17 +0000449
Chris Lattner53e677a2004-04-02 20:23:17 +0000450
451//===----------------------------------------------------------------------===//
452// Simple SCEV method implementations
453//===----------------------------------------------------------------------===//
454
455/// getIntegerSCEV - Given an integer or FP type, create a constant for the
456/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000457SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000458 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000459 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000460 C = Constant::getNullValue(Ty);
461 else if (Ty->isFloatingPoint())
462 C = ConstantFP::get(Ty, Val);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000463 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000464 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000465 return SCEVUnknown::get(C);
466}
467
468/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
469/// input value to the specified type. If the type must be extended, it is zero
470/// extended.
471static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
472 const Type *SrcTy = V->getType();
473 assert(SrcTy->isInteger() && Ty->isInteger() &&
474 "Cannot truncate or zero extend with non-integer arguments!");
475 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
476 return V; // No conversion
477 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
478 return SCEVTruncateExpr::get(V, Ty);
479 return SCEVZeroExtendExpr::get(V, Ty);
480}
481
482/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
483///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000484SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000485 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
486 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000487
Chris Lattnerb06432c2004-04-23 21:29:03 +0000488 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000489}
490
491/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
492///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000493SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000494 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000495 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000496}
497
498
Chris Lattner53e677a2004-04-02 20:23:17 +0000499/// PartialFact - Compute V!/(V-NumSteps)!
500static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
501 // Handle this case efficiently, it is common to have constant iteration
502 // counts while computing loop exit values.
503 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000504 uint64_t Val = SC->getValue()->getZExtValue();
Chris Lattner53e677a2004-04-02 20:23:17 +0000505 uint64_t Result = 1;
506 for (; NumSteps; --NumSteps)
507 Result *= Val-(NumSteps-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000508 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000509 return SCEVUnknown::get(ConstantExpr::getTruncOrBitCast(Res, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000510 }
511
512 const Type *Ty = V->getType();
513 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000514 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000515
Chris Lattner53e677a2004-04-02 20:23:17 +0000516 SCEVHandle Result = V;
517 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000518 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000519 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000520 return Result;
521}
522
523
524/// evaluateAtIteration - Return the value of this chain of recurrences at
525/// the specified iteration number. We can evaluate this recurrence by
526/// multiplying each element in the chain by the binomial coefficient
527/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
528///
529/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
530///
531/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
532/// Is the binomial equation safe using modular arithmetic??
533///
534SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
535 SCEVHandle Result = getStart();
536 int Divisor = 1;
537 const Type *Ty = It->getType();
538 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
539 SCEVHandle BC = PartialFact(It, i);
540 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000541 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000542 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000543 Result = SCEVAddExpr::get(Result, Val);
544 }
545 return Result;
546}
547
548
549//===----------------------------------------------------------------------===//
550// SCEV Expression folder implementations
551//===----------------------------------------------------------------------===//
552
553SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
554 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000555 return SCEVUnknown::get(
Reid Spencer315d0552006-12-05 22:39:58 +0000556 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000557
558 // If the input value is a chrec scev made out of constants, truncate
559 // all of the constants.
560 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
561 std::vector<SCEVHandle> Operands;
562 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
563 // FIXME: This should allow truncation of other expression types!
564 if (isa<SCEVConstant>(AddRec->getOperand(i)))
565 Operands.push_back(get(AddRec->getOperand(i), Ty));
566 else
567 break;
568 if (Operands.size() == AddRec->getNumOperands())
569 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
570 }
571
Chris Lattnerb3364092006-10-04 21:49:37 +0000572 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000573 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
574 return Result;
575}
576
577SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
578 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000579 return SCEVUnknown::get(
Reid Spencerd977d862006-12-12 23:36:14 +0000580 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000581
582 // FIXME: If the input value is a chrec scev, and we can prove that the value
583 // did not overflow the old, smaller, value, we can zero extend all of the
584 // operands (often constants). This would allow analysis of something like
585 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
586
Chris Lattnerb3364092006-10-04 21:49:37 +0000587 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000588 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
589 return Result;
590}
591
592// get - Get a canonical add expression, or something simpler if possible.
593SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
594 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000595 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000596
597 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000598 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000599
600 // If there are any constants, fold them together.
601 unsigned Idx = 0;
602 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
603 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000604 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000605 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
606 // We found two constants, fold them together!
607 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
609 Ops[0] = SCEVConstant::get(CI);
610 Ops.erase(Ops.begin()+1); // Erase the folded element
611 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000612 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000613 } else {
614 // If we couldn't fold the expression, move to the next constant. Note
615 // that this is impossible to happen in practice because we always
616 // constant fold constant ints to constant ints.
617 ++Idx;
618 }
619 }
620
621 // If we are left with a constant zero being added, strip it off.
622 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
623 Ops.erase(Ops.begin());
624 --Idx;
625 }
626 }
627
Chris Lattner627018b2004-04-07 16:16:11 +0000628 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000629
Chris Lattner53e677a2004-04-02 20:23:17 +0000630 // Okay, check to see if the same value occurs in the operand list twice. If
631 // so, merge them together into an multiply expression. Since we sorted the
632 // list, these values are required to be adjacent.
633 const Type *Ty = Ops[0]->getType();
634 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
635 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
636 // Found a match, merge the two values into a multiply, and add any
637 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000638 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000639 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
640 if (Ops.size() == 2)
641 return Mul;
642 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
643 Ops.push_back(Mul);
644 return SCEVAddExpr::get(Ops);
645 }
646
647 // Okay, now we know the first non-constant operand. If there are add
648 // operands they would be next.
649 if (Idx < Ops.size()) {
650 bool DeletedAdd = false;
651 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
652 // If we have an add, expand the add operands onto the end of the operands
653 // list.
654 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
655 Ops.erase(Ops.begin()+Idx);
656 DeletedAdd = true;
657 }
658
659 // If we deleted at least one add, we added operands to the end of the list,
660 // and they are not necessarily sorted. Recurse to resort and resimplify
661 // any operands we just aquired.
662 if (DeletedAdd)
663 return get(Ops);
664 }
665
666 // Skip over the add expression until we get to a multiply.
667 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
668 ++Idx;
669
670 // If we are adding something to a multiply expression, make sure the
671 // something is not already an operand of the multiply. If so, merge it into
672 // the multiply.
673 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
674 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
675 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
676 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
677 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000678 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000679 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
680 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
681 if (Mul->getNumOperands() != 2) {
682 // If the multiply has more than two operands, we must get the
683 // Y*Z term.
684 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
685 MulOps.erase(MulOps.begin()+MulOp);
686 InnerMul = SCEVMulExpr::get(MulOps);
687 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000688 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000689 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
690 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
691 if (Ops.size() == 2) return OuterMul;
692 if (AddOp < Idx) {
693 Ops.erase(Ops.begin()+AddOp);
694 Ops.erase(Ops.begin()+Idx-1);
695 } else {
696 Ops.erase(Ops.begin()+Idx);
697 Ops.erase(Ops.begin()+AddOp-1);
698 }
699 Ops.push_back(OuterMul);
700 return SCEVAddExpr::get(Ops);
701 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000702
Chris Lattner53e677a2004-04-02 20:23:17 +0000703 // Check this multiply against other multiplies being added together.
704 for (unsigned OtherMulIdx = Idx+1;
705 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
706 ++OtherMulIdx) {
707 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
708 // If MulOp occurs in OtherMul, we can fold the two multiplies
709 // together.
710 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
711 OMulOp != e; ++OMulOp)
712 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
713 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
714 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
715 if (Mul->getNumOperands() != 2) {
716 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
717 MulOps.erase(MulOps.begin()+MulOp);
718 InnerMul1 = SCEVMulExpr::get(MulOps);
719 }
720 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
721 if (OtherMul->getNumOperands() != 2) {
722 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
723 OtherMul->op_end());
724 MulOps.erase(MulOps.begin()+OMulOp);
725 InnerMul2 = SCEVMulExpr::get(MulOps);
726 }
727 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
728 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
729 if (Ops.size() == 2) return OuterMul;
730 Ops.erase(Ops.begin()+Idx);
731 Ops.erase(Ops.begin()+OtherMulIdx-1);
732 Ops.push_back(OuterMul);
733 return SCEVAddExpr::get(Ops);
734 }
735 }
736 }
737 }
738
739 // If there are any add recurrences in the operands list, see if any other
740 // added values are loop invariant. If so, we can fold them into the
741 // recurrence.
742 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
743 ++Idx;
744
745 // Scan over all recurrences, trying to fold loop invariants into them.
746 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
747 // Scan all of the other operands to this add and add them to the vector if
748 // they are loop invariant w.r.t. the recurrence.
749 std::vector<SCEVHandle> LIOps;
750 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
751 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
752 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
753 LIOps.push_back(Ops[i]);
754 Ops.erase(Ops.begin()+i);
755 --i; --e;
756 }
757
758 // If we found some loop invariants, fold them into the recurrence.
759 if (!LIOps.empty()) {
760 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
761 LIOps.push_back(AddRec->getStart());
762
763 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
764 AddRecOps[0] = SCEVAddExpr::get(LIOps);
765
766 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
767 // If all of the other operands were loop invariant, we are done.
768 if (Ops.size() == 1) return NewRec;
769
770 // Otherwise, add the folded AddRec by the non-liv parts.
771 for (unsigned i = 0;; ++i)
772 if (Ops[i] == AddRec) {
773 Ops[i] = NewRec;
774 break;
775 }
776 return SCEVAddExpr::get(Ops);
777 }
778
779 // Okay, if there weren't any loop invariants to be folded, check to see if
780 // there are multiple AddRec's with the same loop induction variable being
781 // added together. If so, we can fold them.
782 for (unsigned OtherIdx = Idx+1;
783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
784 if (OtherIdx != Idx) {
785 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
786 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
787 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
788 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
789 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
790 if (i >= NewOps.size()) {
791 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
792 OtherAddRec->op_end());
793 break;
794 }
795 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
796 }
797 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
798
799 if (Ops.size() == 2) return NewAddRec;
800
801 Ops.erase(Ops.begin()+Idx);
802 Ops.erase(Ops.begin()+OtherIdx-1);
803 Ops.push_back(NewAddRec);
804 return SCEVAddExpr::get(Ops);
805 }
806 }
807
808 // Otherwise couldn't fold anything into this recurrence. Move onto the
809 // next one.
810 }
811
812 // Okay, it looks like we really DO need an add expr. Check to see if we
813 // already have one, otherwise create a new one.
814 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000815 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
816 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000817 if (Result == 0) Result = new SCEVAddExpr(Ops);
818 return Result;
819}
820
821
822SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
823 assert(!Ops.empty() && "Cannot get empty mul!");
824
825 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000826 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000827
828 // If there are any constants, fold them together.
829 unsigned Idx = 0;
830 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
831
832 // C1*(C2+V) -> C1*C2 + C1*V
833 if (Ops.size() == 2)
834 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
835 if (Add->getNumOperands() == 2 &&
836 isa<SCEVConstant>(Add->getOperand(0)))
837 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
838 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
839
840
841 ++Idx;
842 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
843 // We found two constants, fold them together!
844 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
845 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
846 Ops[0] = SCEVConstant::get(CI);
847 Ops.erase(Ops.begin()+1); // Erase the folded element
848 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000849 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000850 } else {
851 // If we couldn't fold the expression, move to the next constant. Note
852 // that this is impossible to happen in practice because we always
853 // constant fold constant ints to constant ints.
854 ++Idx;
855 }
856 }
857
858 // If we are left with a constant one being multiplied, strip it off.
859 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
860 Ops.erase(Ops.begin());
861 --Idx;
862 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
863 // If we have a multiply of zero, it will always be zero.
864 return Ops[0];
865 }
866 }
867
868 // Skip over the add expression until we get to a multiply.
869 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
870 ++Idx;
871
872 if (Ops.size() == 1)
873 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000874
Chris Lattner53e677a2004-04-02 20:23:17 +0000875 // If there are mul operands inline them all into this expression.
876 if (Idx < Ops.size()) {
877 bool DeletedMul = false;
878 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
879 // If we have an mul, expand the mul operands onto the end of the operands
880 // list.
881 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
882 Ops.erase(Ops.begin()+Idx);
883 DeletedMul = true;
884 }
885
886 // If we deleted at least one mul, we added operands to the end of the list,
887 // and they are not necessarily sorted. Recurse to resort and resimplify
888 // any operands we just aquired.
889 if (DeletedMul)
890 return get(Ops);
891 }
892
893 // If there are any add recurrences in the operands list, see if any other
894 // added values are loop invariant. If so, we can fold them into the
895 // recurrence.
896 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
897 ++Idx;
898
899 // Scan over all recurrences, trying to fold loop invariants into them.
900 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
901 // Scan all of the other operands to this mul and add them to the vector if
902 // they are loop invariant w.r.t. the recurrence.
903 std::vector<SCEVHandle> LIOps;
904 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
905 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
906 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
907 LIOps.push_back(Ops[i]);
908 Ops.erase(Ops.begin()+i);
909 --i; --e;
910 }
911
912 // If we found some loop invariants, fold them into the recurrence.
913 if (!LIOps.empty()) {
914 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
915 std::vector<SCEVHandle> NewOps;
916 NewOps.reserve(AddRec->getNumOperands());
917 if (LIOps.size() == 1) {
918 SCEV *Scale = LIOps[0];
919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
920 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
921 } else {
922 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
923 std::vector<SCEVHandle> MulOps(LIOps);
924 MulOps.push_back(AddRec->getOperand(i));
925 NewOps.push_back(SCEVMulExpr::get(MulOps));
926 }
927 }
928
929 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
930
931 // If all of the other operands were loop invariant, we are done.
932 if (Ops.size() == 1) return NewRec;
933
934 // Otherwise, multiply the folded AddRec by the non-liv parts.
935 for (unsigned i = 0;; ++i)
936 if (Ops[i] == AddRec) {
937 Ops[i] = NewRec;
938 break;
939 }
940 return SCEVMulExpr::get(Ops);
941 }
942
943 // Okay, if there weren't any loop invariants to be folded, check to see if
944 // there are multiple AddRec's with the same loop induction variable being
945 // multiplied together. If so, we can fold them.
946 for (unsigned OtherIdx = Idx+1;
947 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
948 if (OtherIdx != Idx) {
949 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
950 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
951 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
952 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
953 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
954 G->getStart());
955 SCEVHandle B = F->getStepRecurrence();
956 SCEVHandle D = G->getStepRecurrence();
957 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
958 SCEVMulExpr::get(G, B),
959 SCEVMulExpr::get(B, D));
960 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
961 F->getLoop());
962 if (Ops.size() == 2) return NewAddRec;
963
964 Ops.erase(Ops.begin()+Idx);
965 Ops.erase(Ops.begin()+OtherIdx-1);
966 Ops.push_back(NewAddRec);
967 return SCEVMulExpr::get(Ops);
968 }
969 }
970
971 // Otherwise couldn't fold anything into this recurrence. Move onto the
972 // next one.
973 }
974
975 // Okay, it looks like we really DO need an mul expr. Check to see if we
976 // already have one, otherwise create a new one.
977 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000978 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
979 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000980 if (Result == 0)
981 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000982 return Result;
983}
984
Chris Lattner60a05cc2006-04-01 04:48:52 +0000985SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000986 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
987 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000988 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000989 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000990 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000991
992 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
993 Constant *LHSCV = LHSC->getValue();
994 Constant *RHSCV = RHSC->getValue();
Reid Spencer1628cec2006-10-26 06:15:43 +0000995 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +0000996 }
997 }
998
999 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1000
Chris Lattnerb3364092006-10-04 21:49:37 +00001001 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001002 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001003 return Result;
1004}
1005
1006
1007/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1008/// specified loop. Simplify the expression as much as possible.
1009SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1010 const SCEVHandle &Step, const Loop *L) {
1011 std::vector<SCEVHandle> Operands;
1012 Operands.push_back(Start);
1013 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1014 if (StepChrec->getLoop() == L) {
1015 Operands.insert(Operands.end(), StepChrec->op_begin(),
1016 StepChrec->op_end());
1017 return get(Operands, L);
1018 }
1019
1020 Operands.push_back(Step);
1021 return get(Operands, L);
1022}
1023
1024/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1025/// specified loop. Simplify the expression as much as possible.
1026SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1027 const Loop *L) {
1028 if (Operands.size() == 1) return Operands[0];
1029
1030 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1031 if (StepC->getValue()->isNullValue()) {
1032 Operands.pop_back();
1033 return get(Operands, L); // { X,+,0 } --> X
1034 }
1035
1036 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001037 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1038 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001039 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1040 return Result;
1041}
1042
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001043SCEVHandle SCEVUnknown::get(Value *V) {
1044 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1045 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001046 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001047 if (Result == 0) Result = new SCEVUnknown(V);
1048 return Result;
1049}
1050
Chris Lattner53e677a2004-04-02 20:23:17 +00001051
1052//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001053// ScalarEvolutionsImpl Definition and Implementation
1054//===----------------------------------------------------------------------===//
1055//
1056/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1057/// evolution code.
1058///
1059namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001060 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001061 /// F - The function we are analyzing.
1062 ///
1063 Function &F;
1064
1065 /// LI - The loop information for the function we are currently analyzing.
1066 ///
1067 LoopInfo &LI;
1068
1069 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1070 /// things.
1071 SCEVHandle UnknownValue;
1072
1073 /// Scalars - This is a cache of the scalars we have analyzed so far.
1074 ///
1075 std::map<Value*, SCEVHandle> Scalars;
1076
1077 /// IterationCounts - Cache the iteration count of the loops for this
1078 /// function as they are computed.
1079 std::map<const Loop*, SCEVHandle> IterationCounts;
1080
Chris Lattner3221ad02004-04-17 22:58:41 +00001081 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1082 /// the PHI instructions that we attempt to compute constant evolutions for.
1083 /// This allows us to avoid potentially expensive recomputation of these
1084 /// properties. An instruction maps to null if we are unable to compute its
1085 /// exit value.
1086 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001087
Chris Lattner53e677a2004-04-02 20:23:17 +00001088 public:
1089 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1090 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1091
1092 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1093 /// expression and create a new one.
1094 SCEVHandle getSCEV(Value *V);
1095
Chris Lattnera0740fb2005-08-09 23:36:33 +00001096 /// hasSCEV - Return true if the SCEV for this value has already been
1097 /// computed.
1098 bool hasSCEV(Value *V) const {
1099 return Scalars.count(V);
1100 }
1101
1102 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1103 /// the specified value.
1104 void setSCEV(Value *V, const SCEVHandle &H) {
1105 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1106 assert(isNew && "This entry already existed!");
1107 }
1108
1109
Chris Lattner53e677a2004-04-02 20:23:17 +00001110 /// getSCEVAtScope - Compute the value of the specified expression within
1111 /// the indicated loop (which may be null to indicate in no loop). If the
1112 /// expression cannot be evaluated, return UnknownValue itself.
1113 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1114
1115
1116 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1117 /// an analyzable loop-invariant iteration count.
1118 bool hasLoopInvariantIterationCount(const Loop *L);
1119
1120 /// getIterationCount - If the specified loop has a predictable iteration
1121 /// count, return it. Note that it is not valid to call this method on a
1122 /// loop without a loop-invariant iteration count.
1123 SCEVHandle getIterationCount(const Loop *L);
1124
1125 /// deleteInstructionFromRecords - This method should be called by the
1126 /// client before it removes an instruction from the program, to make sure
1127 /// that no dangling references are left around.
1128 void deleteInstructionFromRecords(Instruction *I);
1129
1130 private:
1131 /// createSCEV - We know that there is no SCEV for the specified value.
1132 /// Analyze the expression.
1133 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001134
1135 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1136 /// SCEVs.
1137 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001138
1139 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1140 /// for the specified instruction and replaces any references to the
1141 /// symbolic value SymName with the specified value. This is used during
1142 /// PHI resolution.
1143 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1144 const SCEVHandle &SymName,
1145 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001146
1147 /// ComputeIterationCount - Compute the number of times the specified loop
1148 /// will iterate.
1149 SCEVHandle ComputeIterationCount(const Loop *L);
1150
Chris Lattner673e02b2004-10-12 01:49:27 +00001151 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1152 /// 'setcc load X, cst', try to se if we can compute the trip count.
1153 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1154 Constant *RHS,
1155 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001156 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001157
Chris Lattner7980fb92004-04-17 18:36:24 +00001158 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1159 /// constant number of times (the condition evolves only from constants),
1160 /// try to evaluate a few iterations of the loop until we get the exit
1161 /// condition gets a value of ExitWhen (true or false). If we cannot
1162 /// evaluate the trip count of the loop, return UnknownValue.
1163 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1164 bool ExitWhen);
1165
Chris Lattner53e677a2004-04-02 20:23:17 +00001166 /// HowFarToZero - Return the number of times a backedge comparing the
1167 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001168 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001169 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1170
1171 /// HowFarToNonZero - Return the number of times a backedge checking the
1172 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001173 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001174 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001175
Chris Lattnerdb25de42005-08-15 23:33:51 +00001176 /// HowManyLessThans - Return the number of times a backedge containing the
1177 /// specified less-than comparison will execute. If not computable, return
1178 /// UnknownValue.
1179 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1180
Chris Lattner3221ad02004-04-17 22:58:41 +00001181 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1182 /// in the header of its containing loop, we know the loop executes a
1183 /// constant number of times, and the PHI node is just a recurrence
1184 /// involving constants, fold it.
1185 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1186 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001187 };
1188}
1189
1190//===----------------------------------------------------------------------===//
1191// Basic SCEV Analysis and PHI Idiom Recognition Code
1192//
1193
1194/// deleteInstructionFromRecords - This method should be called by the
1195/// client before it removes an instruction from the program, to make sure
1196/// that no dangling references are left around.
1197void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1198 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001199 if (PHINode *PN = dyn_cast<PHINode>(I))
1200 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001201}
1202
1203
1204/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1205/// expression and create a new one.
1206SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1207 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1208
1209 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1210 if (I != Scalars.end()) return I->second;
1211 SCEVHandle S = createSCEV(V);
1212 Scalars.insert(std::make_pair(V, S));
1213 return S;
1214}
1215
Chris Lattner4dc534c2005-02-13 04:37:18 +00001216/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1217/// the specified instruction and replaces any references to the symbolic value
1218/// SymName with the specified value. This is used during PHI resolution.
1219void ScalarEvolutionsImpl::
1220ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1221 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001222 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001223 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001224
Chris Lattner4dc534c2005-02-13 04:37:18 +00001225 SCEVHandle NV =
1226 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1227 if (NV == SI->second) return; // No change.
1228
1229 SI->second = NV; // Update the scalars map!
1230
1231 // Any instruction values that use this instruction might also need to be
1232 // updated!
1233 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1234 UI != E; ++UI)
1235 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1236}
Chris Lattner53e677a2004-04-02 20:23:17 +00001237
1238/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1239/// a loop header, making it a potential recurrence, or it doesn't.
1240///
1241SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1242 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1243 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1244 if (L->getHeader() == PN->getParent()) {
1245 // If it lives in the loop header, it has two incoming values, one
1246 // from outside the loop, and one from inside.
1247 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1248 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001249
Chris Lattner53e677a2004-04-02 20:23:17 +00001250 // While we are analyzing this PHI node, handle its value symbolically.
1251 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1252 assert(Scalars.find(PN) == Scalars.end() &&
1253 "PHI node already processed?");
1254 Scalars.insert(std::make_pair(PN, SymbolicName));
1255
1256 // Using this symbolic name for the PHI, analyze the value coming around
1257 // the back-edge.
1258 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1259
1260 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1261 // has a special value for the first iteration of the loop.
1262
1263 // If the value coming around the backedge is an add with the symbolic
1264 // value we just inserted, then we found a simple induction variable!
1265 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1266 // If there is a single occurrence of the symbolic value, replace it
1267 // with a recurrence.
1268 unsigned FoundIndex = Add->getNumOperands();
1269 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1270 if (Add->getOperand(i) == SymbolicName)
1271 if (FoundIndex == e) {
1272 FoundIndex = i;
1273 break;
1274 }
1275
1276 if (FoundIndex != Add->getNumOperands()) {
1277 // Create an add with everything but the specified operand.
1278 std::vector<SCEVHandle> Ops;
1279 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1280 if (i != FoundIndex)
1281 Ops.push_back(Add->getOperand(i));
1282 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1283
1284 // This is not a valid addrec if the step amount is varying each
1285 // loop iteration, but is not itself an addrec in this loop.
1286 if (Accum->isLoopInvariant(L) ||
1287 (isa<SCEVAddRecExpr>(Accum) &&
1288 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1289 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1290 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1291
1292 // Okay, for the entire analysis of this edge we assumed the PHI
1293 // to be symbolic. We now need to go back and update all of the
1294 // entries for the scalars that use the PHI (except for the PHI
1295 // itself) to use the new analyzed value instead of the "symbolic"
1296 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001297 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001298 return PHISCEV;
1299 }
1300 }
Chris Lattner97156e72006-04-26 18:34:07 +00001301 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1302 // Otherwise, this could be a loop like this:
1303 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1304 // In this case, j = {1,+,1} and BEValue is j.
1305 // Because the other in-value of i (0) fits the evolution of BEValue
1306 // i really is an addrec evolution.
1307 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1308 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1309
1310 // If StartVal = j.start - j.stride, we can use StartVal as the
1311 // initial step of the addrec evolution.
1312 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1313 AddRec->getOperand(1))) {
1314 SCEVHandle PHISCEV =
1315 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1316
1317 // Okay, for the entire analysis of this edge we assumed the PHI
1318 // to be symbolic. We now need to go back and update all of the
1319 // entries for the scalars that use the PHI (except for the PHI
1320 // itself) to use the new analyzed value instead of the "symbolic"
1321 // value.
1322 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1323 return PHISCEV;
1324 }
1325 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001326 }
1327
1328 return SymbolicName;
1329 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001330
Chris Lattner53e677a2004-04-02 20:23:17 +00001331 // If it's not a loop phi, we can't handle it yet.
1332 return SCEVUnknown::get(PN);
1333}
1334
Chris Lattnera17f0392006-12-12 02:26:09 +00001335/// GetConstantFactor - Determine the largest constant factor that S has. For
1336/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
1337static uint64_t GetConstantFactor(SCEVHandle S) {
1338 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1339 if (uint64_t V = C->getValue()->getZExtValue())
1340 return V;
1341 else // Zero is a multiple of everything.
1342 return 1ULL << (S->getType()->getPrimitiveSizeInBits()-1);
1343 }
1344
1345 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1346 return GetConstantFactor(T->getOperand()) &
1347 T->getType()->getIntegralTypeMask();
1348 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1349 return GetConstantFactor(E->getOperand());
1350
1351 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1352 // The result is the min of all operands.
1353 uint64_t Res = GetConstantFactor(A->getOperand(0));
1354 for (unsigned i = 1, e = A->getNumOperands(); i != e && Res > 1; ++i)
1355 Res = std::min(Res, GetConstantFactor(A->getOperand(i)));
1356 return Res;
1357 }
1358
1359 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1360 // The result is the product of all the operands.
1361 uint64_t Res = GetConstantFactor(M->getOperand(0));
1362 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i)
1363 Res *= GetConstantFactor(M->getOperand(i));
1364 return Res;
1365 }
1366
1367 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001368 // For now, we just handle linear expressions.
1369 if (A->getNumOperands() == 2) {
1370 // We want the GCD between the start and the stride value.
1371 uint64_t Start = GetConstantFactor(A->getOperand(0));
1372 if (Start == 1) return 1;
1373 uint64_t Stride = GetConstantFactor(A->getOperand(1));
1374 return GreatestCommonDivisor64(Start, Stride);
1375 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001376 }
1377
1378 // SCEVSDivExpr, SCEVUnknown.
1379 return 1;
1380}
Chris Lattner53e677a2004-04-02 20:23:17 +00001381
1382/// createSCEV - We know that there is no SCEV for the specified value.
1383/// Analyze the expression.
1384///
1385SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1386 if (Instruction *I = dyn_cast<Instruction>(V)) {
1387 switch (I->getOpcode()) {
1388 case Instruction::Add:
1389 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1390 getSCEV(I->getOperand(1)));
1391 case Instruction::Mul:
1392 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1393 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001394 case Instruction::SDiv:
1395 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1396 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001397 break;
1398
1399 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001400 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1401 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001402 case Instruction::Or:
1403 // If the RHS of the Or is a constant, we may have something like:
1404 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1405 // optimizations will transparently handle this case.
1406 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1407 SCEVHandle LHS = getSCEV(I->getOperand(0));
1408 uint64_t CommonFact = GetConstantFactor(LHS);
1409 assert(CommonFact && "Common factor should at least be 1!");
1410 if (CommonFact > CI->getZExtValue()) {
1411 // If the LHS is a multiple that is larger than the RHS, use +.
1412 return SCEVAddExpr::get(LHS,
1413 getSCEV(I->getOperand(1)));
1414 }
1415 }
1416 break;
1417
Chris Lattner53e677a2004-04-02 20:23:17 +00001418 case Instruction::Shl:
1419 // Turn shift left of a constant amount into a multiply.
1420 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1421 Constant *X = ConstantInt::get(V->getType(), 1);
1422 X = ConstantExpr::getShl(X, SA);
1423 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1424 }
1425 break;
1426
Reid Spencer3da59db2006-11-27 01:05:10 +00001427 case Instruction::Trunc:
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001428 // We don't handle trunc to bool yet.
1429 if (I->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001430 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)),
1431 I->getType()->getUnsignedVersion());
1432 break;
1433
1434 case Instruction::ZExt:
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001435 // We don't handle zext from bool yet.
1436 if (I->getOperand(0)->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001437 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)),
1438 I->getType()->getUnsignedVersion());
1439 break;
1440
1441 case Instruction::BitCast:
1442 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001443 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1444 return getSCEV(I->getOperand(0));
1445 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001446
1447 case Instruction::PHI:
1448 return createNodeForPHI(cast<PHINode>(I));
1449
1450 default: // We cannot analyze this expression.
1451 break;
1452 }
1453 }
1454
1455 return SCEVUnknown::get(V);
1456}
1457
1458
1459
1460//===----------------------------------------------------------------------===//
1461// Iteration Count Computation Code
1462//
1463
1464/// getIterationCount - If the specified loop has a predictable iteration
1465/// count, return it. Note that it is not valid to call this method on a
1466/// loop without a loop-invariant iteration count.
1467SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1468 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1469 if (I == IterationCounts.end()) {
1470 SCEVHandle ItCount = ComputeIterationCount(L);
1471 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1472 if (ItCount != UnknownValue) {
1473 assert(ItCount->isLoopInvariant(L) &&
1474 "Computed trip count isn't loop invariant for loop!");
1475 ++NumTripCountsComputed;
1476 } else if (isa<PHINode>(L->getHeader()->begin())) {
1477 // Only count loops that have phi nodes as not being computable.
1478 ++NumTripCountsNotComputed;
1479 }
1480 }
1481 return I->second;
1482}
1483
1484/// ComputeIterationCount - Compute the number of times the specified loop
1485/// will iterate.
1486SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1487 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001488 std::vector<BasicBlock*> ExitBlocks;
1489 L->getExitBlocks(ExitBlocks);
1490 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001491
1492 // Okay, there is one exit block. Try to find the condition that causes the
1493 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001494 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001495
1496 BasicBlock *ExitingBlock = 0;
1497 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1498 PI != E; ++PI)
1499 if (L->contains(*PI)) {
1500 if (ExitingBlock == 0)
1501 ExitingBlock = *PI;
1502 else
1503 return UnknownValue; // More than one block exiting!
1504 }
1505 assert(ExitingBlock && "No exits from loop, something is broken!");
1506
1507 // Okay, we've computed the exiting block. See what condition causes us to
1508 // exit.
1509 //
1510 // FIXME: we should be able to handle switch instructions (with a single exit)
1511 // FIXME: We should handle cast of int to bool as well
1512 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1513 if (ExitBr == 0) return UnknownValue;
1514 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001515 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1516
1517 // If its not an integer comparison then compute it the hard way.
1518 // Note that ICmpInst deals with pointer comparisons too so we must check
1519 // the type of the operand.
1520 if (ExitCond == 0 || !ExitCond->getOperand(0)->getType()->isIntegral())
Chris Lattner7980fb92004-04-17 18:36:24 +00001521 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1522 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001523
Reid Spencere4d87aa2006-12-23 06:05:41 +00001524 // If the condition was exit on true, convert the condition to exit on false
1525 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001526 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001527 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001528 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001529 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001530
1531 // Handle common loops like: for (X = "string"; *X; ++X)
1532 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1533 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1534 SCEVHandle ItCnt =
1535 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1536 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1537 }
1538
Chris Lattner53e677a2004-04-02 20:23:17 +00001539 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1540 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1541
1542 // Try to evaluate any dependencies out of the loop.
1543 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1544 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1545 Tmp = getSCEVAtScope(RHS, L);
1546 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1547
Reid Spencere4d87aa2006-12-23 06:05:41 +00001548 // At this point, we would like to compute how many iterations of the
1549 // loop the predicate will return true for these inputs.
Chris Lattner53e677a2004-04-02 20:23:17 +00001550 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1551 // If there is a constant, force it into the RHS.
1552 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001553 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001554 }
1555
1556 // FIXME: think about handling pointer comparisons! i.e.:
1557 // while (P != P+100) ++P;
1558
1559 // If we have a comparison of a chrec against a constant, try to use value
1560 // ranges to answer this query.
1561 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1562 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1563 if (AddRec->getLoop() == L) {
1564 // Form the comparison range using the constant of the correct type so
1565 // that the ConstantRange class knows to do a signed or unsigned
1566 // comparison.
1567 ConstantInt *CompVal = RHSC->getValue();
1568 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001569 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001570 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001571 if (CompVal) {
1572 // Form the constant range.
1573 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001574
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 // Now that we have it, if it's signed, convert it to an unsigned
1576 // range.
Reid Spencer2e20d392006-12-21 06:43:46 +00001577 // FIXME:Signless. This entire if statement can go away when
1578 // integers are signless. ConstantRange is already signless.
Chris Lattner53e677a2004-04-02 20:23:17 +00001579 if (CompRange.getLower()->getType()->isSigned()) {
1580 const Type *NewTy = RHSC->getValue()->getType();
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001581 Constant *NewL = ConstantExpr::getBitCast(CompRange.getLower(),
1582 NewTy);
1583 Constant *NewU = ConstantExpr::getBitCast(CompRange.getUpper(),
1584 NewTy);
Chris Lattner53e677a2004-04-02 20:23:17 +00001585 CompRange = ConstantRange(NewL, NewU);
1586 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001587
Reid Spencere4d87aa2006-12-23 06:05:41 +00001588 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange,
1589 ICmpInst::isSignedPredicate(Cond));
Chris Lattner53e677a2004-04-02 20:23:17 +00001590 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1591 }
1592 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001593
Chris Lattner53e677a2004-04-02 20:23:17 +00001594 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001595 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001596 // Convert to: while (X-Y != 0)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001597 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1598 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001599 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001600 }
1601 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001602 // Convert to: while (X-Y == 0) // while (X == Y)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001603 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1604 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001606 }
1607 case ICmpInst::ICMP_SLT: {
1608 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1609 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001610 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001611 }
1612 case ICmpInst::ICMP_SGT: {
1613 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1614 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001615 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001616 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001617 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001618#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001619 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001621 cerr << "[unsigned] ";
1622 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001623 << Instruction::getOpcodeName(Instruction::ICmp)
1624 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001625#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001626 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001628 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001629 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00001630}
1631
Chris Lattner673e02b2004-10-12 01:49:27 +00001632static ConstantInt *
1633EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1634 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1635 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1636 assert(isa<SCEVConstant>(Val) &&
1637 "Evaluation of SCEV at constant didn't fold correctly?");
1638 return cast<SCEVConstant>(Val)->getValue();
1639}
1640
1641/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1642/// and a GEP expression (missing the pointer index) indexing into it, return
1643/// the addressed element of the initializer or null if the index expression is
1644/// invalid.
1645static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001646GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001647 const std::vector<ConstantInt*> &Indices) {
1648 Constant *Init = GV->getInitializer();
1649 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001650 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001651 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1652 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1653 Init = cast<Constant>(CS->getOperand(Idx));
1654 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1655 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1656 Init = cast<Constant>(CA->getOperand(Idx));
1657 } else if (isa<ConstantAggregateZero>(Init)) {
1658 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1659 assert(Idx < STy->getNumElements() && "Bad struct index!");
1660 Init = Constant::getNullValue(STy->getElementType(Idx));
1661 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1662 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1663 Init = Constant::getNullValue(ATy->getElementType());
1664 } else {
1665 assert(0 && "Unknown constant aggregate type!");
1666 }
1667 return 0;
1668 } else {
1669 return 0; // Unknown initializer type
1670 }
1671 }
1672 return Init;
1673}
1674
1675/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1676/// 'setcc load X, cst', try to se if we can compute the trip count.
1677SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001678ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001679 const Loop *L,
1680 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001681 if (LI->isVolatile()) return UnknownValue;
1682
1683 // Check to see if the loaded pointer is a getelementptr of a global.
1684 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1685 if (!GEP) return UnknownValue;
1686
1687 // Make sure that it is really a constant global we are gepping, with an
1688 // initializer, and make sure the first IDX is really 0.
1689 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1690 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1691 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1692 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1693 return UnknownValue;
1694
1695 // Okay, we allow one non-constant index into the GEP instruction.
1696 Value *VarIdx = 0;
1697 std::vector<ConstantInt*> Indexes;
1698 unsigned VarIdxNum = 0;
1699 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1700 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1701 Indexes.push_back(CI);
1702 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1703 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1704 VarIdx = GEP->getOperand(i);
1705 VarIdxNum = i-2;
1706 Indexes.push_back(0);
1707 }
1708
1709 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1710 // Check to see if X is a loop variant variable value now.
1711 SCEVHandle Idx = getSCEV(VarIdx);
1712 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1713 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1714
1715 // We can only recognize very limited forms of loop index expressions, in
1716 // particular, only affine AddRec's like {C1,+,C2}.
1717 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1718 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1719 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1720 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1721 return UnknownValue;
1722
1723 unsigned MaxSteps = MaxBruteForceIterations;
1724 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001725 ConstantInt *ItCst =
1726 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001727 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1728
1729 // Form the GEP offset.
1730 Indexes[VarIdxNum] = Val;
1731
1732 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1733 if (Result == 0) break; // Cannot compute!
1734
1735 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001736 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Chris Lattner673e02b2004-10-12 01:49:27 +00001737 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
Chris Lattner003cbf32006-09-28 23:36:21 +00001738 if (cast<ConstantBool>(Result)->getValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001739#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001740 cerr << "\n***\n*** Computed loop count " << *ItCst
1741 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1742 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001743#endif
1744 ++NumArrayLenItCounts;
1745 return SCEVConstant::get(ItCst); // Found terminating iteration!
1746 }
1747 }
1748 return UnknownValue;
1749}
1750
1751
Chris Lattner3221ad02004-04-17 22:58:41 +00001752/// CanConstantFold - Return true if we can constant fold an instruction of the
1753/// specified type, assuming that all operands were constants.
1754static bool CanConstantFold(const Instruction *I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001755 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00001756 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1757 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001758
Chris Lattner3221ad02004-04-17 22:58:41 +00001759 if (const CallInst *CI = dyn_cast<CallInst>(I))
1760 if (const Function *F = CI->getCalledFunction())
1761 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1762 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001763}
1764
Chris Lattner3221ad02004-04-17 22:58:41 +00001765/// ConstantFold - Constant fold an instruction of the specified type with the
1766/// specified constant operands. This function may modify the operands vector.
1767static Constant *ConstantFold(const Instruction *I,
1768 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001769 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1770 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1771
Reid Spencer3da59db2006-11-27 01:05:10 +00001772 if (isa<CastInst>(I))
1773 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1774
Chris Lattner7980fb92004-04-17 18:36:24 +00001775 switch (I->getOpcode()) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001776 case Instruction::Select:
1777 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1778 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001779 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001780 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001781 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001782 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001783 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001784 case Instruction::GetElementPtr: {
Chris Lattner7980fb92004-04-17 18:36:24 +00001785 Constant *Base = Operands[0];
1786 Operands.erase(Operands.begin());
1787 return ConstantExpr::getGetElementPtr(Base, Operands);
1788 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001789 case Instruction::ICmp:
1790 return ConstantExpr::getICmp(
1791 cast<ICmpInst>(I)->getPredicate(), Operands[0], Operands[1]);
1792 case Instruction::FCmp:
1793 return ConstantExpr::getFCmp(
1794 cast<FCmpInst>(I)->getPredicate(), Operands[0], Operands[1]);
1795 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001796 return 0;
1797}
1798
1799
Chris Lattner3221ad02004-04-17 22:58:41 +00001800/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1801/// in the loop that V is derived from. We allow arbitrary operations along the
1802/// way, but the operands of an operation must either be constants or a value
1803/// derived from a constant PHI. If this expression does not fit with these
1804/// constraints, return null.
1805static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1806 // If this is not an instruction, or if this is an instruction outside of the
1807 // loop, it can't be derived from a loop PHI.
1808 Instruction *I = dyn_cast<Instruction>(V);
1809 if (I == 0 || !L->contains(I->getParent())) return 0;
1810
1811 if (PHINode *PN = dyn_cast<PHINode>(I))
1812 if (L->getHeader() == I->getParent())
1813 return PN;
1814 else
1815 // We don't currently keep track of the control flow needed to evaluate
1816 // PHIs, so we cannot handle PHIs inside of loops.
1817 return 0;
1818
1819 // If we won't be able to constant fold this expression even if the operands
1820 // are constants, return early.
1821 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001822
Chris Lattner3221ad02004-04-17 22:58:41 +00001823 // Otherwise, we can evaluate this instruction if all of its operands are
1824 // constant or derived from a PHI node themselves.
1825 PHINode *PHI = 0;
1826 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1827 if (!(isa<Constant>(I->getOperand(Op)) ||
1828 isa<GlobalValue>(I->getOperand(Op)))) {
1829 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1830 if (P == 0) return 0; // Not evolving from PHI
1831 if (PHI == 0)
1832 PHI = P;
1833 else if (PHI != P)
1834 return 0; // Evolving from multiple different PHIs.
1835 }
1836
1837 // This is a expression evolving from a constant PHI!
1838 return PHI;
1839}
1840
1841/// EvaluateExpression - Given an expression that passes the
1842/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1843/// in the loop has the value PHIVal. If we can't fold this expression for some
1844/// reason, return null.
1845static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1846 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001847 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001848 return GV;
1849 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001850 Instruction *I = cast<Instruction>(V);
1851
1852 std::vector<Constant*> Operands;
1853 Operands.resize(I->getNumOperands());
1854
1855 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1856 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1857 if (Operands[i] == 0) return 0;
1858 }
1859
1860 return ConstantFold(I, Operands);
1861}
1862
1863/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1864/// in the header of its containing loop, we know the loop executes a
1865/// constant number of times, and the PHI node is just a recurrence
1866/// involving constants, fold it.
1867Constant *ScalarEvolutionsImpl::
1868getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1869 std::map<PHINode*, Constant*>::iterator I =
1870 ConstantEvolutionLoopExitValue.find(PN);
1871 if (I != ConstantEvolutionLoopExitValue.end())
1872 return I->second;
1873
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001874 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001875 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1876
1877 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1878
1879 // Since the loop is canonicalized, the PHI node must have two entries. One
1880 // entry must be a constant (coming in from outside of the loop), and the
1881 // second must be derived from the same PHI.
1882 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1883 Constant *StartCST =
1884 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1885 if (StartCST == 0)
1886 return RetVal = 0; // Must be a constant.
1887
1888 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1889 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1890 if (PN2 != PN)
1891 return RetVal = 0; // Not derived from same PHI.
1892
1893 // Execute the loop symbolically to determine the exit value.
1894 unsigned IterationNum = 0;
1895 unsigned NumIterations = Its;
1896 if (NumIterations != Its)
1897 return RetVal = 0; // More than 2^32 iterations??
1898
1899 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1900 if (IterationNum == NumIterations)
1901 return RetVal = PHIVal; // Got exit value!
1902
1903 // Compute the value of the PHI node for the next iteration.
1904 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1905 if (NextPHI == PHIVal)
1906 return RetVal = NextPHI; // Stopped evolving!
1907 if (NextPHI == 0)
1908 return 0; // Couldn't evaluate!
1909 PHIVal = NextPHI;
1910 }
1911}
1912
Chris Lattner7980fb92004-04-17 18:36:24 +00001913/// ComputeIterationCountExhaustively - If the trip is known to execute a
1914/// constant number of times (the condition evolves only from constants),
1915/// try to evaluate a few iterations of the loop until we get the exit
1916/// condition gets a value of ExitWhen (true or false). If we cannot
1917/// evaluate the trip count of the loop, return UnknownValue.
1918SCEVHandle ScalarEvolutionsImpl::
1919ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1920 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1921 if (PN == 0) return UnknownValue;
1922
1923 // Since the loop is canonicalized, the PHI node must have two entries. One
1924 // entry must be a constant (coming in from outside of the loop), and the
1925 // second must be derived from the same PHI.
1926 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1927 Constant *StartCST =
1928 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1929 if (StartCST == 0) return UnknownValue; // Must be a constant.
1930
1931 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1932 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1933 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1934
1935 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1936 // the loop symbolically to determine when the condition gets a value of
1937 // "ExitWhen".
1938 unsigned IterationNum = 0;
1939 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1940 for (Constant *PHIVal = StartCST;
1941 IterationNum != MaxIterations; ++IterationNum) {
1942 ConstantBool *CondVal =
1943 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1944 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001945
Chris Lattner7980fb92004-04-17 18:36:24 +00001946 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001947 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001948 ++NumBruteForceTripCountsComputed;
Reid Spencerb83eb642006-10-20 07:07:24 +00001949 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001950 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001951
Chris Lattner3221ad02004-04-17 22:58:41 +00001952 // Compute the value of the PHI node for the next iteration.
1953 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1954 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001955 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001956 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001957 }
1958
1959 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001960 return UnknownValue;
1961}
1962
1963/// getSCEVAtScope - Compute the value of the specified expression within the
1964/// indicated loop (which may be null to indicate in no loop). If the
1965/// expression cannot be evaluated, return UnknownValue.
1966SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1967 // FIXME: this should be turned into a virtual method on SCEV!
1968
Chris Lattner3221ad02004-04-17 22:58:41 +00001969 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001970
Chris Lattner3221ad02004-04-17 22:58:41 +00001971 // If this instruction is evolves from a constant-evolving PHI, compute the
1972 // exit value from the loop without using SCEVs.
1973 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1974 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1975 const Loop *LI = this->LI[I->getParent()];
1976 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1977 if (PHINode *PN = dyn_cast<PHINode>(I))
1978 if (PN->getParent() == LI->getHeader()) {
1979 // Okay, there is no closed form solution for the PHI node. Check
1980 // to see if the loop that contains it has a known iteration count.
1981 // If so, we may be able to force computation of the exit value.
1982 SCEVHandle IterationCount = getIterationCount(LI);
1983 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1984 // Okay, we know how many times the containing loop executes. If
1985 // this is a constant evolving PHI node, get the final value at
1986 // the specified iteration number.
1987 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001988 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001989 LI);
1990 if (RV) return SCEVUnknown::get(RV);
1991 }
1992 }
1993
Reid Spencer09906f32006-12-04 21:33:23 +00001994 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00001995 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00001996 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00001997 // result. This is particularly useful for computing loop exit values.
1998 if (CanConstantFold(I)) {
1999 std::vector<Constant*> Operands;
2000 Operands.reserve(I->getNumOperands());
2001 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2002 Value *Op = I->getOperand(i);
2003 if (Constant *C = dyn_cast<Constant>(Op)) {
2004 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002005 } else {
2006 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2007 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002008 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2009 Op->getType(),
2010 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002011 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2012 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002013 Operands.push_back(ConstantExpr::getIntegerCast(C,
2014 Op->getType(),
2015 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002016 else
2017 return V;
2018 } else {
2019 return V;
2020 }
2021 }
2022 }
2023 return SCEVUnknown::get(ConstantFold(I, Operands));
2024 }
2025 }
2026
2027 // This is some other type of SCEVUnknown, just return it.
2028 return V;
2029 }
2030
Chris Lattner53e677a2004-04-02 20:23:17 +00002031 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2032 // Avoid performing the look-up in the common case where the specified
2033 // expression has no loop-variant portions.
2034 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2035 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2036 if (OpAtScope != Comm->getOperand(i)) {
2037 if (OpAtScope == UnknownValue) return UnknownValue;
2038 // Okay, at least one of these operands is loop variant but might be
2039 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002040 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002041 NewOps.push_back(OpAtScope);
2042
2043 for (++i; i != e; ++i) {
2044 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2045 if (OpAtScope == UnknownValue) return UnknownValue;
2046 NewOps.push_back(OpAtScope);
2047 }
2048 if (isa<SCEVAddExpr>(Comm))
2049 return SCEVAddExpr::get(NewOps);
2050 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2051 return SCEVMulExpr::get(NewOps);
2052 }
2053 }
2054 // If we got here, all operands are loop invariant.
2055 return Comm;
2056 }
2057
Chris Lattner60a05cc2006-04-01 04:48:52 +00002058 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2059 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002060 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002061 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002062 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002063 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2064 return Div; // must be loop invariant
2065 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002066 }
2067
2068 // If this is a loop recurrence for a loop that does not contain L, then we
2069 // are dealing with the final value computed by the loop.
2070 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2071 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2072 // To evaluate this recurrence, we need to know how many times the AddRec
2073 // loop iterates. Compute this now.
2074 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2075 if (IterationCount == UnknownValue) return UnknownValue;
2076 IterationCount = getTruncateOrZeroExtend(IterationCount,
2077 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002078
Chris Lattner53e677a2004-04-02 20:23:17 +00002079 // If the value is affine, simplify the expression evaluation to just
2080 // Start + Step*IterationCount.
2081 if (AddRec->isAffine())
2082 return SCEVAddExpr::get(AddRec->getStart(),
2083 SCEVMulExpr::get(IterationCount,
2084 AddRec->getOperand(1)));
2085
2086 // Otherwise, evaluate it the hard way.
2087 return AddRec->evaluateAtIteration(IterationCount);
2088 }
2089 return UnknownValue;
2090 }
2091
2092 //assert(0 && "Unknown SCEV type!");
2093 return UnknownValue;
2094}
2095
2096
2097/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2098/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2099/// might be the same) or two SCEVCouldNotCompute objects.
2100///
2101static std::pair<SCEVHandle,SCEVHandle>
2102SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2103 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2104 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2105 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2106 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002107
Chris Lattner53e677a2004-04-02 20:23:17 +00002108 // We currently can only solve this if the coefficients are constants.
2109 if (!L || !M || !N) {
2110 SCEV *CNC = new SCEVCouldNotCompute();
2111 return std::make_pair(CNC, CNC);
2112 }
2113
Reid Spencer1628cec2006-10-26 06:15:43 +00002114 Constant *C = L->getValue();
2115 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002116
Chris Lattner53e677a2004-04-02 20:23:17 +00002117 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002118 // The B coefficient is M-N/2
2119 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002120 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002121 Two));
2122 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002123 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002124
Chris Lattner53e677a2004-04-02 20:23:17 +00002125 // Compute the B^2-4ac term.
2126 Constant *SqrtTerm =
2127 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2128 ConstantExpr::getMul(A, C));
2129 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2130
2131 // Compute floor(sqrt(B^2-4ac))
Reid Spencerb83eb642006-10-20 07:07:24 +00002132 ConstantInt *SqrtVal =
Reid Spencerd977d862006-12-12 23:36:14 +00002133 cast<ConstantInt>(ConstantExpr::getBitCast(SqrtTerm,
Chris Lattner53e677a2004-04-02 20:23:17 +00002134 SqrtTerm->getType()->getUnsignedVersion()));
Reid Spencerb83eb642006-10-20 07:07:24 +00002135 uint64_t SqrtValV = SqrtVal->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002136 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002137 // The square root might not be precise for arbitrary 64-bit integer
2138 // values. Do some sanity checks to ensure it's correct.
2139 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2140 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2141 SCEV *CNC = new SCEVCouldNotCompute();
2142 return std::make_pair(CNC, CNC);
2143 }
2144
Reid Spencerb83eb642006-10-20 07:07:24 +00002145 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
Reid Spencerd977d862006-12-12 23:36:14 +00002146 SqrtTerm = ConstantExpr::getTruncOrBitCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002147
Chris Lattner53e677a2004-04-02 20:23:17 +00002148 Constant *NegB = ConstantExpr::getNeg(B);
2149 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002150
Chris Lattner53e677a2004-04-02 20:23:17 +00002151 // The divisions must be performed as signed divisions.
Reid Spencerd3773502006-12-21 18:59:16 +00002152 // FIXME:Signedness. These casts can all go away once integer types are
2153 // signless.
Chris Lattner53e677a2004-04-02 20:23:17 +00002154 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 =
Reid Spencere4d87aa2006-12-23 06:05:41 +00002227 dyn_cast<ConstantBool>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2228 R1->getValue(), 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());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002258 Constant *NonZero =
2259 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
Chris Lattner003cbf32006-09-28 23:36:21 +00002260 if (NonZero == ConstantBool::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002261 return getSCEV(Zero);
2262 return UnknownValue; // Otherwise it will loop infinitely.
2263 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002264
Chris Lattner53e677a2004-04-02 20:23:17 +00002265 // We could implement others, but I really doubt anyone writes loops like
2266 // this, and if they did, they would already be constant folded.
2267 return UnknownValue;
2268}
2269
Chris Lattnerdb25de42005-08-15 23:33:51 +00002270/// HowManyLessThans - Return the number of times a backedge containing the
2271/// specified less-than comparison will execute. If not computable, return
2272/// UnknownValue.
2273SCEVHandle ScalarEvolutionsImpl::
2274HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2275 // Only handle: "ADDREC < LoopInvariant".
2276 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2277
2278 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2279 if (!AddRec || AddRec->getLoop() != L)
2280 return UnknownValue;
2281
2282 if (AddRec->isAffine()) {
2283 // FORNOW: We only support unit strides.
2284 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2285 if (AddRec->getOperand(1) != One)
2286 return UnknownValue;
2287
2288 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2289 // know that m is >= n on input to the loop. If it is, the condition return
2290 // true zero times. What we really should return, for full generality, is
2291 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2292 // canonical loop form: most do-loops will have a check that dominates the
2293 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2294 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2295
2296 // Search for the check.
2297 BasicBlock *Preheader = L->getLoopPreheader();
2298 BasicBlock *PreheaderDest = L->getHeader();
2299 if (Preheader == 0) return UnknownValue;
2300
2301 BranchInst *LoopEntryPredicate =
2302 dyn_cast<BranchInst>(Preheader->getTerminator());
2303 if (!LoopEntryPredicate) return UnknownValue;
2304
2305 // This might be a critical edge broken out. If the loop preheader ends in
2306 // an unconditional branch to the loop, check to see if the preheader has a
2307 // single predecessor, and if so, look for its terminator.
2308 while (LoopEntryPredicate->isUnconditional()) {
2309 PreheaderDest = Preheader;
2310 Preheader = Preheader->getSinglePredecessor();
2311 if (!Preheader) return UnknownValue; // Multiple preds.
2312
2313 LoopEntryPredicate =
2314 dyn_cast<BranchInst>(Preheader->getTerminator());
2315 if (!LoopEntryPredicate) return UnknownValue;
2316 }
2317
2318 // Now that we found a conditional branch that dominates the loop, check to
2319 // see if it is the comparison we are looking for.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002320 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2321 Value *PreCondLHS = ICI->getOperand(0);
2322 Value *PreCondRHS = ICI->getOperand(1);
2323 ICmpInst::Predicate Cond;
2324 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2325 Cond = ICI->getPredicate();
2326 else
2327 Cond = ICI->getInversePredicate();
Chris Lattnerdb25de42005-08-15 23:33:51 +00002328
Reid Spencere4d87aa2006-12-23 06:05:41 +00002329 switch (Cond) {
2330 case ICmpInst::ICMP_UGT:
2331 std::swap(PreCondLHS, PreCondRHS);
2332 Cond = ICmpInst::ICMP_ULT;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002333 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002334 case ICmpInst::ICMP_SGT:
2335 std::swap(PreCondLHS, PreCondRHS);
2336 Cond = ICmpInst::ICMP_SLT;
2337 break;
2338 default: break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002339 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002340
Reid Spencere4d87aa2006-12-23 06:05:41 +00002341 if (Cond == ICmpInst::ICMP_SLT) {
2342 if (PreCondLHS->getType()->isInteger()) {
2343 if (RHS != getSCEV(PreCondRHS))
2344 return UnknownValue; // Not a comparison against 'm'.
2345
2346 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2347 != getSCEV(PreCondLHS))
2348 return UnknownValue; // Not a comparison against 'n-1'.
2349 }
2350 else return UnknownValue;
2351 } else if (Cond == ICmpInst::ICMP_ULT)
2352 return UnknownValue;
2353
2354 // cerr << "Computed Loop Trip Count as: "
2355 // << // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2356 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2357 }
2358 else
2359 return UnknownValue;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002360 }
2361
2362 return UnknownValue;
2363}
2364
Chris Lattner53e677a2004-04-02 20:23:17 +00002365/// getNumIterationsInRange - Return the number of iterations of this loop that
2366/// produce values in the specified constant range. Another way of looking at
2367/// this is that it returns the first iteration number where the value is not in
2368/// the condition, thus computing the exit count. If the iteration count can't
2369/// be computed, an instance of SCEVCouldNotCompute is returned.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002370SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2371 bool isSigned) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002372 if (Range.isFullSet()) // Infinite loop.
2373 return new SCEVCouldNotCompute();
2374
2375 // If the start is a non-zero constant, shift the range to simplify things.
2376 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2377 if (!SC->getValue()->isNullValue()) {
2378 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002379 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002380 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2381 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2382 return ShiftedAddRec->getNumIterationsInRange(
Reid Spencere4d87aa2006-12-23 06:05:41 +00002383 Range.subtract(SC->getValue()),isSigned);
Chris Lattner53e677a2004-04-02 20:23:17 +00002384 // This is strange and shouldn't happen.
2385 return new SCEVCouldNotCompute();
2386 }
2387
2388 // The only time we can solve this is when we have all constant indices.
2389 // Otherwise, we cannot determine the overflow conditions.
2390 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2391 if (!isa<SCEVConstant>(getOperand(i)))
2392 return new SCEVCouldNotCompute();
2393
2394
2395 // Okay at this point we know that all elements of the chrec are constants and
2396 // that the start element is zero.
2397
2398 // First check to see if the range contains zero. If not, the first
2399 // iteration exits.
2400 ConstantInt *Zero = ConstantInt::get(getType(), 0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002401 if (!Range.contains(Zero, isSigned)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002402
Chris Lattner53e677a2004-04-02 20:23:17 +00002403 if (isAffine()) {
2404 // If this is an affine expression then we have this situation:
2405 // Solve {0,+,A} in Range === Ax in Range
2406
2407 // Since we know that zero is in the range, we know that the upper value of
2408 // the range must be the first possible exit value. Also note that we
2409 // already checked for a full range.
2410 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2411 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2412 ConstantInt *One = ConstantInt::get(getType(), 1);
2413
2414 // The exit value should be (Upper+A-1)/A.
2415 Constant *ExitValue = Upper;
2416 if (A != One) {
2417 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002418 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002419 }
2420 assert(isa<ConstantInt>(ExitValue) &&
2421 "Constant folding of integers not implemented?");
2422
2423 // Evaluate at the exit value. If we really did fall out of the valid
2424 // range, then we computed our trip count, otherwise wrap around or other
2425 // things must have happened.
2426 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002427 if (Range.contains(Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002428 return new SCEVCouldNotCompute(); // Something strange happened
2429
2430 // Ensure that the previous value is in the range. This is a sanity check.
2431 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002432 ConstantExpr::getSub(ExitValue, One)), isSigned) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002433 "Linear scev computation is off in a bad way!");
2434 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2435 } else if (isQuadratic()) {
2436 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2437 // quadratic equation to solve it. To do this, we must frame our problem in
2438 // terms of figuring out when zero is crossed, instead of when
2439 // Range.getUpper() is crossed.
2440 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002441 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002442 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2443
2444 // Next, solve the constructed addrec
2445 std::pair<SCEVHandle,SCEVHandle> Roots =
2446 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2447 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2448 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2449 if (R1) {
2450 // Pick the smallest positive root value.
2451 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2452 if (ConstantBool *CB =
Reid Spencere4d87aa2006-12-23 06:05:41 +00002453 dyn_cast<ConstantBool>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2454 R1->getValue(), R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002455 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002456 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002457
Chris Lattner53e677a2004-04-02 20:23:17 +00002458 // Make sure the root is not off by one. The returned iteration should
2459 // not be in the range, but the previous one should be. When solving
2460 // for "X*X < 5", for example, we should not return a root of 2.
2461 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2462 R1->getValue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002463 if (Range.contains(R1Val, isSigned)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002464 // The next iteration must be out of the range...
2465 Constant *NextVal =
2466 ConstantExpr::getAdd(R1->getValue(),
2467 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002468
Chris Lattner53e677a2004-04-02 20:23:17 +00002469 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002470 if (!Range.contains(R1Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002471 return SCEVUnknown::get(NextVal);
2472 return new SCEVCouldNotCompute(); // Something strange happened
2473 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002474
Chris Lattner53e677a2004-04-02 20:23:17 +00002475 // If R1 was not in the range, then it is a good return value. Make
2476 // sure that R1-1 WAS in the range though, just in case.
2477 Constant *NextVal =
2478 ConstantExpr::getSub(R1->getValue(),
2479 ConstantInt::get(R1->getType(), 1));
2480 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002481 if (Range.contains(R1Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002482 return R1;
2483 return new SCEVCouldNotCompute(); // Something strange happened
2484 }
2485 }
2486 }
2487
2488 // Fallback, if this is a general polynomial, figure out the progression
2489 // through brute force: evaluate until we find an iteration that fails the
2490 // test. This is likely to be slow, but getting an accurate trip count is
2491 // incredibly important, we will be able to simplify the exit test a lot, and
2492 // we are almost guaranteed to get a trip count in this case.
2493 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2494 ConstantInt *One = ConstantInt::get(getType(), 1);
2495 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2496 do {
2497 ++NumBruteForceEvaluations;
2498 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2499 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2500 return new SCEVCouldNotCompute();
2501
2502 // Check to see if we found the value!
Reid Spencere4d87aa2006-12-23 06:05:41 +00002503 if (!Range.contains(cast<SCEVConstant>(Val)->getValue(), isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002504 return SCEVConstant::get(TestVal);
2505
2506 // Increment to test the next index.
2507 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2508 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002509
Chris Lattner53e677a2004-04-02 20:23:17 +00002510 return new SCEVCouldNotCompute();
2511}
2512
2513
2514
2515//===----------------------------------------------------------------------===//
2516// ScalarEvolution Class Implementation
2517//===----------------------------------------------------------------------===//
2518
2519bool ScalarEvolution::runOnFunction(Function &F) {
2520 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2521 return false;
2522}
2523
2524void ScalarEvolution::releaseMemory() {
2525 delete (ScalarEvolutionsImpl*)Impl;
2526 Impl = 0;
2527}
2528
2529void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2530 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002531 AU.addRequiredTransitive<LoopInfo>();
2532}
2533
2534SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2535 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2536}
2537
Chris Lattnera0740fb2005-08-09 23:36:33 +00002538/// hasSCEV - Return true if the SCEV for this value has already been
2539/// computed.
2540bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002541 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002542}
2543
2544
2545/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2546/// the specified value.
2547void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2548 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2549}
2550
2551
Chris Lattner53e677a2004-04-02 20:23:17 +00002552SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2553 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2554}
2555
2556bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2557 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2558}
2559
2560SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2561 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2562}
2563
2564void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2565 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2566}
2567
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002568static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002569 const Loop *L) {
2570 // Print all inner loops first
2571 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2572 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002573
Bill Wendlinge8156192006-12-07 01:30:32 +00002574 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002575
2576 std::vector<BasicBlock*> ExitBlocks;
2577 L->getExitBlocks(ExitBlocks);
2578 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002579 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002580
2581 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002582 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002583 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002584 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002585 }
2586
Bill Wendlinge8156192006-12-07 01:30:32 +00002587 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002588}
2589
Reid Spencerce9653c2004-12-07 04:03:45 +00002590void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002591 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2592 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2593
2594 OS << "Classifying expressions for: " << F.getName() << "\n";
2595 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002596 if (I->getType()->isInteger()) {
2597 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002598 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002599 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002600 SV->print(OS);
2601 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002602
Chris Lattner6ffe5512004-04-27 15:13:33 +00002603 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002604 ConstantRange Bounds = SV->getValueRange();
2605 if (!Bounds.isFullSet())
2606 OS << "Bounds: " << Bounds << " ";
2607 }
2608
Chris Lattner6ffe5512004-04-27 15:13:33 +00002609 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002610 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002611 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002612 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2613 OS << "<<Unknown>>";
2614 } else {
2615 OS << *ExitValue;
2616 }
2617 }
2618
2619
2620 OS << "\n";
2621 }
2622
2623 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2624 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2625 PrintLoopInfo(OS, this, *I);
2626}
2627