blob: dffb1d1bd1239316c18a07ff809500deb5205731 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman844731a2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman844731a2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000103char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
Chris Lattner53e677a2004-04-02 20:23:17 +0000112SCEV::~SCEV() {}
113void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000114 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000115}
116
Reid Spencer581b0d42007-02-28 19:57:34 +0000117uint32_t SCEV::getBitWidth() const {
118 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
119 return ITy->getBitWidth();
120 return 0;
121}
122
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000123bool SCEV::isZero() const {
124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
125 return SC->getValue()->isZero();
126 return false;
127}
128
Chris Lattner53e677a2004-04-02 20:23:17 +0000129
130SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
131
132bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
133 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000134 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000135}
136
137const Type *SCEVCouldNotCompute::getType() const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return false;
145}
146
Chris Lattner4dc534c2005-02-13 04:37:18 +0000147SCEVHandle SCEVCouldNotCompute::
148replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000149 const SCEVHandle &Conc,
150 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000151 return this;
152}
153
Chris Lattner53e677a2004-04-02 20:23:17 +0000154void SCEVCouldNotCompute::print(std::ostream &OS) const {
155 OS << "***COULDNOTCOMPUTE***";
156}
157
158bool SCEVCouldNotCompute::classof(const SCEV *S) {
159 return S->getSCEVType() == scCouldNotCompute;
160}
161
162
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000163// SCEVConstants - Only allow the creation of one SCEVConstant for any
164// particular value. Don't use a SCEVHandle here, or else the object will
165// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000166static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000167
Chris Lattner53e677a2004-04-02 20:23:17 +0000168
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000169SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000170 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171}
Chris Lattner53e677a2004-04-02 20:23:17 +0000172
Dan Gohman246b2562007-10-22 18:31:58 +0000173SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000174 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175 if (R == 0) R = new SCEVConstant(V);
176 return R;
177}
Chris Lattner53e677a2004-04-02 20:23:17 +0000178
Dan Gohman246b2562007-10-22 18:31:58 +0000179SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
180 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000181}
182
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185void SCEVConstant::print(std::ostream &OS) const {
186 WriteAsOperand(OS, V, false);
187}
Chris Lattner53e677a2004-04-02 20:23:17 +0000188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
190// particular input. Don't use a SCEVHandle here, or else the object will
191// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000192static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
193 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
196 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000197 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000199 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
200 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201}
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000204 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205}
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207void SCEVTruncateExpr::print(std::ostream &OS) const {
208 OS << "(truncate " << *Op << " to " << *Ty << ")";
209}
210
211// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
212// particular input. Don't use a SCEVHandle here, or else the object will never
213// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000214static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
215 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216
217SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000218 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000219 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000221 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
222 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
225SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000226 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227}
228
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000229void SCEVZeroExtendExpr::print(std::ostream &OS) const {
230 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
231}
232
Dan Gohmand19534a2007-06-15 14:38:12 +0000233// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
234// particular input. Don't use a SCEVHandle here, or else the object will never
235// be deleted!
236static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
237 SCEVSignExtendExpr*> > SCEVSignExtends;
238
239SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
240 : SCEV(scSignExtend), Op(op), Ty(ty) {
241 assert(Op->getType()->isInteger() && Ty->isInteger() &&
242 "Cannot sign extend non-integer value!");
243 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
244 && "This is not an extending conversion!");
245}
246
247SCEVSignExtendExpr::~SCEVSignExtendExpr() {
248 SCEVSignExtends->erase(std::make_pair(Op, Ty));
249}
250
Dan Gohmand19534a2007-06-15 14:38:12 +0000251void SCEVSignExtendExpr::print(std::ostream &OS) const {
252 OS << "(signextend " << *Op << " to " << *Ty << ")";
253}
254
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000255// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
256// particular input. Don't use a SCEVHandle here, or else the object will never
257// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000258static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
259 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000260
261SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000262 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
263 std::vector<SCEV*>(Operands.begin(),
264 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000265}
266
267void SCEVCommutativeExpr::print(std::ostream &OS) const {
268 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
269 const char *OpStr = getOperationStr();
270 OS << "(" << *Operands[0];
271 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
272 OS << OpStr << *Operands[i];
273 OS << ")";
274}
275
Chris Lattner4dc534c2005-02-13 04:37:18 +0000276SCEVHandle SCEVCommutativeExpr::
277replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000278 const SCEVHandle &Conc,
279 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000280 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000281 SCEVHandle H =
282 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000283 if (H != getOperand(i)) {
284 std::vector<SCEVHandle> NewOps;
285 NewOps.reserve(getNumOperands());
286 for (unsigned j = 0; j != i; ++j)
287 NewOps.push_back(getOperand(j));
288 NewOps.push_back(H);
289 for (++i; i != e; ++i)
290 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000291 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000292
293 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000294 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000295 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000296 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000297 else if (isa<SCEVSMaxExpr>(this))
298 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000299 else if (isa<SCEVUMaxExpr>(this))
300 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000301 else
302 assert(0 && "Unknown commutative expr!");
303 }
304 }
305 return this;
306}
307
308
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000309// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000310// input. Don't use a SCEVHandle here, or else the object will never be
311// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000312static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000313 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000315SCEVUDivExpr::~SCEVUDivExpr() {
316 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000317}
318
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000319void SCEVUDivExpr::print(std::ostream &OS) const {
320 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000321}
322
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000323const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000324 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000325}
326
327// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
328// particular input. Don't use a SCEVHandle here, or else the object will never
329// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000330static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
331 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000332
333SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000334 SCEVAddRecExprs->erase(std::make_pair(L,
335 std::vector<SCEV*>(Operands.begin(),
336 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
338
Chris Lattner4dc534c2005-02-13 04:37:18 +0000339SCEVHandle SCEVAddRecExpr::
340replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000341 const SCEVHandle &Conc,
342 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000343 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000344 SCEVHandle H =
345 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000346 if (H != getOperand(i)) {
347 std::vector<SCEVHandle> NewOps;
348 NewOps.reserve(getNumOperands());
349 for (unsigned j = 0; j != i; ++j)
350 NewOps.push_back(getOperand(j));
351 NewOps.push_back(H);
352 for (++i; i != e; ++i)
353 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000354 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000355
Dan Gohman246b2562007-10-22 18:31:58 +0000356 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000357 }
358 }
359 return this;
360}
361
362
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
364 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000365 // contain L and if the start is invariant.
366 return !QueryLoop->contains(L->getHeader()) &&
367 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000368}
369
370
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000371void SCEVAddRecExpr::print(std::ostream &OS) const {
372 OS << "{" << *Operands[0];
373 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
374 OS << ",+," << *Operands[i];
375 OS << "}<" << L->getHeader()->getName() + ">";
376}
Chris Lattner53e677a2004-04-02 20:23:17 +0000377
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000378// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
379// value. Don't use a SCEVHandle here, or else the object will never be
380// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000381static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000382
Chris Lattnerb3364092006-10-04 21:49:37 +0000383SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000384
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
386 // All non-instruction values are loop invariant. All instructions are loop
387 // invariant if they are not contained in the specified loop.
388 if (Instruction *I = dyn_cast<Instruction>(V))
389 return !L->contains(I->getParent());
390 return true;
391}
Chris Lattner53e677a2004-04-02 20:23:17 +0000392
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000393const Type *SCEVUnknown::getType() const {
394 return V->getType();
395}
Chris Lattner53e677a2004-04-02 20:23:17 +0000396
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000397void SCEVUnknown::print(std::ostream &OS) const {
398 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000399}
400
Chris Lattner8d741b82004-06-20 06:23:15 +0000401//===----------------------------------------------------------------------===//
402// SCEV Utilities
403//===----------------------------------------------------------------------===//
404
405namespace {
406 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
407 /// than the complexity of the RHS. This comparator is used to canonicalize
408 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000409 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000410 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000411 return LHS->getSCEVType() < RHS->getSCEVType();
412 }
413 };
414}
415
416/// GroupByComplexity - Given a list of SCEV objects, order them by their
417/// complexity, and group objects of the same complexity together by value.
418/// When this routine is finished, we know that any duplicates in the vector are
419/// consecutive and that complexity is monotonically increasing.
420///
421/// Note that we go take special precautions to ensure that we get determinstic
422/// results from this routine. In other words, we don't want the results of
423/// this to depend on where the addresses of various SCEV objects happened to
424/// land in memory.
425///
426static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
427 if (Ops.size() < 2) return; // Noop
428 if (Ops.size() == 2) {
429 // This is the common case, which also happens to be trivially simple.
430 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000431 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000432 std::swap(Ops[0], Ops[1]);
433 return;
434 }
435
436 // Do the rough sort by complexity.
437 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
438
439 // Now that we are sorted by complexity, group elements of the same
440 // complexity. Note that this is, at worst, N^2, but the vector is likely to
441 // be extremely short in practice. Note that we take this approach because we
442 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000443 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000444 SCEV *S = Ops[i];
445 unsigned Complexity = S->getSCEVType();
446
447 // If there are any objects of the same complexity and same value as this
448 // one, group them.
449 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
450 if (Ops[j] == S) { // Found a duplicate.
451 // Move it to immediately after i'th element.
452 std::swap(Ops[i+1], Ops[j]);
453 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000454 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000455 }
456 }
457 }
458}
459
Chris Lattner53e677a2004-04-02 20:23:17 +0000460
Chris Lattner53e677a2004-04-02 20:23:17 +0000461
462//===----------------------------------------------------------------------===//
463// Simple SCEV method implementations
464//===----------------------------------------------------------------------===//
465
466/// getIntegerSCEV - Given an integer or FP type, create a constant for the
467/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000468SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000469 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000470 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000471 C = Constant::getNullValue(Ty);
472 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000473 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
474 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000475 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000476 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000477 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000478}
479
Chris Lattner53e677a2004-04-02 20:23:17 +0000480/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
481///
Dan Gohman246b2562007-10-22 18:31:58 +0000482SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000483 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000484 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000485
Nick Lewycky178f20a2008-02-20 06:58:55 +0000486 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000487}
488
489/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
490SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
491 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
492 return getUnknown(ConstantExpr::getNot(VC->getValue()));
493
Nick Lewycky178f20a2008-02-20 06:58:55 +0000494 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000495 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000496}
497
498/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
499///
Dan Gohman246b2562007-10-22 18:31:58 +0000500SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
501 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000502 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000503 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000504}
505
506
Eli Friedmanb42a6262008-08-04 23:49:06 +0000507/// BinomialCoefficient - Compute BC(It, K). The result has width W.
508// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000509static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000510 ScalarEvolution &SE,
511 const IntegerType* ResultTy) {
512 // Handle the simplest case efficiently.
513 if (K == 1)
514 return SE.getTruncateOrZeroExtend(It, ResultTy);
515
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000516 // We are using the following formula for BC(It, K):
517 //
518 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
519 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000520 // Suppose, W is the bitwidth of the return value. We must be prepared for
521 // overflow. Hence, we must assure that the result of our computation is
522 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
523 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000524 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000525 // However, this code doesn't use exactly that formula; the formula it uses
526 // is something like the following, where T is the number of factors of 2 in
527 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
528 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000529 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000530 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000531 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000532 // This formula is trivially equivalent to the previous formula. However,
533 // this formula can be implemented much more efficiently. The trick is that
534 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
535 // arithmetic. To do exact division in modular arithmetic, all we have
536 // to do is multiply by the inverse. Therefore, this step can be done at
537 // width W.
538 //
539 // The next issue is how to safely do the division by 2^T. The way this
540 // is done is by doing the multiplication step at a width of at least W + T
541 // bits. This way, the bottom W+T bits of the product are accurate. Then,
542 // when we perform the division by 2^T (which is equivalent to a right shift
543 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
544 // truncated out after the division by 2^T.
545 //
546 // In comparison to just directly using the first formula, this technique
547 // is much more efficient; using the first formula requires W * K bits,
548 // but this formula less than W + K bits. Also, the first formula requires
549 // a division step, whereas this formula only requires multiplies and shifts.
550 //
551 // It doesn't matter whether the subtraction step is done in the calculation
552 // width or the input iteration count's width; if the subtraction overflows,
553 // the result must be zero anyway. We prefer here to do it in the width of
554 // the induction variable because it helps a lot for certain cases; CodeGen
555 // isn't smart enough to ignore the overflow, which leads to much less
556 // efficient code if the width of the subtraction is wider than the native
557 // register width.
558 //
559 // (It's possible to not widen at all by pulling out factors of 2 before
560 // the multiplication; for example, K=2 can be calculated as
561 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
562 // extra arithmetic, so it's not an obvious win, and it gets
563 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000564
Eli Friedmanb42a6262008-08-04 23:49:06 +0000565 // Protection from insane SCEVs; this bound is conservative,
566 // but it probably doesn't matter.
567 if (K > 1000)
568 return new SCEVCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000569
Eli Friedmanb42a6262008-08-04 23:49:06 +0000570 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000571
Eli Friedmanb42a6262008-08-04 23:49:06 +0000572 // Calculate K! / 2^T and T; we divide out the factors of two before
573 // multiplying for calculating K! / 2^T to avoid overflow.
574 // Other overflow doesn't matter because we only care about the bottom
575 // W bits of the result.
576 APInt OddFactorial(W, 1);
577 unsigned T = 1;
578 for (unsigned i = 3; i <= K; ++i) {
579 APInt Mult(W, i);
580 unsigned TwoFactors = Mult.countTrailingZeros();
581 T += TwoFactors;
582 Mult = Mult.lshr(TwoFactors);
583 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000584 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000585
Eli Friedmanb42a6262008-08-04 23:49:06 +0000586 // We need at least W + T bits for the multiplication step
587 // FIXME: A temporary hack; we round up the bitwidths
588 // to the nearest power of 2 to be nice to the code generator.
589 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
590 // FIXME: Temporary hack to avoid generating integers that are too wide.
591 // Although, it's not completely clear how to determine how much
592 // widening is safe; for example, on X86, we can't really widen
593 // beyond 64 because we need to be able to do multiplication
594 // that's CalculationBits wide, but on X86-64, we can safely widen up to
595 // 128 bits.
596 if (CalculationBits > 64)
597 return new SCEVCouldNotCompute();
598
599 // Calcuate 2^T, at width T+W.
600 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
601
602 // Calculate the multiplicative inverse of K! / 2^T;
603 // this multiplication factor will perform the exact division by
604 // K! / 2^T.
605 APInt Mod = APInt::getSignedMinValue(W+1);
606 APInt MultiplyFactor = OddFactorial.zext(W+1);
607 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
608 MultiplyFactor = MultiplyFactor.trunc(W);
609
610 // Calculate the product, at width T+W
611 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
612 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
613 for (unsigned i = 1; i != K; ++i) {
614 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
615 Dividend = SE.getMulExpr(Dividend,
616 SE.getTruncateOrZeroExtend(S, CalculationTy));
617 }
618
619 // Divide by 2^T
620 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
621
622 // Truncate the result, and divide by K! / 2^T.
623
624 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
625 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000626}
627
Chris Lattner53e677a2004-04-02 20:23:17 +0000628/// evaluateAtIteration - Return the value of this chain of recurrences at
629/// the specified iteration number. We can evaluate this recurrence by
630/// multiplying each element in the chain by the binomial coefficient
631/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
632///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000633/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000634///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000635/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000636///
Dan Gohman246b2562007-10-22 18:31:58 +0000637SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
638 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000639 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000640 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000641 // The computation is correct in the face of overflow provided that the
642 // multiplication is performed _after_ the evaluation of the binomial
643 // coefficient.
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000644 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
645 cast<IntegerType>(getType()));
646 if (isa<SCEVCouldNotCompute>(Coeff))
647 return Coeff;
648
649 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000650 }
651 return Result;
652}
653
Chris Lattner53e677a2004-04-02 20:23:17 +0000654//===----------------------------------------------------------------------===//
655// SCEV Expression folder implementations
656//===----------------------------------------------------------------------===//
657
Dan Gohman246b2562007-10-22 18:31:58 +0000658SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000659 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000660 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000661 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000662
663 // If the input value is a chrec scev made out of constants, truncate
664 // all of the constants.
665 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
666 std::vector<SCEVHandle> Operands;
667 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
668 // FIXME: This should allow truncation of other expression types!
669 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000670 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000671 else
672 break;
673 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000674 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000675 }
676
Chris Lattnerb3364092006-10-04 21:49:37 +0000677 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000678 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
679 return Result;
680}
681
Dan Gohman246b2562007-10-22 18:31:58 +0000682SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000683 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000684 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000685 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000686
687 // FIXME: If the input value is a chrec scev, and we can prove that the value
688 // did not overflow the old, smaller, value, we can zero extend all of the
689 // operands (often constants). This would allow analysis of something like
690 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
691
Chris Lattnerb3364092006-10-04 21:49:37 +0000692 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000693 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
694 return Result;
695}
696
Dan Gohman246b2562007-10-22 18:31:58 +0000697SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000698 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000699 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000700 ConstantExpr::getSExt(SC->getValue(), Ty));
701
702 // FIXME: If the input value is a chrec scev, and we can prove that the value
703 // did not overflow the old, smaller, value, we can sign extend all of the
704 // operands (often constants). This would allow analysis of something like
705 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
706
707 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
708 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
709 return Result;
710}
711
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000712/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
713/// of the input value to the specified type. If the type must be
714/// extended, it is zero extended.
715SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
716 const Type *Ty) {
717 const Type *SrcTy = V->getType();
718 assert(SrcTy->isInteger() && Ty->isInteger() &&
719 "Cannot truncate or zero extend with non-integer arguments!");
720 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
721 return V; // No conversion
722 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
723 return getTruncateExpr(V, Ty);
724 return getZeroExtendExpr(V, Ty);
725}
726
Chris Lattner53e677a2004-04-02 20:23:17 +0000727// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000728SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000729 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000730 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000731
732 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000733 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000734
735 // If there are any constants, fold them together.
736 unsigned Idx = 0;
737 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
738 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000739 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000740 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
741 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000742 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
743 RHSC->getValue()->getValue());
744 Ops[0] = getConstant(Fold);
745 Ops.erase(Ops.begin()+1); // Erase the folded element
746 if (Ops.size() == 1) return Ops[0];
747 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000748 }
749
750 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000751 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000752 Ops.erase(Ops.begin());
753 --Idx;
754 }
755 }
756
Chris Lattner627018b2004-04-07 16:16:11 +0000757 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000758
Chris Lattner53e677a2004-04-02 20:23:17 +0000759 // Okay, check to see if the same value occurs in the operand list twice. If
760 // so, merge them together into an multiply expression. Since we sorted the
761 // list, these values are required to be adjacent.
762 const Type *Ty = Ops[0]->getType();
763 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
764 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
765 // Found a match, merge the two values into a multiply, and add any
766 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000767 SCEVHandle Two = getIntegerSCEV(2, Ty);
768 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000769 if (Ops.size() == 2)
770 return Mul;
771 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
772 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000773 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000774 }
775
Dan Gohmanf50cd742007-06-18 19:30:09 +0000776 // Now we know the first non-constant operand. Skip past any cast SCEVs.
777 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
778 ++Idx;
779
780 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000781 if (Idx < Ops.size()) {
782 bool DeletedAdd = false;
783 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
784 // If we have an add, expand the add operands onto the end of the operands
785 // list.
786 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
787 Ops.erase(Ops.begin()+Idx);
788 DeletedAdd = true;
789 }
790
791 // If we deleted at least one add, we added operands to the end of the list,
792 // and they are not necessarily sorted. Recurse to resort and resimplify
793 // any operands we just aquired.
794 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000795 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000796 }
797
798 // Skip over the add expression until we get to a multiply.
799 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
800 ++Idx;
801
802 // If we are adding something to a multiply expression, make sure the
803 // something is not already an operand of the multiply. If so, merge it into
804 // the multiply.
805 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
806 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
807 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
808 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
809 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000810 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000811 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
812 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
813 if (Mul->getNumOperands() != 2) {
814 // If the multiply has more than two operands, we must get the
815 // Y*Z term.
816 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
817 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000818 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000819 }
Dan Gohman246b2562007-10-22 18:31:58 +0000820 SCEVHandle One = getIntegerSCEV(1, Ty);
821 SCEVHandle AddOne = getAddExpr(InnerMul, One);
822 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000823 if (Ops.size() == 2) return OuterMul;
824 if (AddOp < Idx) {
825 Ops.erase(Ops.begin()+AddOp);
826 Ops.erase(Ops.begin()+Idx-1);
827 } else {
828 Ops.erase(Ops.begin()+Idx);
829 Ops.erase(Ops.begin()+AddOp-1);
830 }
831 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000832 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000833 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000834
Chris Lattner53e677a2004-04-02 20:23:17 +0000835 // Check this multiply against other multiplies being added together.
836 for (unsigned OtherMulIdx = Idx+1;
837 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
838 ++OtherMulIdx) {
839 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
840 // If MulOp occurs in OtherMul, we can fold the two multiplies
841 // together.
842 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
843 OMulOp != e; ++OMulOp)
844 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
845 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
846 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
847 if (Mul->getNumOperands() != 2) {
848 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
849 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000850 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000851 }
852 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
853 if (OtherMul->getNumOperands() != 2) {
854 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
855 OtherMul->op_end());
856 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000857 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000858 }
Dan Gohman246b2562007-10-22 18:31:58 +0000859 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
860 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000861 if (Ops.size() == 2) return OuterMul;
862 Ops.erase(Ops.begin()+Idx);
863 Ops.erase(Ops.begin()+OtherMulIdx-1);
864 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000865 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000866 }
867 }
868 }
869 }
870
871 // If there are any add recurrences in the operands list, see if any other
872 // added values are loop invariant. If so, we can fold them into the
873 // recurrence.
874 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
875 ++Idx;
876
877 // Scan over all recurrences, trying to fold loop invariants into them.
878 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
879 // Scan all of the other operands to this add and add them to the vector if
880 // they are loop invariant w.r.t. the recurrence.
881 std::vector<SCEVHandle> LIOps;
882 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
883 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
884 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
885 LIOps.push_back(Ops[i]);
886 Ops.erase(Ops.begin()+i);
887 --i; --e;
888 }
889
890 // If we found some loop invariants, fold them into the recurrence.
891 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +0000892 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +0000893 LIOps.push_back(AddRec->getStart());
894
895 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000896 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000897
Dan Gohman246b2562007-10-22 18:31:58 +0000898 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000899 // If all of the other operands were loop invariant, we are done.
900 if (Ops.size() == 1) return NewRec;
901
902 // Otherwise, add the folded AddRec by the non-liv parts.
903 for (unsigned i = 0;; ++i)
904 if (Ops[i] == AddRec) {
905 Ops[i] = NewRec;
906 break;
907 }
Dan Gohman246b2562007-10-22 18:31:58 +0000908 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000909 }
910
911 // Okay, if there weren't any loop invariants to be folded, check to see if
912 // there are multiple AddRec's with the same loop induction variable being
913 // added together. If so, we can fold them.
914 for (unsigned OtherIdx = Idx+1;
915 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
916 if (OtherIdx != Idx) {
917 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
918 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
919 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
920 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
921 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
922 if (i >= NewOps.size()) {
923 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
924 OtherAddRec->op_end());
925 break;
926 }
Dan Gohman246b2562007-10-22 18:31:58 +0000927 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000928 }
Dan Gohman246b2562007-10-22 18:31:58 +0000929 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000930
931 if (Ops.size() == 2) return NewAddRec;
932
933 Ops.erase(Ops.begin()+Idx);
934 Ops.erase(Ops.begin()+OtherIdx-1);
935 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000936 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000937 }
938 }
939
940 // Otherwise couldn't fold anything into this recurrence. Move onto the
941 // next one.
942 }
943
944 // Okay, it looks like we really DO need an add expr. Check to see if we
945 // already have one, otherwise create a new one.
946 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000947 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
948 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000949 if (Result == 0) Result = new SCEVAddExpr(Ops);
950 return Result;
951}
952
953
Dan Gohman246b2562007-10-22 18:31:58 +0000954SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000955 assert(!Ops.empty() && "Cannot get empty mul!");
956
957 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000958 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000959
960 // If there are any constants, fold them together.
961 unsigned Idx = 0;
962 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
963
964 // C1*(C2+V) -> C1*C2 + C1*V
965 if (Ops.size() == 2)
966 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
967 if (Add->getNumOperands() == 2 &&
968 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000969 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
970 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000971
972
973 ++Idx;
974 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
975 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000976 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
977 RHSC->getValue()->getValue());
978 Ops[0] = getConstant(Fold);
979 Ops.erase(Ops.begin()+1); // Erase the folded element
980 if (Ops.size() == 1) return Ops[0];
981 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000982 }
983
984 // If we are left with a constant one being multiplied, strip it off.
985 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
986 Ops.erase(Ops.begin());
987 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000988 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000989 // If we have a multiply of zero, it will always be zero.
990 return Ops[0];
991 }
992 }
993
994 // Skip over the add expression until we get to a multiply.
995 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
996 ++Idx;
997
998 if (Ops.size() == 1)
999 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001000
Chris Lattner53e677a2004-04-02 20:23:17 +00001001 // If there are mul operands inline them all into this expression.
1002 if (Idx < Ops.size()) {
1003 bool DeletedMul = false;
1004 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1005 // If we have an mul, expand the mul operands onto the end of the operands
1006 // list.
1007 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1008 Ops.erase(Ops.begin()+Idx);
1009 DeletedMul = true;
1010 }
1011
1012 // If we deleted at least one mul, we added operands to the end of the list,
1013 // and they are not necessarily sorted. Recurse to resort and resimplify
1014 // any operands we just aquired.
1015 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001016 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001017 }
1018
1019 // If there are any add recurrences in the operands list, see if any other
1020 // added values are loop invariant. If so, we can fold them into the
1021 // recurrence.
1022 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1023 ++Idx;
1024
1025 // Scan over all recurrences, trying to fold loop invariants into them.
1026 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1027 // Scan all of the other operands to this mul and add them to the vector if
1028 // they are loop invariant w.r.t. the recurrence.
1029 std::vector<SCEVHandle> LIOps;
1030 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1031 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1032 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1033 LIOps.push_back(Ops[i]);
1034 Ops.erase(Ops.begin()+i);
1035 --i; --e;
1036 }
1037
1038 // If we found some loop invariants, fold them into the recurrence.
1039 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001040 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001041 std::vector<SCEVHandle> NewOps;
1042 NewOps.reserve(AddRec->getNumOperands());
1043 if (LIOps.size() == 1) {
1044 SCEV *Scale = LIOps[0];
1045 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001046 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001047 } else {
1048 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1049 std::vector<SCEVHandle> MulOps(LIOps);
1050 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001051 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001052 }
1053 }
1054
Dan Gohman246b2562007-10-22 18:31:58 +00001055 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001056
1057 // If all of the other operands were loop invariant, we are done.
1058 if (Ops.size() == 1) return NewRec;
1059
1060 // Otherwise, multiply the folded AddRec by the non-liv parts.
1061 for (unsigned i = 0;; ++i)
1062 if (Ops[i] == AddRec) {
1063 Ops[i] = NewRec;
1064 break;
1065 }
Dan Gohman246b2562007-10-22 18:31:58 +00001066 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001067 }
1068
1069 // Okay, if there weren't any loop invariants to be folded, check to see if
1070 // there are multiple AddRec's with the same loop induction variable being
1071 // multiplied together. If so, we can fold them.
1072 for (unsigned OtherIdx = Idx+1;
1073 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1074 if (OtherIdx != Idx) {
1075 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1076 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1077 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1078 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001079 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001080 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001081 SCEVHandle B = F->getStepRecurrence(*this);
1082 SCEVHandle D = G->getStepRecurrence(*this);
1083 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1084 getMulExpr(G, B),
1085 getMulExpr(B, D));
1086 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1087 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001088 if (Ops.size() == 2) return NewAddRec;
1089
1090 Ops.erase(Ops.begin()+Idx);
1091 Ops.erase(Ops.begin()+OtherIdx-1);
1092 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001093 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001094 }
1095 }
1096
1097 // Otherwise couldn't fold anything into this recurrence. Move onto the
1098 // next one.
1099 }
1100
1101 // Okay, it looks like we really DO need an mul expr. Check to see if we
1102 // already have one, otherwise create a new one.
1103 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001104 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1105 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001106 if (Result == 0)
1107 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001108 return Result;
1109}
1110
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001111SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001112 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1113 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001114 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001115
1116 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1117 Constant *LHSCV = LHSC->getValue();
1118 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001119 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001120 }
1121 }
1122
1123 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1124
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001125 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1126 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001127 return Result;
1128}
1129
1130
1131/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1132/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001133SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001134 const SCEVHandle &Step, const Loop *L) {
1135 std::vector<SCEVHandle> Operands;
1136 Operands.push_back(Start);
1137 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1138 if (StepChrec->getLoop() == L) {
1139 Operands.insert(Operands.end(), StepChrec->op_begin(),
1140 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001141 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001142 }
1143
1144 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001145 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001146}
1147
1148/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1149/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001150SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001151 const Loop *L) {
1152 if (Operands.size() == 1) return Operands[0];
1153
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001154 if (Operands.back()->isZero()) {
1155 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001156 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001157 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001158
Dan Gohmand9cc7492008-08-08 18:33:12 +00001159 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1160 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1161 const Loop* NestedLoop = NestedAR->getLoop();
1162 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1163 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1164 NestedAR->op_end());
1165 SCEVHandle NestedARHandle(NestedAR);
1166 Operands[0] = NestedAR->getStart();
1167 NestedOperands[0] = getAddRecExpr(Operands, L);
1168 return getAddRecExpr(NestedOperands, NestedLoop);
1169 }
1170 }
1171
Chris Lattner53e677a2004-04-02 20:23:17 +00001172 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001173 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1174 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001175 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1176 return Result;
1177}
1178
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001179SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1180 const SCEVHandle &RHS) {
1181 std::vector<SCEVHandle> Ops;
1182 Ops.push_back(LHS);
1183 Ops.push_back(RHS);
1184 return getSMaxExpr(Ops);
1185}
1186
1187SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1188 assert(!Ops.empty() && "Cannot get empty smax!");
1189 if (Ops.size() == 1) return Ops[0];
1190
1191 // Sort by complexity, this groups all similar expression types together.
1192 GroupByComplexity(Ops);
1193
1194 // If there are any constants, fold them together.
1195 unsigned Idx = 0;
1196 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1197 ++Idx;
1198 assert(Idx < Ops.size());
1199 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1200 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001201 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001202 APIntOps::smax(LHSC->getValue()->getValue(),
1203 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001204 Ops[0] = getConstant(Fold);
1205 Ops.erase(Ops.begin()+1); // Erase the folded element
1206 if (Ops.size() == 1) return Ops[0];
1207 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001208 }
1209
1210 // If we are left with a constant -inf, strip it off.
1211 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1212 Ops.erase(Ops.begin());
1213 --Idx;
1214 }
1215 }
1216
1217 if (Ops.size() == 1) return Ops[0];
1218
1219 // Find the first SMax
1220 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1221 ++Idx;
1222
1223 // Check to see if one of the operands is an SMax. If so, expand its operands
1224 // onto our operand list, and recurse to simplify.
1225 if (Idx < Ops.size()) {
1226 bool DeletedSMax = false;
1227 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1228 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1229 Ops.erase(Ops.begin()+Idx);
1230 DeletedSMax = true;
1231 }
1232
1233 if (DeletedSMax)
1234 return getSMaxExpr(Ops);
1235 }
1236
1237 // Okay, check to see if the same value occurs in the operand list twice. If
1238 // so, delete one. Since we sorted the list, these values are required to
1239 // be adjacent.
1240 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1241 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1242 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1243 --i; --e;
1244 }
1245
1246 if (Ops.size() == 1) return Ops[0];
1247
1248 assert(!Ops.empty() && "Reduced smax down to nothing!");
1249
Nick Lewycky3e630762008-02-20 06:48:22 +00001250 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001251 // already have one, otherwise create a new one.
1252 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1253 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1254 SCEVOps)];
1255 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1256 return Result;
1257}
1258
Nick Lewycky3e630762008-02-20 06:48:22 +00001259SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1260 const SCEVHandle &RHS) {
1261 std::vector<SCEVHandle> Ops;
1262 Ops.push_back(LHS);
1263 Ops.push_back(RHS);
1264 return getUMaxExpr(Ops);
1265}
1266
1267SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1268 assert(!Ops.empty() && "Cannot get empty umax!");
1269 if (Ops.size() == 1) return Ops[0];
1270
1271 // Sort by complexity, this groups all similar expression types together.
1272 GroupByComplexity(Ops);
1273
1274 // If there are any constants, fold them together.
1275 unsigned Idx = 0;
1276 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1277 ++Idx;
1278 assert(Idx < Ops.size());
1279 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1280 // We found two constants, fold them together!
1281 ConstantInt *Fold = ConstantInt::get(
1282 APIntOps::umax(LHSC->getValue()->getValue(),
1283 RHSC->getValue()->getValue()));
1284 Ops[0] = getConstant(Fold);
1285 Ops.erase(Ops.begin()+1); // Erase the folded element
1286 if (Ops.size() == 1) return Ops[0];
1287 LHSC = cast<SCEVConstant>(Ops[0]);
1288 }
1289
1290 // If we are left with a constant zero, strip it off.
1291 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1292 Ops.erase(Ops.begin());
1293 --Idx;
1294 }
1295 }
1296
1297 if (Ops.size() == 1) return Ops[0];
1298
1299 // Find the first UMax
1300 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1301 ++Idx;
1302
1303 // Check to see if one of the operands is a UMax. If so, expand its operands
1304 // onto our operand list, and recurse to simplify.
1305 if (Idx < Ops.size()) {
1306 bool DeletedUMax = false;
1307 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1308 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1309 Ops.erase(Ops.begin()+Idx);
1310 DeletedUMax = true;
1311 }
1312
1313 if (DeletedUMax)
1314 return getUMaxExpr(Ops);
1315 }
1316
1317 // Okay, check to see if the same value occurs in the operand list twice. If
1318 // so, delete one. Since we sorted the list, these values are required to
1319 // be adjacent.
1320 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1321 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1322 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1323 --i; --e;
1324 }
1325
1326 if (Ops.size() == 1) return Ops[0];
1327
1328 assert(!Ops.empty() && "Reduced umax down to nothing!");
1329
1330 // Okay, it looks like we really DO need a umax expr. Check to see if we
1331 // already have one, otherwise create a new one.
1332 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1333 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1334 SCEVOps)];
1335 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1336 return Result;
1337}
1338
Dan Gohman246b2562007-10-22 18:31:58 +00001339SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001340 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001341 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001342 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001343 if (Result == 0) Result = new SCEVUnknown(V);
1344 return Result;
1345}
1346
Chris Lattner53e677a2004-04-02 20:23:17 +00001347
1348//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001349// ScalarEvolutionsImpl Definition and Implementation
1350//===----------------------------------------------------------------------===//
1351//
1352/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1353/// evolution code.
1354///
1355namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001356 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001357 /// SE - A reference to the public ScalarEvolution object.
1358 ScalarEvolution &SE;
1359
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 /// F - The function we are analyzing.
1361 ///
1362 Function &F;
1363
1364 /// LI - The loop information for the function we are currently analyzing.
1365 ///
1366 LoopInfo &LI;
1367
1368 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1369 /// things.
1370 SCEVHandle UnknownValue;
1371
1372 /// Scalars - This is a cache of the scalars we have analyzed so far.
1373 ///
1374 std::map<Value*, SCEVHandle> Scalars;
1375
1376 /// IterationCounts - Cache the iteration count of the loops for this
1377 /// function as they are computed.
1378 std::map<const Loop*, SCEVHandle> IterationCounts;
1379
Chris Lattner3221ad02004-04-17 22:58:41 +00001380 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1381 /// the PHI instructions that we attempt to compute constant evolutions for.
1382 /// This allows us to avoid potentially expensive recomputation of these
1383 /// properties. An instruction maps to null if we are unable to compute its
1384 /// exit value.
1385 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001386
Chris Lattner53e677a2004-04-02 20:23:17 +00001387 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001388 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1389 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001390
1391 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1392 /// expression and create a new one.
1393 SCEVHandle getSCEV(Value *V);
1394
Chris Lattnera0740fb2005-08-09 23:36:33 +00001395 /// hasSCEV - Return true if the SCEV for this value has already been
1396 /// computed.
1397 bool hasSCEV(Value *V) const {
1398 return Scalars.count(V);
1399 }
1400
1401 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1402 /// the specified value.
1403 void setSCEV(Value *V, const SCEVHandle &H) {
1404 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1405 assert(isNew && "This entry already existed!");
Devang Patel89d0a4d2008-11-11 19:17:41 +00001406 isNew = false;
Chris Lattnera0740fb2005-08-09 23:36:33 +00001407 }
1408
1409
Chris Lattner53e677a2004-04-02 20:23:17 +00001410 /// getSCEVAtScope - Compute the value of the specified expression within
1411 /// the indicated loop (which may be null to indicate in no loop). If the
1412 /// expression cannot be evaluated, return UnknownValue itself.
1413 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1414
1415
1416 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1417 /// an analyzable loop-invariant iteration count.
1418 bool hasLoopInvariantIterationCount(const Loop *L);
1419
1420 /// getIterationCount - If the specified loop has a predictable iteration
1421 /// count, return it. Note that it is not valid to call this method on a
1422 /// loop without a loop-invariant iteration count.
1423 SCEVHandle getIterationCount(const Loop *L);
1424
Dan Gohman5cec4db2007-06-19 14:28:31 +00001425 /// deleteValueFromRecords - This method should be called by the
1426 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001427 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001428 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001429
1430 private:
1431 /// createSCEV - We know that there is no SCEV for the specified value.
1432 /// Analyze the expression.
1433 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001434
1435 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1436 /// SCEVs.
1437 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001438
1439 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1440 /// for the specified instruction and replaces any references to the
1441 /// symbolic value SymName with the specified value. This is used during
1442 /// PHI resolution.
1443 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1444 const SCEVHandle &SymName,
1445 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001446
1447 /// ComputeIterationCount - Compute the number of times the specified loop
1448 /// will iterate.
1449 SCEVHandle ComputeIterationCount(const Loop *L);
1450
Chris Lattner673e02b2004-10-12 01:49:27 +00001451 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001452 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001453 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1454 Constant *RHS,
1455 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001456 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001457
Chris Lattner7980fb92004-04-17 18:36:24 +00001458 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1459 /// constant number of times (the condition evolves only from constants),
1460 /// try to evaluate a few iterations of the loop until we get the exit
1461 /// condition gets a value of ExitWhen (true or false). If we cannot
1462 /// evaluate the trip count of the loop, return UnknownValue.
1463 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1464 bool ExitWhen);
1465
Chris Lattner53e677a2004-04-02 20:23:17 +00001466 /// HowFarToZero - Return the number of times a backedge comparing the
1467 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001468 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001469 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1470
1471 /// HowFarToNonZero - Return the number of times a backedge checking the
1472 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001473 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001475
Chris Lattnerdb25de42005-08-15 23:33:51 +00001476 /// HowManyLessThans - Return the number of times a backedge containing the
1477 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001478 /// UnknownValue. isSigned specifies whether the less-than is signed.
1479 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1480 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001481
Dan Gohmanfd6edef2008-09-15 22:18:04 +00001482 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1483 /// (which may not be an immediate predecessor) which has exactly one
1484 /// successor from which BB is reachable, or null if no such block is
1485 /// found.
1486 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1487
Nick Lewycky59cff122008-07-12 07:41:32 +00001488 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1489 /// a conditional between LHS and RHS.
1490 bool executesAtLeastOnce(const Loop *L, bool isSigned, SCEV *LHS, SCEV *RHS);
1491
Chris Lattner3221ad02004-04-17 22:58:41 +00001492 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1493 /// in the header of its containing loop, we know the loop executes a
1494 /// constant number of times, and the PHI node is just a recurrence
1495 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001496 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001497 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001498 };
1499}
1500
1501//===----------------------------------------------------------------------===//
1502// Basic SCEV Analysis and PHI Idiom Recognition Code
1503//
1504
Dan Gohman5cec4db2007-06-19 14:28:31 +00001505/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001506/// client before it removes an instruction from the program, to make sure
1507/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001508void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1509 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001510
Dan Gohman5cec4db2007-06-19 14:28:31 +00001511 if (Scalars.erase(V)) {
1512 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001513 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001514 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001515 }
1516
1517 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001518 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001519 Worklist.pop_back();
1520
Dan Gohman5cec4db2007-06-19 14:28:31 +00001521 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001522 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001523 Instruction *Inst = cast<Instruction>(*UI);
1524 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001525 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001526 ConstantEvolutionLoopExitValue.erase(PN);
1527 Worklist.push_back(Inst);
1528 }
1529 }
1530 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001531}
1532
1533
1534/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1535/// expression and create a new one.
1536SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1537 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1538
1539 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1540 if (I != Scalars.end()) return I->second;
1541 SCEVHandle S = createSCEV(V);
1542 Scalars.insert(std::make_pair(V, S));
1543 return S;
1544}
1545
Chris Lattner4dc534c2005-02-13 04:37:18 +00001546/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1547/// the specified instruction and replaces any references to the symbolic value
1548/// SymName with the specified value. This is used during PHI resolution.
1549void ScalarEvolutionsImpl::
1550ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1551 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001552 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001553 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001554
Chris Lattner4dc534c2005-02-13 04:37:18 +00001555 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001556 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001557 if (NV == SI->second) return; // No change.
1558
1559 SI->second = NV; // Update the scalars map!
1560
1561 // Any instruction values that use this instruction might also need to be
1562 // updated!
1563 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1564 UI != E; ++UI)
1565 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1566}
Chris Lattner53e677a2004-04-02 20:23:17 +00001567
1568/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1569/// a loop header, making it a potential recurrence, or it doesn't.
1570///
1571SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1572 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1573 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1574 if (L->getHeader() == PN->getParent()) {
1575 // If it lives in the loop header, it has two incoming values, one
1576 // from outside the loop, and one from inside.
1577 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1578 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001579
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001581 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001582 assert(Scalars.find(PN) == Scalars.end() &&
1583 "PHI node already processed?");
1584 Scalars.insert(std::make_pair(PN, SymbolicName));
1585
1586 // Using this symbolic name for the PHI, analyze the value coming around
1587 // the back-edge.
1588 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1589
1590 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1591 // has a special value for the first iteration of the loop.
1592
1593 // If the value coming around the backedge is an add with the symbolic
1594 // value we just inserted, then we found a simple induction variable!
1595 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1596 // If there is a single occurrence of the symbolic value, replace it
1597 // with a recurrence.
1598 unsigned FoundIndex = Add->getNumOperands();
1599 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1600 if (Add->getOperand(i) == SymbolicName)
1601 if (FoundIndex == e) {
1602 FoundIndex = i;
1603 break;
1604 }
1605
1606 if (FoundIndex != Add->getNumOperands()) {
1607 // Create an add with everything but the specified operand.
1608 std::vector<SCEVHandle> Ops;
1609 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1610 if (i != FoundIndex)
1611 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001612 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001613
1614 // This is not a valid addrec if the step amount is varying each
1615 // loop iteration, but is not itself an addrec in this loop.
1616 if (Accum->isLoopInvariant(L) ||
1617 (isa<SCEVAddRecExpr>(Accum) &&
1618 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1619 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001620 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001621
1622 // Okay, for the entire analysis of this edge we assumed the PHI
1623 // to be symbolic. We now need to go back and update all of the
1624 // entries for the scalars that use the PHI (except for the PHI
1625 // itself) to use the new analyzed value instead of the "symbolic"
1626 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001627 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001628 return PHISCEV;
1629 }
1630 }
Chris Lattner97156e72006-04-26 18:34:07 +00001631 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1632 // Otherwise, this could be a loop like this:
1633 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1634 // In this case, j = {1,+,1} and BEValue is j.
1635 // Because the other in-value of i (0) fits the evolution of BEValue
1636 // i really is an addrec evolution.
1637 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1638 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1639
1640 // If StartVal = j.start - j.stride, we can use StartVal as the
1641 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001642 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1643 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001644 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001645 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001646
1647 // Okay, for the entire analysis of this edge we assumed the PHI
1648 // to be symbolic. We now need to go back and update all of the
1649 // entries for the scalars that use the PHI (except for the PHI
1650 // itself) to use the new analyzed value instead of the "symbolic"
1651 // value.
1652 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1653 return PHISCEV;
1654 }
1655 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001656 }
1657
1658 return SymbolicName;
1659 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001660
Chris Lattner53e677a2004-04-02 20:23:17 +00001661 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001662 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001663}
1664
Nick Lewycky83bb0052007-11-22 07:59:40 +00001665/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1666/// guaranteed to end in (at every loop iteration). It is, at the same time,
1667/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1668/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1669static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1670 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001671 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001672
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001673 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001674 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1675
1676 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1677 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1678 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1679 }
1680
1681 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1682 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1683 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1684 }
1685
Chris Lattnera17f0392006-12-12 02:26:09 +00001686 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001687 // The result is the min of all operands results.
1688 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1689 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1690 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1691 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001692 }
1693
1694 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001695 // The result is the sum of all operands results.
1696 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1697 uint32_t BitWidth = M->getBitWidth();
1698 for (unsigned i = 1, e = M->getNumOperands();
1699 SumOpRes != BitWidth && i != e; ++i)
1700 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1701 BitWidth);
1702 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001703 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001704
Chris Lattnera17f0392006-12-12 02:26:09 +00001705 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001706 // The result is the min of all operands results.
1707 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1708 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1709 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1710 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001711 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001712
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001713 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1714 // The result is the min of all operands results.
1715 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1716 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1717 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1718 return MinOpRes;
1719 }
1720
Nick Lewycky3e630762008-02-20 06:48:22 +00001721 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1722 // The result is the min of all operands results.
1723 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1724 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1725 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1726 return MinOpRes;
1727 }
1728
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001729 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001730 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001731}
Chris Lattner53e677a2004-04-02 20:23:17 +00001732
1733/// createSCEV - We know that there is no SCEV for the specified value.
1734/// Analyze the expression.
1735///
1736SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001737 if (!isa<IntegerType>(V->getType()))
1738 return SE.getUnknown(V);
1739
Dan Gohman6c459a22008-06-22 19:56:46 +00001740 unsigned Opcode = Instruction::UserOp1;
1741 if (Instruction *I = dyn_cast<Instruction>(V))
1742 Opcode = I->getOpcode();
1743 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1744 Opcode = CE->getOpcode();
1745 else
1746 return SE.getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001747
Dan Gohman6c459a22008-06-22 19:56:46 +00001748 User *U = cast<User>(V);
1749 switch (Opcode) {
1750 case Instruction::Add:
1751 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1752 getSCEV(U->getOperand(1)));
1753 case Instruction::Mul:
1754 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1755 getSCEV(U->getOperand(1)));
1756 case Instruction::UDiv:
1757 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1758 getSCEV(U->getOperand(1)));
1759 case Instruction::Sub:
1760 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1761 getSCEV(U->getOperand(1)));
1762 case Instruction::Or:
1763 // If the RHS of the Or is a constant, we may have something like:
1764 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1765 // optimizations will transparently handle this case.
1766 //
1767 // In order for this transformation to be safe, the LHS must be of the
1768 // form X*(2^n) and the Or constant must be less than 2^n.
1769 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1770 SCEVHandle LHS = getSCEV(U->getOperand(0));
1771 const APInt &CIVal = CI->getValue();
1772 if (GetMinTrailingZeros(LHS) >=
1773 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1774 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001775 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001776 break;
1777 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001778 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001779 // If the RHS of the xor is a signbit, then this is just an add.
1780 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001781 if (CI->getValue().isSignBit())
1782 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1783 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001784
1785 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001786 else if (CI->isAllOnesValue())
1787 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1788 }
1789 break;
1790
1791 case Instruction::Shl:
1792 // Turn shift left of a constant amount into a multiply.
1793 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1794 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1795 Constant *X = ConstantInt::get(
1796 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1797 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1798 }
1799 break;
1800
Nick Lewycky01eaf802008-07-07 06:15:49 +00001801 case Instruction::LShr:
1802 // Turn logical shift right of a constant into a unsigned divide.
1803 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1804 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1805 Constant *X = ConstantInt::get(
1806 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1807 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1808 }
1809 break;
1810
Dan Gohman6c459a22008-06-22 19:56:46 +00001811 case Instruction::Trunc:
1812 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1813
1814 case Instruction::ZExt:
1815 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1816
1817 case Instruction::SExt:
1818 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1819
1820 case Instruction::BitCast:
1821 // BitCasts are no-op casts so we just eliminate the cast.
1822 if (U->getType()->isInteger() &&
1823 U->getOperand(0)->getType()->isInteger())
1824 return getSCEV(U->getOperand(0));
1825 break;
1826
1827 case Instruction::PHI:
1828 return createNodeForPHI(cast<PHINode>(U));
1829
1830 case Instruction::Select:
1831 // This could be a smax or umax that was lowered earlier.
1832 // Try to recover it.
1833 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1834 Value *LHS = ICI->getOperand(0);
1835 Value *RHS = ICI->getOperand(1);
1836 switch (ICI->getPredicate()) {
1837 case ICmpInst::ICMP_SLT:
1838 case ICmpInst::ICMP_SLE:
1839 std::swap(LHS, RHS);
1840 // fall through
1841 case ICmpInst::ICMP_SGT:
1842 case ICmpInst::ICMP_SGE:
1843 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1844 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1845 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00001846 // ~smax(~x, ~y) == smin(x, y).
1847 return SE.getNotSCEV(SE.getSMaxExpr(
1848 SE.getNotSCEV(getSCEV(LHS)),
1849 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00001850 break;
1851 case ICmpInst::ICMP_ULT:
1852 case ICmpInst::ICMP_ULE:
1853 std::swap(LHS, RHS);
1854 // fall through
1855 case ICmpInst::ICMP_UGT:
1856 case ICmpInst::ICMP_UGE:
1857 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1858 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1859 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1860 // ~umax(~x, ~y) == umin(x, y)
1861 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1862 SE.getNotSCEV(getSCEV(RHS))));
1863 break;
1864 default:
1865 break;
1866 }
1867 }
1868
1869 default: // We cannot analyze this expression.
1870 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001871 }
1872
Dan Gohman246b2562007-10-22 18:31:58 +00001873 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001874}
1875
1876
1877
1878//===----------------------------------------------------------------------===//
1879// Iteration Count Computation Code
1880//
1881
1882/// getIterationCount - If the specified loop has a predictable iteration
1883/// count, return it. Note that it is not valid to call this method on a
1884/// loop without a loop-invariant iteration count.
1885SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1886 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1887 if (I == IterationCounts.end()) {
1888 SCEVHandle ItCount = ComputeIterationCount(L);
1889 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1890 if (ItCount != UnknownValue) {
1891 assert(ItCount->isLoopInvariant(L) &&
1892 "Computed trip count isn't loop invariant for loop!");
1893 ++NumTripCountsComputed;
1894 } else if (isa<PHINode>(L->getHeader()->begin())) {
1895 // Only count loops that have phi nodes as not being computable.
1896 ++NumTripCountsNotComputed;
1897 }
1898 }
1899 return I->second;
1900}
1901
1902/// ComputeIterationCount - Compute the number of times the specified loop
1903/// will iterate.
1904SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1905 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001906 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001907 L->getExitBlocks(ExitBlocks);
1908 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001909
1910 // Okay, there is one exit block. Try to find the condition that causes the
1911 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001912 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001913
1914 BasicBlock *ExitingBlock = 0;
1915 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1916 PI != E; ++PI)
1917 if (L->contains(*PI)) {
1918 if (ExitingBlock == 0)
1919 ExitingBlock = *PI;
1920 else
1921 return UnknownValue; // More than one block exiting!
1922 }
1923 assert(ExitingBlock && "No exits from loop, something is broken!");
1924
1925 // Okay, we've computed the exiting block. See what condition causes us to
1926 // exit.
1927 //
1928 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001929 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1930 if (ExitBr == 0) return UnknownValue;
1931 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001932
1933 // At this point, we know we have a conditional branch that determines whether
1934 // the loop is exited. However, we don't know if the branch is executed each
1935 // time through the loop. If not, then the execution count of the branch will
1936 // not be equal to the trip count of the loop.
1937 //
1938 // Currently we check for this by checking to see if the Exit branch goes to
1939 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001940 // times as the loop. We also handle the case where the exit block *is* the
1941 // loop header. This is common for un-rotated loops. More extensive analysis
1942 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001943 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001944 ExitBr->getSuccessor(1) != L->getHeader() &&
1945 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001946 return UnknownValue;
1947
Reid Spencere4d87aa2006-12-23 06:05:41 +00001948 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1949
Nick Lewycky3b711652008-02-21 08:34:02 +00001950 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001951 // Note that ICmpInst deals with pointer comparisons too so we must check
1952 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001953 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001954 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1955 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001956
Reid Spencere4d87aa2006-12-23 06:05:41 +00001957 // If the condition was exit on true, convert the condition to exit on false
1958 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001959 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001960 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001961 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001962 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001963
1964 // Handle common loops like: for (X = "string"; *X; ++X)
1965 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1966 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1967 SCEVHandle ItCnt =
1968 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1969 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1970 }
1971
Chris Lattner53e677a2004-04-02 20:23:17 +00001972 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1973 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1974
1975 // Try to evaluate any dependencies out of the loop.
1976 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1977 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1978 Tmp = getSCEVAtScope(RHS, L);
1979 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1980
Reid Spencere4d87aa2006-12-23 06:05:41 +00001981 // At this point, we would like to compute how many iterations of the
1982 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00001983 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
1984 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00001985 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001986 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001987 }
1988
1989 // FIXME: think about handling pointer comparisons! i.e.:
1990 // while (P != P+100) ++P;
1991
1992 // If we have a comparison of a chrec against a constant, try to use value
1993 // ranges to answer this query.
1994 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1995 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1996 if (AddRec->getLoop() == L) {
1997 // Form the comparison range using the constant of the correct type so
1998 // that the ConstantRange class knows to do a signed or unsigned
1999 // comparison.
2000 ConstantInt *CompVal = RHSC->getValue();
2001 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002002 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002003 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002004 if (CompVal) {
2005 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002006 ConstantRange CompRange(
2007 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002008
Dan Gohman246b2562007-10-22 18:31:58 +00002009 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002010 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2011 }
2012 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002013
Chris Lattner53e677a2004-04-02 20:23:17 +00002014 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002015 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002016 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00002017 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002018 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002019 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002020 }
2021 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002022 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00002023 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002024 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002025 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002026 }
2027 case ICmpInst::ICMP_SLT: {
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002028 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002029 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002030 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002031 }
2032 case ICmpInst::ICMP_SGT: {
Eli Friedman068acc32008-07-30 00:04:08 +00002033 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2034 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002035 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2036 break;
2037 }
2038 case ICmpInst::ICMP_ULT: {
2039 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2040 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2041 break;
2042 }
2043 case ICmpInst::ICMP_UGT: {
Dale Johannesena0c8fc62008-04-20 16:58:57 +00002044 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky08de6132008-05-06 04:03:18 +00002045 SE.getNotSCEV(RHS), L, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002046 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002047 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002048 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002049 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002050#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002051 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002052 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00002053 cerr << "[unsigned] ";
2054 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002055 << Instruction::getOpcodeName(Instruction::ICmp)
2056 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002057#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002058 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002059 }
Chris Lattner7980fb92004-04-17 18:36:24 +00002060 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002061 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002062}
2063
Chris Lattner673e02b2004-10-12 01:49:27 +00002064static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002065EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2066 ScalarEvolution &SE) {
2067 SCEVHandle InVal = SE.getConstant(C);
2068 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002069 assert(isa<SCEVConstant>(Val) &&
2070 "Evaluation of SCEV at constant didn't fold correctly?");
2071 return cast<SCEVConstant>(Val)->getValue();
2072}
2073
2074/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2075/// and a GEP expression (missing the pointer index) indexing into it, return
2076/// the addressed element of the initializer or null if the index expression is
2077/// invalid.
2078static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002079GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002080 const std::vector<ConstantInt*> &Indices) {
2081 Constant *Init = GV->getInitializer();
2082 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002083 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002084 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2085 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2086 Init = cast<Constant>(CS->getOperand(Idx));
2087 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2088 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2089 Init = cast<Constant>(CA->getOperand(Idx));
2090 } else if (isa<ConstantAggregateZero>(Init)) {
2091 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2092 assert(Idx < STy->getNumElements() && "Bad struct index!");
2093 Init = Constant::getNullValue(STy->getElementType(Idx));
2094 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2095 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2096 Init = Constant::getNullValue(ATy->getElementType());
2097 } else {
2098 assert(0 && "Unknown constant aggregate type!");
2099 }
2100 return 0;
2101 } else {
2102 return 0; // Unknown initializer type
2103 }
2104 }
2105 return Init;
2106}
2107
2108/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky08de6132008-05-06 04:03:18 +00002109/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002110SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002111ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002112 const Loop *L,
2113 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002114 if (LI->isVolatile()) return UnknownValue;
2115
2116 // Check to see if the loaded pointer is a getelementptr of a global.
2117 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2118 if (!GEP) return UnknownValue;
2119
2120 // Make sure that it is really a constant global we are gepping, with an
2121 // initializer, and make sure the first IDX is really 0.
2122 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2123 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2124 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2125 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2126 return UnknownValue;
2127
2128 // Okay, we allow one non-constant index into the GEP instruction.
2129 Value *VarIdx = 0;
2130 std::vector<ConstantInt*> Indexes;
2131 unsigned VarIdxNum = 0;
2132 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2133 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2134 Indexes.push_back(CI);
2135 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2136 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2137 VarIdx = GEP->getOperand(i);
2138 VarIdxNum = i-2;
2139 Indexes.push_back(0);
2140 }
2141
2142 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2143 // Check to see if X is a loop variant variable value now.
2144 SCEVHandle Idx = getSCEV(VarIdx);
2145 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2146 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2147
2148 // We can only recognize very limited forms of loop index expressions, in
2149 // particular, only affine AddRec's like {C1,+,C2}.
2150 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2151 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2152 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2153 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2154 return UnknownValue;
2155
2156 unsigned MaxSteps = MaxBruteForceIterations;
2157 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002158 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002159 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002160 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002161
2162 // Form the GEP offset.
2163 Indexes[VarIdxNum] = Val;
2164
2165 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2166 if (Result == 0) break; // Cannot compute!
2167
2168 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002169 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002170 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002171 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002172#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002173 cerr << "\n***\n*** Computed loop count " << *ItCst
2174 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2175 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002176#endif
2177 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002178 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002179 }
2180 }
2181 return UnknownValue;
2182}
2183
2184
Chris Lattner3221ad02004-04-17 22:58:41 +00002185/// CanConstantFold - Return true if we can constant fold an instruction of the
2186/// specified type, assuming that all operands were constants.
2187static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002188 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002189 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2190 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002191
Chris Lattner3221ad02004-04-17 22:58:41 +00002192 if (const CallInst *CI = dyn_cast<CallInst>(I))
2193 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002194 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002195 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002196}
2197
Chris Lattner3221ad02004-04-17 22:58:41 +00002198/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2199/// in the loop that V is derived from. We allow arbitrary operations along the
2200/// way, but the operands of an operation must either be constants or a value
2201/// derived from a constant PHI. If this expression does not fit with these
2202/// constraints, return null.
2203static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2204 // If this is not an instruction, or if this is an instruction outside of the
2205 // loop, it can't be derived from a loop PHI.
2206 Instruction *I = dyn_cast<Instruction>(V);
2207 if (I == 0 || !L->contains(I->getParent())) return 0;
2208
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002209 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002210 if (L->getHeader() == I->getParent())
2211 return PN;
2212 else
2213 // We don't currently keep track of the control flow needed to evaluate
2214 // PHIs, so we cannot handle PHIs inside of loops.
2215 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002216 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002217
2218 // If we won't be able to constant fold this expression even if the operands
2219 // are constants, return early.
2220 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002221
Chris Lattner3221ad02004-04-17 22:58:41 +00002222 // Otherwise, we can evaluate this instruction if all of its operands are
2223 // constant or derived from a PHI node themselves.
2224 PHINode *PHI = 0;
2225 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2226 if (!(isa<Constant>(I->getOperand(Op)) ||
2227 isa<GlobalValue>(I->getOperand(Op)))) {
2228 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2229 if (P == 0) return 0; // Not evolving from PHI
2230 if (PHI == 0)
2231 PHI = P;
2232 else if (PHI != P)
2233 return 0; // Evolving from multiple different PHIs.
2234 }
2235
2236 // This is a expression evolving from a constant PHI!
2237 return PHI;
2238}
2239
2240/// EvaluateExpression - Given an expression that passes the
2241/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2242/// in the loop has the value PHIVal. If we can't fold this expression for some
2243/// reason, return null.
2244static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2245 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002246 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002247 Instruction *I = cast<Instruction>(V);
2248
2249 std::vector<Constant*> Operands;
2250 Operands.resize(I->getNumOperands());
2251
2252 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2253 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2254 if (Operands[i] == 0) return 0;
2255 }
2256
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002257 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2258 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2259 &Operands[0], Operands.size());
2260 else
2261 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2262 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002263}
2264
2265/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2266/// in the header of its containing loop, we know the loop executes a
2267/// constant number of times, and the PHI node is just a recurrence
2268/// involving constants, fold it.
2269Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002270getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002271 std::map<PHINode*, Constant*>::iterator I =
2272 ConstantEvolutionLoopExitValue.find(PN);
2273 if (I != ConstantEvolutionLoopExitValue.end())
2274 return I->second;
2275
Reid Spencere8019bb2007-03-01 07:25:48 +00002276 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002277 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2278
2279 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2280
2281 // Since the loop is canonicalized, the PHI node must have two entries. One
2282 // entry must be a constant (coming in from outside of the loop), and the
2283 // second must be derived from the same PHI.
2284 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2285 Constant *StartCST =
2286 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2287 if (StartCST == 0)
2288 return RetVal = 0; // Must be a constant.
2289
2290 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2291 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2292 if (PN2 != PN)
2293 return RetVal = 0; // Not derived from same PHI.
2294
2295 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002296 if (Its.getActiveBits() >= 32)
2297 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002298
Reid Spencere8019bb2007-03-01 07:25:48 +00002299 unsigned NumIterations = Its.getZExtValue(); // must be in range
2300 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002301 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2302 if (IterationNum == NumIterations)
2303 return RetVal = PHIVal; // Got exit value!
2304
2305 // Compute the value of the PHI node for the next iteration.
2306 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2307 if (NextPHI == PHIVal)
2308 return RetVal = NextPHI; // Stopped evolving!
2309 if (NextPHI == 0)
2310 return 0; // Couldn't evaluate!
2311 PHIVal = NextPHI;
2312 }
2313}
2314
Chris Lattner7980fb92004-04-17 18:36:24 +00002315/// ComputeIterationCountExhaustively - If the trip is known to execute a
2316/// constant number of times (the condition evolves only from constants),
2317/// try to evaluate a few iterations of the loop until we get the exit
2318/// condition gets a value of ExitWhen (true or false). If we cannot
2319/// evaluate the trip count of the loop, return UnknownValue.
2320SCEVHandle ScalarEvolutionsImpl::
2321ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2322 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2323 if (PN == 0) return UnknownValue;
2324
2325 // Since the loop is canonicalized, the PHI node must have two entries. One
2326 // entry must be a constant (coming in from outside of the loop), and the
2327 // second must be derived from the same PHI.
2328 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2329 Constant *StartCST =
2330 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2331 if (StartCST == 0) return UnknownValue; // Must be a constant.
2332
2333 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2334 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2335 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2336
2337 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2338 // the loop symbolically to determine when the condition gets a value of
2339 // "ExitWhen".
2340 unsigned IterationNum = 0;
2341 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2342 for (Constant *PHIVal = StartCST;
2343 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002344 ConstantInt *CondVal =
2345 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002346
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002347 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002348 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002349
Reid Spencere8019bb2007-03-01 07:25:48 +00002350 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002351 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002352 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002353 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002354 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002355
Chris Lattner3221ad02004-04-17 22:58:41 +00002356 // Compute the value of the PHI node for the next iteration.
2357 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2358 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002359 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002360 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002361 }
2362
2363 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002364 return UnknownValue;
2365}
2366
2367/// getSCEVAtScope - Compute the value of the specified expression within the
2368/// indicated loop (which may be null to indicate in no loop). If the
2369/// expression cannot be evaluated, return UnknownValue.
2370SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2371 // FIXME: this should be turned into a virtual method on SCEV!
2372
Chris Lattner3221ad02004-04-17 22:58:41 +00002373 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002374
Nick Lewycky3e630762008-02-20 06:48:22 +00002375 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002376 // exit value from the loop without using SCEVs.
2377 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2378 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2379 const Loop *LI = this->LI[I->getParent()];
2380 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2381 if (PHINode *PN = dyn_cast<PHINode>(I))
2382 if (PN->getParent() == LI->getHeader()) {
2383 // Okay, there is no closed form solution for the PHI node. Check
2384 // to see if the loop that contains it has a known iteration count.
2385 // If so, we may be able to force computation of the exit value.
2386 SCEVHandle IterationCount = getIterationCount(LI);
2387 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2388 // Okay, we know how many times the containing loop executes. If
2389 // this is a constant evolving PHI node, get the final value at
2390 // the specified iteration number.
2391 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002392 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002393 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002394 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002395 }
2396 }
2397
Reid Spencer09906f32006-12-04 21:33:23 +00002398 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002399 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002400 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002401 // result. This is particularly useful for computing loop exit values.
2402 if (CanConstantFold(I)) {
2403 std::vector<Constant*> Operands;
2404 Operands.reserve(I->getNumOperands());
2405 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2406 Value *Op = I->getOperand(i);
2407 if (Constant *C = dyn_cast<Constant>(Op)) {
2408 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002409 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002410 // If any of the operands is non-constant and if they are
2411 // non-integer, don't even try to analyze them with scev techniques.
2412 if (!isa<IntegerType>(Op->getType()))
2413 return V;
2414
Chris Lattner3221ad02004-04-17 22:58:41 +00002415 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2416 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002417 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2418 Op->getType(),
2419 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002420 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2421 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002422 Operands.push_back(ConstantExpr::getIntegerCast(C,
2423 Op->getType(),
2424 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002425 else
2426 return V;
2427 } else {
2428 return V;
2429 }
2430 }
2431 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002432
2433 Constant *C;
2434 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2435 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2436 &Operands[0], Operands.size());
2437 else
2438 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2439 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002440 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002441 }
2442 }
2443
2444 // This is some other type of SCEVUnknown, just return it.
2445 return V;
2446 }
2447
Chris Lattner53e677a2004-04-02 20:23:17 +00002448 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2449 // Avoid performing the look-up in the common case where the specified
2450 // expression has no loop-variant portions.
2451 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2452 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2453 if (OpAtScope != Comm->getOperand(i)) {
2454 if (OpAtScope == UnknownValue) return UnknownValue;
2455 // Okay, at least one of these operands is loop variant but might be
2456 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002457 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002458 NewOps.push_back(OpAtScope);
2459
2460 for (++i; i != e; ++i) {
2461 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2462 if (OpAtScope == UnknownValue) return UnknownValue;
2463 NewOps.push_back(OpAtScope);
2464 }
2465 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002466 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002467 if (isa<SCEVMulExpr>(Comm))
2468 return SE.getMulExpr(NewOps);
2469 if (isa<SCEVSMaxExpr>(Comm))
2470 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002471 if (isa<SCEVUMaxExpr>(Comm))
2472 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002473 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002474 }
2475 }
2476 // If we got here, all operands are loop invariant.
2477 return Comm;
2478 }
2479
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002480 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Chris Lattner60a05cc2006-04-01 04:48:52 +00002481 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002482 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002483 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002484 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002485 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2486 return Div; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002487 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002488 }
2489
2490 // If this is a loop recurrence for a loop that does not contain L, then we
2491 // are dealing with the final value computed by the loop.
2492 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2493 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2494 // To evaluate this recurrence, we need to know how many times the AddRec
2495 // loop iterates. Compute this now.
2496 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2497 if (IterationCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002498
Eli Friedmanb42a6262008-08-04 23:49:06 +00002499 // Then, evaluate the AddRec.
Dan Gohman246b2562007-10-22 18:31:58 +00002500 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002501 }
2502 return UnknownValue;
2503 }
2504
2505 //assert(0 && "Unknown SCEV type!");
2506 return UnknownValue;
2507}
2508
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002509/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2510/// following equation:
2511///
2512/// A * X = B (mod N)
2513///
2514/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2515/// A and B isn't important.
2516///
2517/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2518static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2519 ScalarEvolution &SE) {
2520 uint32_t BW = A.getBitWidth();
2521 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2522 assert(A != 0 && "A must be non-zero.");
2523
2524 // 1. D = gcd(A, N)
2525 //
2526 // The gcd of A and N may have only one prime factor: 2. The number of
2527 // trailing zeros in A is its multiplicity
2528 uint32_t Mult2 = A.countTrailingZeros();
2529 // D = 2^Mult2
2530
2531 // 2. Check if B is divisible by D.
2532 //
2533 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2534 // is not less than multiplicity of this prime factor for D.
2535 if (B.countTrailingZeros() < Mult2)
2536 return new SCEVCouldNotCompute();
2537
2538 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2539 // modulo (N / D).
2540 //
2541 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2542 // bit width during computations.
2543 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2544 APInt Mod(BW + 1, 0);
2545 Mod.set(BW - Mult2); // Mod = N / D
2546 APInt I = AD.multiplicativeInverse(Mod);
2547
2548 // 4. Compute the minimum unsigned root of the equation:
2549 // I * (B / D) mod (N / D)
2550 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2551
2552 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2553 // bits.
2554 return SE.getConstant(Result.trunc(BW));
2555}
Chris Lattner53e677a2004-04-02 20:23:17 +00002556
2557/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2558/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2559/// might be the same) or two SCEVCouldNotCompute objects.
2560///
2561static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002562SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002563 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002564 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2565 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2566 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002567
Chris Lattner53e677a2004-04-02 20:23:17 +00002568 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002569 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002570 SCEV *CNC = new SCEVCouldNotCompute();
2571 return std::make_pair(CNC, CNC);
2572 }
2573
Reid Spencere8019bb2007-03-01 07:25:48 +00002574 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002575 const APInt &L = LC->getValue()->getValue();
2576 const APInt &M = MC->getValue()->getValue();
2577 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002578 APInt Two(BitWidth, 2);
2579 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002580
Reid Spencere8019bb2007-03-01 07:25:48 +00002581 {
2582 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002583 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002584 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2585 // The B coefficient is M-N/2
2586 APInt B(M);
2587 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002588
Reid Spencere8019bb2007-03-01 07:25:48 +00002589 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002590 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002591
Reid Spencere8019bb2007-03-01 07:25:48 +00002592 // Compute the B^2-4ac term.
2593 APInt SqrtTerm(B);
2594 SqrtTerm *= B;
2595 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002596
Reid Spencere8019bb2007-03-01 07:25:48 +00002597 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2598 // integer value or else APInt::sqrt() will assert.
2599 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002600
Reid Spencere8019bb2007-03-01 07:25:48 +00002601 // Compute the two solutions for the quadratic formula.
2602 // The divisions must be performed as signed divisions.
2603 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002604 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002605 if (TwoA.isMinValue()) {
2606 SCEV *CNC = new SCEVCouldNotCompute();
2607 return std::make_pair(CNC, CNC);
2608 }
2609
Reid Spencere8019bb2007-03-01 07:25:48 +00002610 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2611 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002612
Dan Gohman246b2562007-10-22 18:31:58 +00002613 return std::make_pair(SE.getConstant(Solution1),
2614 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002615 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002616}
2617
2618/// HowFarToZero - Return the number of times a backedge comparing the specified
2619/// value to zero will execute. If not computable, return UnknownValue
2620SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2621 // If the value is a constant
2622 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2623 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002624 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002625 return UnknownValue; // Otherwise it will loop infinitely.
2626 }
2627
2628 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2629 if (!AddRec || AddRec->getLoop() != L)
2630 return UnknownValue;
2631
2632 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002633 // If this is an affine expression, the execution count of this branch is
2634 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002635 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002636 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002637 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002638 // equivalent to:
2639 //
2640 // Step*N = -Start (mod 2^BW)
2641 //
2642 // where BW is the common bit width of Start and Step.
2643
Chris Lattner53e677a2004-04-02 20:23:17 +00002644 // Get the initial value for the loop.
2645 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002646 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002647
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002648 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002649
Chris Lattner53e677a2004-04-02 20:23:17 +00002650 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002651 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002652
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002653 // First, handle unitary steps.
2654 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2655 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2656 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2657 return Start; // N = Start (as unsigned)
2658
2659 // Then, try to solve the above equation provided that Start is constant.
2660 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2661 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2662 -StartC->getValue()->getValue(),SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002663 }
Chris Lattner42a75512007-01-15 02:27:26 +00002664 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002665 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2666 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002667 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002668 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2669 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2670 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002671#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002672 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2673 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002674#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002675 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002676 if (ConstantInt *CB =
2677 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002678 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002679 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002680 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002681
Chris Lattner53e677a2004-04-02 20:23:17 +00002682 // We can only use this value if the chrec ends up with an exact zero
2683 // value at this index. When solving for "X*X != 5", for example, we
2684 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002685 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002686 if (Val->isZero())
2687 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002688 }
2689 }
2690 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002691
Chris Lattner53e677a2004-04-02 20:23:17 +00002692 return UnknownValue;
2693}
2694
2695/// HowFarToNonZero - Return the number of times a backedge checking the
2696/// specified value for nonzero will execute. If not computable, return
2697/// UnknownValue
2698SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2699 // Loops that look like: while (X == 0) are very strange indeed. We don't
2700 // handle them yet except for the trivial case. This could be expanded in the
2701 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002702
Chris Lattner53e677a2004-04-02 20:23:17 +00002703 // If the value is a constant, check to see if it is known to be non-zero
2704 // already. If so, the backedge will execute zero times.
2705 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002706 if (!C->getValue()->isNullValue())
2707 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002708 return UnknownValue; // Otherwise it will loop infinitely.
2709 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002710
Chris Lattner53e677a2004-04-02 20:23:17 +00002711 // We could implement others, but I really doubt anyone writes loops like
2712 // this, and if they did, they would already be constant folded.
2713 return UnknownValue;
2714}
2715
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002716/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2717/// (which may not be an immediate predecessor) which has exactly one
2718/// successor from which BB is reachable, or null if no such block is
2719/// found.
2720///
2721BasicBlock *
2722ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2723 // If the block has a unique predecessor, the predecessor must have
2724 // no other successors from which BB is reachable.
2725 if (BasicBlock *Pred = BB->getSinglePredecessor())
2726 return Pred;
2727
2728 // A loop's header is defined to be a block that dominates the loop.
2729 // If the loop has a preheader, it must be a block that has exactly
2730 // one successor that can reach BB. This is slightly more strict
2731 // than necessary, but works if critical edges are split.
2732 if (Loop *L = LI.getLoopFor(BB))
2733 return L->getLoopPreheader();
2734
2735 return 0;
2736}
2737
Nick Lewycky59cff122008-07-12 07:41:32 +00002738/// executesAtLeastOnce - Test whether entry to the loop is protected by
2739/// a conditional between LHS and RHS.
2740bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2741 SCEV *LHS, SCEV *RHS) {
2742 BasicBlock *Preheader = L->getLoopPreheader();
2743 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00002744
Dan Gohman38372182008-08-12 20:17:31 +00002745 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002746 // there are predecessors that can be found that have unique successors
2747 // leading to the original header.
2748 for (; Preheader;
2749 PreheaderDest = Preheader,
2750 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00002751
2752 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00002753 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00002754 if (!LoopEntryPredicate ||
2755 LoopEntryPredicate->isUnconditional())
2756 continue;
2757
2758 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2759 if (!ICI) continue;
2760
2761 // Now that we found a conditional branch that dominates the loop, check to
2762 // see if it is the comparison we are looking for.
2763 Value *PreCondLHS = ICI->getOperand(0);
2764 Value *PreCondRHS = ICI->getOperand(1);
2765 ICmpInst::Predicate Cond;
2766 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2767 Cond = ICI->getPredicate();
2768 else
2769 Cond = ICI->getInversePredicate();
2770
2771 switch (Cond) {
2772 case ICmpInst::ICMP_UGT:
2773 if (isSigned) continue;
2774 std::swap(PreCondLHS, PreCondRHS);
2775 Cond = ICmpInst::ICMP_ULT;
2776 break;
2777 case ICmpInst::ICMP_SGT:
2778 if (!isSigned) continue;
2779 std::swap(PreCondLHS, PreCondRHS);
2780 Cond = ICmpInst::ICMP_SLT;
2781 break;
2782 case ICmpInst::ICMP_ULT:
2783 if (isSigned) continue;
2784 break;
2785 case ICmpInst::ICMP_SLT:
2786 if (!isSigned) continue;
2787 break;
2788 default:
2789 continue;
2790 }
2791
2792 if (!PreCondLHS->getType()->isInteger()) continue;
2793
2794 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2795 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2796 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2797 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2798 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2799 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00002800 }
2801
Dan Gohman38372182008-08-12 20:17:31 +00002802 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00002803}
2804
Chris Lattnerdb25de42005-08-15 23:33:51 +00002805/// HowManyLessThans - Return the number of times a backedge containing the
2806/// specified less-than comparison will execute. If not computable, return
2807/// UnknownValue.
2808SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002809HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002810 // Only handle: "ADDREC < LoopInvariant".
2811 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2812
2813 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2814 if (!AddRec || AddRec->getLoop() != L)
2815 return UnknownValue;
2816
2817 if (AddRec->isAffine()) {
2818 // FORNOW: We only support unit strides.
Dan Gohman246b2562007-10-22 18:31:58 +00002819 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Chris Lattnerdb25de42005-08-15 23:33:51 +00002820 if (AddRec->getOperand(1) != One)
2821 return UnknownValue;
2822
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002823 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2824 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2825 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002826 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002827
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002828 // First, we get the value of the LHS in the first iteration: n
2829 SCEVHandle Start = AddRec->getOperand(0);
2830
Nick Lewycky59cff122008-07-12 07:41:32 +00002831 if (executesAtLeastOnce(L, isSigned,
Nick Lewycky86dae652008-07-15 03:40:27 +00002832 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2833 // Since we know that the condition is true in order to enter the loop,
2834 // we know that it will run exactly m-n times.
Nick Lewycky59cff122008-07-12 07:41:32 +00002835 return SE.getMinusSCEV(RHS, Start);
Nick Lewycky86dae652008-07-15 03:40:27 +00002836 } else {
2837 // Then, we get the value of the LHS in the first iteration in which the
2838 // above condition doesn't hold. This equals to max(m,n).
Nick Lewycky59cff122008-07-12 07:41:32 +00002839 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2840 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002841
Nick Lewycky59cff122008-07-12 07:41:32 +00002842 // Finally, we subtract these two values to get the number of times the
2843 // backedge is executed: max(m,n)-n.
2844 return SE.getMinusSCEV(End, Start);
2845 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002846 }
2847
2848 return UnknownValue;
2849}
2850
Chris Lattner53e677a2004-04-02 20:23:17 +00002851/// getNumIterationsInRange - Return the number of iterations of this loop that
2852/// produce values in the specified constant range. Another way of looking at
2853/// this is that it returns the first iteration number where the value is not in
2854/// the condition, thus computing the exit count. If the iteration count can't
2855/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002856SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2857 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002858 if (Range.isFullSet()) // Infinite loop.
2859 return new SCEVCouldNotCompute();
2860
2861 // If the start is a non-zero constant, shift the range to simplify things.
2862 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002863 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002864 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002865 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2866 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002867 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2868 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002869 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002870 // This is strange and shouldn't happen.
2871 return new SCEVCouldNotCompute();
2872 }
2873
2874 // The only time we can solve this is when we have all constant indices.
2875 // Otherwise, we cannot determine the overflow conditions.
2876 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2877 if (!isa<SCEVConstant>(getOperand(i)))
2878 return new SCEVCouldNotCompute();
2879
2880
2881 // Okay at this point we know that all elements of the chrec are constants and
2882 // that the start element is zero.
2883
2884 // First check to see if the range contains zero. If not, the first
2885 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002886 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002887 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002888
Chris Lattner53e677a2004-04-02 20:23:17 +00002889 if (isAffine()) {
2890 // If this is an affine expression then we have this situation:
2891 // Solve {0,+,A} in Range === Ax in Range
2892
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002893 // We know that zero is in the range. If A is positive then we know that
2894 // the upper value of the range must be the first possible exit value.
2895 // If A is negative then the lower of the range is the last possible loop
2896 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002897 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002898 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2899 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002900
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002901 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002902 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002903 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002904
2905 // Evaluate at the exit value. If we really did fall out of the valid
2906 // range, then we computed our trip count, otherwise wrap around or other
2907 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00002908 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002909 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002910 return new SCEVCouldNotCompute(); // Something strange happened
2911
2912 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002913 assert(Range.contains(
2914 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002915 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002916 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00002917 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00002918 } else if (isQuadratic()) {
2919 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2920 // quadratic equation to solve it. To do this, we must frame our problem in
2921 // terms of figuring out when zero is crossed, instead of when
2922 // Range.getUpper() is crossed.
2923 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002924 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2925 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002926
2927 // Next, solve the constructed addrec
2928 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00002929 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002930 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2931 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2932 if (R1) {
2933 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002934 if (ConstantInt *CB =
2935 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002936 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002937 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002938 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002939
Chris Lattner53e677a2004-04-02 20:23:17 +00002940 // Make sure the root is not off by one. The returned iteration should
2941 // not be in the range, but the previous one should be. When solving
2942 // for "X*X < 5", for example, we should not return a root of 2.
2943 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002944 R1->getValue(),
2945 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002946 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002947 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00002948 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002949
Dan Gohman246b2562007-10-22 18:31:58 +00002950 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002951 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002952 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002953 return new SCEVCouldNotCompute(); // Something strange happened
2954 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002955
Chris Lattner53e677a2004-04-02 20:23:17 +00002956 // If R1 was not in the range, then it is a good return value. Make
2957 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00002958 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00002959 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002960 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002961 return R1;
2962 return new SCEVCouldNotCompute(); // Something strange happened
2963 }
2964 }
2965 }
2966
Chris Lattner53e677a2004-04-02 20:23:17 +00002967 return new SCEVCouldNotCompute();
2968}
2969
2970
2971
2972//===----------------------------------------------------------------------===//
2973// ScalarEvolution Class Implementation
2974//===----------------------------------------------------------------------===//
2975
2976bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00002977 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00002978 return false;
2979}
2980
2981void ScalarEvolution::releaseMemory() {
2982 delete (ScalarEvolutionsImpl*)Impl;
2983 Impl = 0;
2984}
2985
2986void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2987 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002988 AU.addRequiredTransitive<LoopInfo>();
2989}
2990
2991SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2992 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2993}
2994
Chris Lattnera0740fb2005-08-09 23:36:33 +00002995/// hasSCEV - Return true if the SCEV for this value has already been
2996/// computed.
2997bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002998 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002999}
3000
3001
3002/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3003/// the specified value.
3004void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3005 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3006}
3007
3008
Chris Lattner53e677a2004-04-02 20:23:17 +00003009SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3010 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3011}
3012
3013bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3014 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3015}
3016
3017SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3018 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3019}
3020
Dan Gohman5cec4db2007-06-19 14:28:31 +00003021void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3022 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003023}
3024
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003025static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003026 const Loop *L) {
3027 // Print all inner loops first
3028 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3029 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003030
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003031 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003032
Devang Patelb7211a22007-08-21 00:31:24 +00003033 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003034 L->getExitBlocks(ExitBlocks);
3035 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003036 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003037
3038 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003039 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003040 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003041 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003042 }
3043
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003044 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003045}
3046
Reid Spencerce9653c2004-12-07 04:03:45 +00003047void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003048 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3049 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3050
3051 OS << "Classifying expressions for: " << F.getName() << "\n";
3052 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00003053 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003054 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003055 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003056 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003057 SV->print(OS);
3058 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003059
Chris Lattner6ffe5512004-04-27 15:13:33 +00003060 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003061 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003062 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003063 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3064 OS << "<<Unknown>>";
3065 } else {
3066 OS << *ExitValue;
3067 }
3068 }
3069
3070
3071 OS << "\n";
3072 }
3073
3074 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3075 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3076 PrintLoopInfo(OS, this, *I);
3077}