blob: d9394805c8b7bdc8c589da2c9c1c6222ab112057 [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"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000070#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000073#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000074#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000075#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000076#include "llvm/Support/ConstantRange.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000077#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000078#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000079#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000080#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000081#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000082#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000083#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000084#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000085using namespace llvm;
86
Chris Lattner3b27d682006-12-19 22:30:33 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman844731a2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman844731a2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000104char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
Chris Lattner53e677a2004-04-02 20:23:17 +0000113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000122}
123
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohman70a1fe72009-05-18 15:22:39 +0000130bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
133 return false;
134}
Chris Lattner53e677a2004-04-02 20:23:17 +0000135
Owen Anderson4a7893b2009-06-18 22:25:12 +0000136SCEVCouldNotCompute::SCEVCouldNotCompute(const ScalarEvolution* p) :
137 SCEV(scCouldNotCompute, p) {}
Dan Gohmanf8a8be82009-04-21 23:15:49 +0000138SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
Chris Lattner4dc534c2005-02-13 04:37:18 +0000155SCEVHandle SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000159 return this;
160}
161
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000162void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000163 OS << "***COULDNOTCOMPUTE***";
164}
165
166bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
168}
169
170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171// SCEVConstants - Only allow the creation of one SCEVConstant for any
172// particular value. Don't use a SCEVHandle here, or else the object will
173// never be deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000174
Dan Gohman246b2562007-10-22 18:31:58 +0000175SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Owen Anderson08367b62009-06-22 18:25:46 +0000176 SCEVConstant *&R = SCEVConstants[V];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000177 if (R == 0) R = new SCEVConstant(V, this);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178 return R;
179}
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Dan Gohman246b2562007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
182 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000183}
184
Dan Gohman6de29f82009-06-15 22:12:54 +0000185SCEVHandle
186ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
187 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
188}
189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000191
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000192void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193 WriteAsOperand(OS, V, false);
194}
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Dan Gohman84923602009-04-21 01:25:57 +0000196SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Anderson4a7893b2009-06-18 22:25:12 +0000197 const SCEVHandle &op, const Type *ty,
198 const ScalarEvolution* p)
199 : SCEV(SCEVTy, p), Op(op), Ty(ty) {}
Dan Gohman84923602009-04-21 01:25:57 +0000200
201SCEVCastExpr::~SCEVCastExpr() {}
202
203bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
204 return Op->dominates(BB, DT);
205}
206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
208// particular input. Don't use a SCEVHandle here, or else the object will
209// never be deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000210
Owen Anderson4a7893b2009-06-18 22:25:12 +0000211SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty,
212 const ScalarEvolution* p)
213 : SCEVCastExpr(scTruncate, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000214 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
215 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner53e677a2004-04-02 20:23:17 +0000219
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000220void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000221 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000222}
223
224// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
225// particular input. Don't use a SCEVHandle here, or else the object will never
226// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227
Owen Anderson4a7893b2009-06-18 22:25:12 +0000228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty,
229 const ScalarEvolution* p)
230 : SCEVCastExpr(scZeroExtend, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000231 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
232 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234}
235
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000236void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000237 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000238}
239
Dan Gohmand19534a2007-06-15 14:38:12 +0000240// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
241// particular input. Don't use a SCEVHandle here, or else the object will never
242// be deleted!
Dan Gohmand19534a2007-06-15 14:38:12 +0000243
Owen Anderson4a7893b2009-06-18 22:25:12 +0000244SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty,
245 const ScalarEvolution* p)
246 : SCEVCastExpr(scSignExtend, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000247 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
248 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000249 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000250}
251
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000252void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000253 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000254}
255
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000256// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
257// particular input. Don't use a SCEVHandle here, or else the object will never
258// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000259
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000260void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000261 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
262 const char *OpStr = getOperationStr();
263 OS << "(" << *Operands[0];
264 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
265 OS << OpStr << *Operands[i];
266 OS << ")";
267}
268
Chris Lattner4dc534c2005-02-13 04:37:18 +0000269SCEVHandle SCEVCommutativeExpr::
270replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000271 const SCEVHandle &Conc,
272 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000274 SCEVHandle H =
275 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000276 if (H != getOperand(i)) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000277 SmallVector<SCEVHandle, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000278 NewOps.reserve(getNumOperands());
279 for (unsigned j = 0; j != i; ++j)
280 NewOps.push_back(getOperand(j));
281 NewOps.push_back(H);
282 for (++i; i != e; ++i)
283 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000284 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000285
286 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000287 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000288 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000289 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000290 else if (isa<SCEVSMaxExpr>(this))
291 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000292 else if (isa<SCEVUMaxExpr>(this))
293 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000294 else
295 assert(0 && "Unknown commutative expr!");
296 }
297 }
298 return this;
299}
300
Dan Gohmanecb403a2009-05-07 14:00:19 +0000301bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000302 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
303 if (!getOperand(i)->dominates(BB, DT))
304 return false;
305 }
306 return true;
307}
308
Chris Lattner4dc534c2005-02-13 04:37:18 +0000309
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000310// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000311// input. Don't use a SCEVHandle here, or else the object will never be
312// deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000313
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000314bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
315 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
316}
317
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000318void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000319 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000320}
321
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000322const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000323 // In most cases the types of LHS and RHS will be the same, but in some
324 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
325 // depend on the type for correctness, but handling types carefully can
326 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
327 // a pointer type than the RHS, so use the RHS' type here.
328 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000329}
330
331// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
332// particular input. Don't use a SCEVHandle here, or else the object will never
333// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334
Chris Lattner4dc534c2005-02-13 04:37:18 +0000335SCEVHandle SCEVAddRecExpr::
336replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000337 const SCEVHandle &Conc,
338 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000339 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000340 SCEVHandle H =
341 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000342 if (H != getOperand(i)) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000343 SmallVector<SCEVHandle, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000344 NewOps.reserve(getNumOperands());
345 for (unsigned j = 0; j != i; ++j)
346 NewOps.push_back(getOperand(j));
347 NewOps.push_back(H);
348 for (++i; i != e; ++i)
349 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000350 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000351
Dan Gohman246b2562007-10-22 18:31:58 +0000352 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000353 }
354 }
355 return this;
356}
357
358
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000359bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
360 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000361 // contain L and if the start is invariant.
Dan Gohmana3035a62009-05-20 01:01:24 +0000362 // Add recurrences are never invariant in the function-body (null loop).
363 return QueryLoop &&
364 !QueryLoop->contains(L->getHeader()) &&
Chris Lattnerff2006a2005-08-16 00:37:01 +0000365 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000366}
367
368
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000369void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000370 OS << "{" << *Operands[0];
371 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
372 OS << ",+," << *Operands[i];
373 OS << "}<" << L->getHeader()->getName() + ">";
374}
Chris Lattner53e677a2004-04-02 20:23:17 +0000375
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000376// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
377// value. Don't use a SCEVHandle here, or else the object will never be
378// deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000379
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000380bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
381 // All non-instruction values are loop invariant. All instructions are loop
382 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000383 // Instructions are never considered invariant in the function body
384 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000386 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000387 return true;
388}
Chris Lattner53e677a2004-04-02 20:23:17 +0000389
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000390bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
391 if (Instruction *I = dyn_cast<Instruction>(getValue()))
392 return DT->dominates(I->getParent(), BB);
393 return true;
394}
395
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000396const Type *SCEVUnknown::getType() const {
397 return V->getType();
398}
Chris Lattner53e677a2004-04-02 20:23:17 +0000399
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000400void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000401 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000402}
403
Chris Lattner8d741b82004-06-20 06:23:15 +0000404//===----------------------------------------------------------------------===//
405// SCEV Utilities
406//===----------------------------------------------------------------------===//
407
408namespace {
409 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
410 /// than the complexity of the RHS. This comparator is used to canonicalize
411 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000412 class VISIBILITY_HIDDEN SCEVComplexityCompare {
413 LoopInfo *LI;
414 public:
415 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
416
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000417 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000418 // Primarily, sort the SCEVs by their getSCEVType().
419 if (LHS->getSCEVType() != RHS->getSCEVType())
420 return LHS->getSCEVType() < RHS->getSCEVType();
421
422 // Aside from the getSCEVType() ordering, the particular ordering
423 // isn't very important except that it's beneficial to be consistent,
424 // so that (a + b) and (b + a) don't end up as different expressions.
425
426 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
427 // not as complete as it could be.
428 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
429 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
430
Dan Gohman5be18e82009-05-19 02:15:55 +0000431 // Order pointer values after integer values. This helps SCEVExpander
432 // form GEPs.
433 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
434 return false;
435 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
436 return true;
437
Dan Gohman72861302009-05-07 14:39:04 +0000438 // Compare getValueID values.
439 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
440 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
441
442 // Sort arguments by their position.
443 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
444 const Argument *RA = cast<Argument>(RU->getValue());
445 return LA->getArgNo() < RA->getArgNo();
446 }
447
448 // For instructions, compare their loop depth, and their opcode.
449 // This is pretty loose.
450 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
451 Instruction *RV = cast<Instruction>(RU->getValue());
452
453 // Compare loop depths.
454 if (LI->getLoopDepth(LV->getParent()) !=
455 LI->getLoopDepth(RV->getParent()))
456 return LI->getLoopDepth(LV->getParent()) <
457 LI->getLoopDepth(RV->getParent());
458
459 // Compare opcodes.
460 if (LV->getOpcode() != RV->getOpcode())
461 return LV->getOpcode() < RV->getOpcode();
462
463 // Compare the number of operands.
464 if (LV->getNumOperands() != RV->getNumOperands())
465 return LV->getNumOperands() < RV->getNumOperands();
466 }
467
468 return false;
469 }
470
Dan Gohman4dfad292009-06-14 22:51:25 +0000471 // Compare constant values.
472 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
473 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
474 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
475 }
476
477 // Compare addrec loop depths.
478 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
479 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
480 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
481 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
482 }
Dan Gohman72861302009-05-07 14:39:04 +0000483
484 // Lexicographically compare n-ary expressions.
485 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
486 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
487 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
488 if (i >= RC->getNumOperands())
489 return false;
490 if (operator()(LC->getOperand(i), RC->getOperand(i)))
491 return true;
492 if (operator()(RC->getOperand(i), LC->getOperand(i)))
493 return false;
494 }
495 return LC->getNumOperands() < RC->getNumOperands();
496 }
497
Dan Gohmana6b35e22009-05-07 19:23:21 +0000498 // Lexicographically compare udiv expressions.
499 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
500 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
501 if (operator()(LC->getLHS(), RC->getLHS()))
502 return true;
503 if (operator()(RC->getLHS(), LC->getLHS()))
504 return false;
505 if (operator()(LC->getRHS(), RC->getRHS()))
506 return true;
507 if (operator()(RC->getRHS(), LC->getRHS()))
508 return false;
509 return false;
510 }
511
Dan Gohman72861302009-05-07 14:39:04 +0000512 // Compare cast expressions by operand.
513 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
514 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
515 return operator()(LC->getOperand(), RC->getOperand());
516 }
517
518 assert(0 && "Unknown SCEV kind!");
519 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000520 }
521 };
522}
523
524/// GroupByComplexity - Given a list of SCEV objects, order them by their
525/// complexity, and group objects of the same complexity together by value.
526/// When this routine is finished, we know that any duplicates in the vector are
527/// consecutive and that complexity is monotonically increasing.
528///
529/// Note that we go take special precautions to ensure that we get determinstic
530/// results from this routine. In other words, we don't want the results of
531/// this to depend on where the addresses of various SCEV objects happened to
532/// land in memory.
533///
Dan Gohmana82752c2009-06-14 22:47:23 +0000534static void GroupByComplexity(SmallVectorImpl<SCEVHandle> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000535 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000536 if (Ops.size() < 2) return; // Noop
537 if (Ops.size() == 2) {
538 // This is the common case, which also happens to be trivially simple.
539 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000540 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000541 std::swap(Ops[0], Ops[1]);
542 return;
543 }
544
545 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000546 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000547
548 // Now that we are sorted by complexity, group elements of the same
549 // complexity. Note that this is, at worst, N^2, but the vector is likely to
550 // be extremely short in practice. Note that we take this approach because we
551 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000552 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000553 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000554 unsigned Complexity = S->getSCEVType();
555
556 // If there are any objects of the same complexity and same value as this
557 // one, group them.
558 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
559 if (Ops[j] == S) { // Found a duplicate.
560 // Move it to immediately after i'th element.
561 std::swap(Ops[i+1], Ops[j]);
562 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000563 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000564 }
565 }
566 }
567}
568
Chris Lattner53e677a2004-04-02 20:23:17 +0000569
Chris Lattner53e677a2004-04-02 20:23:17 +0000570
571//===----------------------------------------------------------------------===//
572// Simple SCEV method implementations
573//===----------------------------------------------------------------------===//
574
Eli Friedmanb42a6262008-08-04 23:49:06 +0000575/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000576/// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000577static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000578 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000579 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000580 // Handle the simplest case efficiently.
581 if (K == 1)
582 return SE.getTruncateOrZeroExtend(It, ResultTy);
583
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000584 // We are using the following formula for BC(It, K):
585 //
586 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
587 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000588 // Suppose, W is the bitwidth of the return value. We must be prepared for
589 // overflow. Hence, we must assure that the result of our computation is
590 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
591 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000592 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000593 // However, this code doesn't use exactly that formula; the formula it uses
594 // is something like the following, where T is the number of factors of 2 in
595 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
596 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000597 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000598 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000599 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000600 // This formula is trivially equivalent to the previous formula. However,
601 // this formula can be implemented much more efficiently. The trick is that
602 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
603 // arithmetic. To do exact division in modular arithmetic, all we have
604 // to do is multiply by the inverse. Therefore, this step can be done at
605 // width W.
606 //
607 // The next issue is how to safely do the division by 2^T. The way this
608 // is done is by doing the multiplication step at a width of at least W + T
609 // bits. This way, the bottom W+T bits of the product are accurate. Then,
610 // when we perform the division by 2^T (which is equivalent to a right shift
611 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
612 // truncated out after the division by 2^T.
613 //
614 // In comparison to just directly using the first formula, this technique
615 // is much more efficient; using the first formula requires W * K bits,
616 // but this formula less than W + K bits. Also, the first formula requires
617 // a division step, whereas this formula only requires multiplies and shifts.
618 //
619 // It doesn't matter whether the subtraction step is done in the calculation
620 // width or the input iteration count's width; if the subtraction overflows,
621 // the result must be zero anyway. We prefer here to do it in the width of
622 // the induction variable because it helps a lot for certain cases; CodeGen
623 // isn't smart enough to ignore the overflow, which leads to much less
624 // efficient code if the width of the subtraction is wider than the native
625 // register width.
626 //
627 // (It's possible to not widen at all by pulling out factors of 2 before
628 // the multiplication; for example, K=2 can be calculated as
629 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
630 // extra arithmetic, so it's not an obvious win, and it gets
631 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000632
Eli Friedmanb42a6262008-08-04 23:49:06 +0000633 // Protection from insane SCEVs; this bound is conservative,
634 // but it probably doesn't matter.
635 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000636 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000637
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000638 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000639
Eli Friedmanb42a6262008-08-04 23:49:06 +0000640 // Calculate K! / 2^T and T; we divide out the factors of two before
641 // multiplying for calculating K! / 2^T to avoid overflow.
642 // Other overflow doesn't matter because we only care about the bottom
643 // W bits of the result.
644 APInt OddFactorial(W, 1);
645 unsigned T = 1;
646 for (unsigned i = 3; i <= K; ++i) {
647 APInt Mult(W, i);
648 unsigned TwoFactors = Mult.countTrailingZeros();
649 T += TwoFactors;
650 Mult = Mult.lshr(TwoFactors);
651 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000652 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000653
Eli Friedmanb42a6262008-08-04 23:49:06 +0000654 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000655 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000656
657 // Calcuate 2^T, at width T+W.
658 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
659
660 // Calculate the multiplicative inverse of K! / 2^T;
661 // this multiplication factor will perform the exact division by
662 // K! / 2^T.
663 APInt Mod = APInt::getSignedMinValue(W+1);
664 APInt MultiplyFactor = OddFactorial.zext(W+1);
665 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
666 MultiplyFactor = MultiplyFactor.trunc(W);
667
668 // Calculate the product, at width T+W
669 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
670 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
671 for (unsigned i = 1; i != K; ++i) {
672 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
673 Dividend = SE.getMulExpr(Dividend,
674 SE.getTruncateOrZeroExtend(S, CalculationTy));
675 }
676
677 // Divide by 2^T
678 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
679
680 // Truncate the result, and divide by K! / 2^T.
681
682 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
683 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000684}
685
Chris Lattner53e677a2004-04-02 20:23:17 +0000686/// evaluateAtIteration - Return the value of this chain of recurrences at
687/// the specified iteration number. We can evaluate this recurrence by
688/// multiplying each element in the chain by the binomial coefficient
689/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
690///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000691/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000692///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000693/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000694///
Dan Gohman246b2562007-10-22 18:31:58 +0000695SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
696 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000697 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000698 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000699 // The computation is correct in the face of overflow provided that the
700 // multiplication is performed _after_ the evaluation of the binomial
701 // coefficient.
Dan Gohman2d1be872009-04-16 03:18:22 +0000702 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000703 if (isa<SCEVCouldNotCompute>(Coeff))
704 return Coeff;
705
706 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000707 }
708 return Result;
709}
710
Chris Lattner53e677a2004-04-02 20:23:17 +0000711//===----------------------------------------------------------------------===//
712// SCEV Expression folder implementations
713//===----------------------------------------------------------------------===//
714
Dan Gohman99243b32009-05-01 16:44:56 +0000715SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
716 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000717 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000718 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000719 assert(isSCEVable(Ty) &&
720 "This is not a conversion to a SCEVable type!");
721 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000722
Dan Gohman622ed672009-05-04 22:02:23 +0000723 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000724 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000725 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000726
Dan Gohman20900ca2009-04-22 16:20:48 +0000727 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000728 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000729 return getTruncateExpr(ST->getOperand(), Ty);
730
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000731 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000732 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000733 return getTruncateOrSignExtend(SS->getOperand(), Ty);
734
735 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000736 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000737 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
738
Dan Gohman6864db62009-06-18 16:24:47 +0000739 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000740 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000741 SmallVector<SCEVHandle, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000742 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000743 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
744 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000745 }
746
Owen Anderson08367b62009-06-22 18:25:46 +0000747 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000748 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty, this);
Chris Lattner53e677a2004-04-02 20:23:17 +0000749 return Result;
750}
751
Dan Gohman8170a682009-04-16 19:25:55 +0000752SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
753 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000754 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000755 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000756 assert(isSCEVable(Ty) &&
757 "This is not a conversion to a SCEVable type!");
758 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000759
Dan Gohman622ed672009-05-04 22:02:23 +0000760 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000761 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000762 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
763 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
764 return getUnknown(C);
765 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000766
Dan Gohman20900ca2009-04-22 16:20:48 +0000767 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000768 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000769 return getZeroExtendExpr(SZ->getOperand(), Ty);
770
Dan Gohman01ecca22009-04-27 20:16:15 +0000771 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000772 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000773 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000774 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000775 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000776 if (AR->isAffine()) {
777 // Check whether the backedge-taken count is SCEVCouldNotCompute.
778 // Note that this serves two purposes: It filters out loops that are
779 // simply not analyzable, and it covers the case where this code is
780 // being called from within backedge-taken count analysis, such that
781 // attempting to ask for the backedge-taken count would likely result
782 // in infinite recursion. In the later case, the analysis code will
783 // cope with a conservative value, and it will take care to purge
784 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000785 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
786 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000787 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000788 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000789 SCEVHandle Start = AR->getStart();
790 SCEVHandle Step = AR->getStepRecurrence(*this);
791
792 // Check whether the backedge-taken count can be losslessly casted to
793 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000794 SCEVHandle CastedMaxBECount =
795 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman5183cae2009-05-18 15:58:39 +0000796 SCEVHandle RecastedMaxBECount =
797 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
798 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000799 const Type *WideTy =
800 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000801 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000802 SCEVHandle ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000803 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000804 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000805 SCEVHandle Add = getAddExpr(Start, ZMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000806 SCEVHandle OperandExtendedAdd =
807 getAddExpr(getZeroExtendExpr(Start, WideTy),
808 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
809 getZeroExtendExpr(Step, WideTy)));
810 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000811 // Return the expression with the addrec on the outside.
812 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
813 getZeroExtendExpr(Step, Ty),
814 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000815
816 // Similar to above, only this time treat the step value as signed.
817 // This covers loops that count down.
818 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000819 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000820 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000821 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000822 OperandExtendedAdd =
823 getAddExpr(getZeroExtendExpr(Start, WideTy),
824 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
825 getSignExtendExpr(Step, WideTy)));
826 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000827 // Return the expression with the addrec on the outside.
828 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
829 getSignExtendExpr(Step, Ty),
830 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000831 }
832 }
833 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000834
Owen Anderson08367b62009-06-22 18:25:46 +0000835 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000836 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty, this);
Chris Lattner53e677a2004-04-02 20:23:17 +0000837 return Result;
838}
839
Dan Gohman01ecca22009-04-27 20:16:15 +0000840SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
841 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000842 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000843 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000844 assert(isSCEVable(Ty) &&
845 "This is not a conversion to a SCEVable type!");
846 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000847
Dan Gohman622ed672009-05-04 22:02:23 +0000848 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000849 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000850 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
851 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
852 return getUnknown(C);
853 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000854
Dan Gohman20900ca2009-04-22 16:20:48 +0000855 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000856 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000857 return getSignExtendExpr(SS->getOperand(), Ty);
858
Dan Gohman01ecca22009-04-27 20:16:15 +0000859 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000860 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000861 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000862 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000863 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000864 if (AR->isAffine()) {
865 // Check whether the backedge-taken count is SCEVCouldNotCompute.
866 // Note that this serves two purposes: It filters out loops that are
867 // simply not analyzable, and it covers the case where this code is
868 // being called from within backedge-taken count analysis, such that
869 // attempting to ask for the backedge-taken count would likely result
870 // in infinite recursion. In the later case, the analysis code will
871 // cope with a conservative value, and it will take care to purge
872 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000873 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
874 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000875 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000876 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000877 SCEVHandle Start = AR->getStart();
878 SCEVHandle Step = AR->getStepRecurrence(*this);
879
880 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000881 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000882 SCEVHandle CastedMaxBECount =
883 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman5183cae2009-05-18 15:58:39 +0000884 SCEVHandle RecastedMaxBECount =
885 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
886 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000887 const Type *WideTy =
888 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000889 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000890 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000891 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000892 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000893 SCEVHandle Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000894 SCEVHandle OperandExtendedAdd =
895 getAddExpr(getSignExtendExpr(Start, WideTy),
896 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
897 getSignExtendExpr(Step, WideTy)));
898 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000899 // Return the expression with the addrec on the outside.
900 return getAddRecExpr(getSignExtendExpr(Start, Ty),
901 getSignExtendExpr(Step, Ty),
902 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000903 }
904 }
905 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000906
Owen Anderson08367b62009-06-22 18:25:46 +0000907 SCEVSignExtendExpr *&Result = SCEVSignExtends[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000908 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty, this);
Dan Gohmand19534a2007-06-15 14:38:12 +0000909 return Result;
910}
911
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000912/// getAnyExtendExpr - Return a SCEV for the given operand extended with
913/// unspecified bits out to the given type.
914///
915SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
916 const Type *Ty) {
917 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
918 "This is not an extending conversion!");
919 assert(isSCEVable(Ty) &&
920 "This is not a conversion to a SCEVable type!");
921 Ty = getEffectiveSCEVType(Ty);
922
923 // Sign-extend negative constants.
924 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
925 if (SC->getValue()->getValue().isNegative())
926 return getSignExtendExpr(Op, Ty);
927
928 // Peel off a truncate cast.
929 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
930 SCEVHandle NewOp = T->getOperand();
931 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
932 return getAnyExtendExpr(NewOp, Ty);
933 return getTruncateOrNoop(NewOp, Ty);
934 }
935
936 // Next try a zext cast. If the cast is folded, use it.
937 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
938 if (!isa<SCEVZeroExtendExpr>(ZExt))
939 return ZExt;
940
941 // Next try a sext cast. If the cast is folded, use it.
942 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
943 if (!isa<SCEVSignExtendExpr>(SExt))
944 return SExt;
945
946 // If the expression is obviously signed, use the sext cast value.
947 if (isa<SCEVSMaxExpr>(Op))
948 return SExt;
949
950 // Absent any other information, use the zext cast value.
951 return ZExt;
952}
953
Dan Gohmanbd59d7b2009-06-14 22:58:51 +0000954/// CollectAddOperandsWithScales - Process the given Ops list, which is
955/// a list of operands to be added under the given scale, update the given
956/// map. This is a helper function for getAddRecExpr. As an example of
957/// what it does, given a sequence of operands that would form an add
958/// expression like this:
959///
960/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
961///
962/// where A and B are constants, update the map with these values:
963///
964/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
965///
966/// and add 13 + A*B*29 to AccumulatedConstant.
967/// This will allow getAddRecExpr to produce this:
968///
969/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
970///
971/// This form often exposes folding opportunities that are hidden in
972/// the original operand list.
973///
974/// Return true iff it appears that any interesting folding opportunities
975/// may be exposed. This helps getAddRecExpr short-circuit extra work in
976/// the common case where no interesting opportunities are present, and
977/// is also used as a check to avoid infinite recursion.
978///
979static bool
980CollectAddOperandsWithScales(DenseMap<SCEVHandle, APInt> &M,
981 SmallVector<SCEVHandle, 8> &NewOps,
982 APInt &AccumulatedConstant,
983 const SmallVectorImpl<SCEVHandle> &Ops,
984 const APInt &Scale,
985 ScalarEvolution &SE) {
986 bool Interesting = false;
987
988 // Iterate over the add operands.
989 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
990 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
991 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
992 APInt NewScale =
993 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
994 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
995 // A multiplication of a constant with another add; recurse.
996 Interesting |=
997 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
998 cast<SCEVAddExpr>(Mul->getOperand(1))
999 ->getOperands(),
1000 NewScale, SE);
1001 } else {
1002 // A multiplication of a constant with some other value. Update
1003 // the map.
1004 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1005 SCEVHandle Key = SE.getMulExpr(MulOps);
1006 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1007 M.insert(std::make_pair(Key, APInt()));
1008 if (Pair.second) {
1009 Pair.first->second = NewScale;
1010 NewOps.push_back(Pair.first->first);
1011 } else {
1012 Pair.first->second += NewScale;
1013 // The map already had an entry for this value, which may indicate
1014 // a folding opportunity.
1015 Interesting = true;
1016 }
1017 }
1018 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1019 // Pull a buried constant out to the outside.
1020 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1021 Interesting = true;
1022 AccumulatedConstant += Scale * C->getValue()->getValue();
1023 } else {
1024 // An ordinary operand. Update the map.
1025 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1026 M.insert(std::make_pair(Ops[i], APInt()));
1027 if (Pair.second) {
1028 Pair.first->second = Scale;
1029 NewOps.push_back(Pair.first->first);
1030 } else {
1031 Pair.first->second += Scale;
1032 // The map already had an entry for this value, which may indicate
1033 // a folding opportunity.
1034 Interesting = true;
1035 }
1036 }
1037 }
1038
1039 return Interesting;
1040}
1041
1042namespace {
1043 struct APIntCompare {
1044 bool operator()(const APInt &LHS, const APInt &RHS) const {
1045 return LHS.ult(RHS);
1046 }
1047 };
1048}
1049
Dan Gohman6c0866c2009-05-24 23:45:28 +00001050/// getAddExpr - Get a canonical add expression, or something simpler if
1051/// possible.
Dan Gohmana82752c2009-06-14 22:47:23 +00001052SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001053 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001054 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001055#ifndef NDEBUG
1056 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1057 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1058 getEffectiveSCEVType(Ops[0]->getType()) &&
1059 "SCEVAddExpr operand types don't match!");
1060#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001061
1062 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001063 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001064
1065 // If there are any constants, fold them together.
1066 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001067 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001068 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001069 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001070 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001071 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001072 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1073 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001074 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001075 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001076 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001077 }
1078
1079 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001080 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001081 Ops.erase(Ops.begin());
1082 --Idx;
1083 }
1084 }
1085
Chris Lattner627018b2004-04-07 16:16:11 +00001086 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001087
Chris Lattner53e677a2004-04-02 20:23:17 +00001088 // Okay, check to see if the same value occurs in the operand list twice. If
1089 // so, merge them together into an multiply expression. Since we sorted the
1090 // list, these values are required to be adjacent.
1091 const Type *Ty = Ops[0]->getType();
1092 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1093 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1094 // Found a match, merge the two values into a multiply, and add any
1095 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +00001096 SCEVHandle Two = getIntegerSCEV(2, Ty);
1097 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001098 if (Ops.size() == 2)
1099 return Mul;
1100 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1101 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001102 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001103 }
1104
Dan Gohman728c7f32009-05-08 21:03:19 +00001105 // Check for truncates. If all the operands are truncated from the same
1106 // type, see if factoring out the truncate would permit the result to be
1107 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1108 // if the contents of the resulting outer trunc fold to something simple.
1109 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1110 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1111 const Type *DstType = Trunc->getType();
1112 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmana82752c2009-06-14 22:47:23 +00001113 SmallVector<SCEVHandle, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001114 bool Ok = true;
1115 // Check all the operands to see if they can be represented in the
1116 // source type of the truncate.
1117 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1118 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1119 if (T->getOperand()->getType() != SrcType) {
1120 Ok = false;
1121 break;
1122 }
1123 LargeOps.push_back(T->getOperand());
1124 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1125 // This could be either sign or zero extension, but sign extension
1126 // is much more likely to be foldable here.
1127 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1128 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001129 SmallVector<SCEVHandle, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001130 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1131 if (const SCEVTruncateExpr *T =
1132 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1133 if (T->getOperand()->getType() != SrcType) {
1134 Ok = false;
1135 break;
1136 }
1137 LargeMulOps.push_back(T->getOperand());
1138 } else if (const SCEVConstant *C =
1139 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1140 // This could be either sign or zero extension, but sign extension
1141 // is much more likely to be foldable here.
1142 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1143 } else {
1144 Ok = false;
1145 break;
1146 }
1147 }
1148 if (Ok)
1149 LargeOps.push_back(getMulExpr(LargeMulOps));
1150 } else {
1151 Ok = false;
1152 break;
1153 }
1154 }
1155 if (Ok) {
1156 // Evaluate the expression in the larger type.
1157 SCEVHandle Fold = getAddExpr(LargeOps);
1158 // If it folds to something simple, use it. Otherwise, don't.
1159 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1160 return getTruncateExpr(Fold, DstType);
1161 }
1162 }
1163
1164 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001165 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1166 ++Idx;
1167
1168 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001169 if (Idx < Ops.size()) {
1170 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001171 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001172 // If we have an add, expand the add operands onto the end of the operands
1173 // list.
1174 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1175 Ops.erase(Ops.begin()+Idx);
1176 DeletedAdd = true;
1177 }
1178
1179 // If we deleted at least one add, we added operands to the end of the list,
1180 // and they are not necessarily sorted. Recurse to resort and resimplify
1181 // any operands we just aquired.
1182 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001183 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001184 }
1185
1186 // Skip over the add expression until we get to a multiply.
1187 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1188 ++Idx;
1189
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001190 // Check to see if there are any folding opportunities present with
1191 // operands multiplied by constant values.
1192 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1193 uint64_t BitWidth = getTypeSizeInBits(Ty);
1194 DenseMap<SCEVHandle, APInt> M;
1195 SmallVector<SCEVHandle, 8> NewOps;
1196 APInt AccumulatedConstant(BitWidth, 0);
1197 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1198 Ops, APInt(BitWidth, 1), *this)) {
1199 // Some interesting folding opportunity is present, so its worthwhile to
1200 // re-generate the operands list. Group the operands by constant scale,
1201 // to avoid multiplying by the same constant scale multiple times.
1202 std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare> MulOpLists;
1203 for (SmallVector<SCEVHandle, 8>::iterator I = NewOps.begin(),
1204 E = NewOps.end(); I != E; ++I)
1205 MulOpLists[M.find(*I)->second].push_back(*I);
1206 // Re-generate the operands list.
1207 Ops.clear();
1208 if (AccumulatedConstant != 0)
1209 Ops.push_back(getConstant(AccumulatedConstant));
1210 for (std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare>::iterator I =
1211 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1212 if (I->first != 0)
1213 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1214 if (Ops.empty())
1215 return getIntegerSCEV(0, Ty);
1216 if (Ops.size() == 1)
1217 return Ops[0];
1218 return getAddExpr(Ops);
1219 }
1220 }
1221
Chris Lattner53e677a2004-04-02 20:23:17 +00001222 // If we are adding something to a multiply expression, make sure the
1223 // something is not already an operand of the multiply. If so, merge it into
1224 // the multiply.
1225 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001226 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001227 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001228 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001229 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001230 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001231 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1232 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1233 if (Mul->getNumOperands() != 2) {
1234 // If the multiply has more than two operands, we must get the
1235 // Y*Z term.
Dan Gohmana82752c2009-06-14 22:47:23 +00001236 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001237 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001238 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001239 }
Dan Gohman246b2562007-10-22 18:31:58 +00001240 SCEVHandle One = getIntegerSCEV(1, Ty);
1241 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1242 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001243 if (Ops.size() == 2) return OuterMul;
1244 if (AddOp < Idx) {
1245 Ops.erase(Ops.begin()+AddOp);
1246 Ops.erase(Ops.begin()+Idx-1);
1247 } else {
1248 Ops.erase(Ops.begin()+Idx);
1249 Ops.erase(Ops.begin()+AddOp-1);
1250 }
1251 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001252 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001253 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001254
Chris Lattner53e677a2004-04-02 20:23:17 +00001255 // Check this multiply against other multiplies being added together.
1256 for (unsigned OtherMulIdx = Idx+1;
1257 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1258 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001259 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001260 // If MulOp occurs in OtherMul, we can fold the two multiplies
1261 // together.
1262 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1263 OMulOp != e; ++OMulOp)
1264 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1265 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1266 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1267 if (Mul->getNumOperands() != 2) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001268 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001269 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001270 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001271 }
1272 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1273 if (OtherMul->getNumOperands() != 2) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001274 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001275 OtherMul->op_end());
1276 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001277 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001278 }
Dan Gohman246b2562007-10-22 18:31:58 +00001279 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1280 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001281 if (Ops.size() == 2) return OuterMul;
1282 Ops.erase(Ops.begin()+Idx);
1283 Ops.erase(Ops.begin()+OtherMulIdx-1);
1284 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001285 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001286 }
1287 }
1288 }
1289 }
1290
1291 // If there are any add recurrences in the operands list, see if any other
1292 // added values are loop invariant. If so, we can fold them into the
1293 // recurrence.
1294 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1295 ++Idx;
1296
1297 // Scan over all recurrences, trying to fold loop invariants into them.
1298 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1299 // Scan all of the other operands to this add and add them to the vector if
1300 // they are loop invariant w.r.t. the recurrence.
Dan Gohmana82752c2009-06-14 22:47:23 +00001301 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001302 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1304 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1305 LIOps.push_back(Ops[i]);
1306 Ops.erase(Ops.begin()+i);
1307 --i; --e;
1308 }
1309
1310 // If we found some loop invariants, fold them into the recurrence.
1311 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001312 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001313 LIOps.push_back(AddRec->getStart());
1314
Dan Gohmana82752c2009-06-14 22:47:23 +00001315 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1316 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001317 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001318
Dan Gohman246b2562007-10-22 18:31:58 +00001319 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001320 // If all of the other operands were loop invariant, we are done.
1321 if (Ops.size() == 1) return NewRec;
1322
1323 // Otherwise, add the folded AddRec by the non-liv parts.
1324 for (unsigned i = 0;; ++i)
1325 if (Ops[i] == AddRec) {
1326 Ops[i] = NewRec;
1327 break;
1328 }
Dan Gohman246b2562007-10-22 18:31:58 +00001329 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 }
1331
1332 // Okay, if there weren't any loop invariants to be folded, check to see if
1333 // there are multiple AddRec's with the same loop induction variable being
1334 // added together. If so, we can fold them.
1335 for (unsigned OtherIdx = Idx+1;
1336 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1337 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001338 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001339 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1340 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohmana82752c2009-06-14 22:47:23 +00001341 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001342 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1343 if (i >= NewOps.size()) {
1344 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1345 OtherAddRec->op_end());
1346 break;
1347 }
Dan Gohman246b2562007-10-22 18:31:58 +00001348 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001349 }
Dan Gohman246b2562007-10-22 18:31:58 +00001350 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001351
1352 if (Ops.size() == 2) return NewAddRec;
1353
1354 Ops.erase(Ops.begin()+Idx);
1355 Ops.erase(Ops.begin()+OtherIdx-1);
1356 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001357 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001358 }
1359 }
1360
1361 // Otherwise couldn't fold anything into this recurrence. Move onto the
1362 // next one.
1363 }
1364
1365 // Okay, it looks like we really DO need an add expr. Check to see if we
1366 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001367 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001368 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
Chris Lattnerb3364092006-10-04 21:49:37 +00001369 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001370 if (Result == 0) Result = new SCEVAddExpr(Ops, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001371 return Result;
1372}
1373
1374
Dan Gohman6c0866c2009-05-24 23:45:28 +00001375/// getMulExpr - Get a canonical multiply expression, or something simpler if
1376/// possible.
Dan Gohmana82752c2009-06-14 22:47:23 +00001377SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001378 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001379#ifndef NDEBUG
1380 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1381 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1382 getEffectiveSCEVType(Ops[0]->getType()) &&
1383 "SCEVMulExpr operand types don't match!");
1384#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001385
1386 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001387 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001388
1389 // If there are any constants, fold them together.
1390 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001391 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001392
1393 // C1*(C2+V) -> C1*C2 + C1*V
1394 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001395 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 if (Add->getNumOperands() == 2 &&
1397 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001398 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1399 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001400
1401
1402 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001403 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001405 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1406 RHSC->getValue()->getValue());
1407 Ops[0] = getConstant(Fold);
1408 Ops.erase(Ops.begin()+1); // Erase the folded element
1409 if (Ops.size() == 1) return Ops[0];
1410 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001411 }
1412
1413 // If we are left with a constant one being multiplied, strip it off.
1414 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1415 Ops.erase(Ops.begin());
1416 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001417 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001418 // If we have a multiply of zero, it will always be zero.
1419 return Ops[0];
1420 }
1421 }
1422
1423 // Skip over the add expression until we get to a multiply.
1424 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1425 ++Idx;
1426
1427 if (Ops.size() == 1)
1428 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001429
Chris Lattner53e677a2004-04-02 20:23:17 +00001430 // If there are mul operands inline them all into this expression.
1431 if (Idx < Ops.size()) {
1432 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001433 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001434 // If we have an mul, expand the mul operands onto the end of the operands
1435 // list.
1436 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1437 Ops.erase(Ops.begin()+Idx);
1438 DeletedMul = true;
1439 }
1440
1441 // If we deleted at least one mul, we added operands to the end of the list,
1442 // and they are not necessarily sorted. Recurse to resort and resimplify
1443 // any operands we just aquired.
1444 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001445 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001446 }
1447
1448 // If there are any add recurrences in the operands list, see if any other
1449 // added values are loop invariant. If so, we can fold them into the
1450 // recurrence.
1451 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1452 ++Idx;
1453
1454 // Scan over all recurrences, trying to fold loop invariants into them.
1455 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1456 // Scan all of the other operands to this mul and add them to the vector if
1457 // they are loop invariant w.r.t. the recurrence.
Dan Gohmana82752c2009-06-14 22:47:23 +00001458 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001459 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1461 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1462 LIOps.push_back(Ops[i]);
1463 Ops.erase(Ops.begin()+i);
1464 --i; --e;
1465 }
1466
1467 // If we found some loop invariants, fold them into the recurrence.
1468 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001469 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmana82752c2009-06-14 22:47:23 +00001470 SmallVector<SCEVHandle, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001471 NewOps.reserve(AddRec->getNumOperands());
1472 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001473 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001475 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 } else {
1477 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001478 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001479 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001480 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001481 }
1482 }
1483
Dan Gohman246b2562007-10-22 18:31:58 +00001484 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001485
1486 // If all of the other operands were loop invariant, we are done.
1487 if (Ops.size() == 1) return NewRec;
1488
1489 // Otherwise, multiply the folded AddRec by the non-liv parts.
1490 for (unsigned i = 0;; ++i)
1491 if (Ops[i] == AddRec) {
1492 Ops[i] = NewRec;
1493 break;
1494 }
Dan Gohman246b2562007-10-22 18:31:58 +00001495 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 }
1497
1498 // Okay, if there weren't any loop invariants to be folded, check to see if
1499 // there are multiple AddRec's with the same loop induction variable being
1500 // multiplied together. If so, we can fold them.
1501 for (unsigned OtherIdx = Idx+1;
1502 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1503 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001504 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001505 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1506 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001507 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001508 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001509 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001510 SCEVHandle B = F->getStepRecurrence(*this);
1511 SCEVHandle D = G->getStepRecurrence(*this);
1512 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1513 getMulExpr(G, B),
1514 getMulExpr(B, D));
1515 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1516 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001517 if (Ops.size() == 2) return NewAddRec;
1518
1519 Ops.erase(Ops.begin()+Idx);
1520 Ops.erase(Ops.begin()+OtherIdx-1);
1521 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001522 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001523 }
1524 }
1525
1526 // Otherwise couldn't fold anything into this recurrence. Move onto the
1527 // next one.
1528 }
1529
1530 // Okay, it looks like we really DO need an mul expr. Check to see if we
1531 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001532 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001533 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
Chris Lattnerb3364092006-10-04 21:49:37 +00001534 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001535 if (Result == 0)
Owen Anderson4a7893b2009-06-18 22:25:12 +00001536 Result = new SCEVMulExpr(Ops, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 return Result;
1538}
1539
Dan Gohman6c0866c2009-05-24 23:45:28 +00001540/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1541/// possible.
Dan Gohmanbf2176a2009-05-04 22:23:18 +00001542SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1543 const SCEVHandle &RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001544 assert(getEffectiveSCEVType(LHS->getType()) ==
1545 getEffectiveSCEVType(RHS->getType()) &&
1546 "SCEVUDivExpr operand types don't match!");
1547
Dan Gohman622ed672009-05-04 22:02:23 +00001548 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001549 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001550 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001551 if (RHSC->isZero())
1552 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001553
Dan Gohman185cf032009-05-08 20:18:49 +00001554 // Determine if the division can be folded into the operands of
1555 // its operands.
1556 // TODO: Generalize this to non-constants by using known-bits information.
1557 const Type *Ty = LHS->getType();
1558 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1559 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1560 // For non-power-of-two values, effectively round the value up to the
1561 // nearest power of two.
1562 if (!RHSC->getValue()->getValue().isPowerOf2())
1563 ++MaxShiftAmt;
1564 const IntegerType *ExtTy =
1565 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1566 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1567 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1568 if (const SCEVConstant *Step =
1569 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1570 if (!Step->getValue()->getValue()
1571 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001572 getZeroExtendExpr(AR, ExtTy) ==
1573 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1574 getZeroExtendExpr(Step, ExtTy),
1575 AR->getLoop())) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001576 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001577 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1578 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1579 return getAddRecExpr(Operands, AR->getLoop());
1580 }
1581 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001582 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001583 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001584 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1585 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1586 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001587 // Find an operand that's safely divisible.
1588 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1589 SCEVHandle Op = M->getOperand(i);
1590 SCEVHandle Div = getUDivExpr(Op, RHSC);
1591 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001592 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1593 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1594 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001595 Operands[i] = Div;
1596 return getMulExpr(Operands);
1597 }
1598 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001599 }
Dan Gohman185cf032009-05-08 20:18:49 +00001600 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001601 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001602 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001603 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1604 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1605 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1606 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001607 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1608 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1609 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1610 break;
1611 Operands.push_back(Op);
1612 }
1613 if (Operands.size() == A->getNumOperands())
1614 return getAddExpr(Operands);
1615 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001616 }
Dan Gohman185cf032009-05-08 20:18:49 +00001617
1618 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001619 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 Constant *LHSCV = LHSC->getValue();
1621 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001622 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001623 }
1624 }
1625
Owen Anderson08367b62009-06-22 18:25:46 +00001626 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001627 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001628 return Result;
1629}
1630
1631
Dan Gohman6c0866c2009-05-24 23:45:28 +00001632/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1633/// Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001634SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001635 const SCEVHandle &Step, const Loop *L) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001636 SmallVector<SCEVHandle, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001637 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001638 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001639 if (StepChrec->getLoop() == L) {
1640 Operands.insert(Operands.end(), StepChrec->op_begin(),
1641 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001642 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001643 }
1644
1645 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001646 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001647}
1648
Dan Gohman6c0866c2009-05-24 23:45:28 +00001649/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1650/// Simplify the expression as much as possible.
Dan Gohmana82752c2009-06-14 22:47:23 +00001651SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001652 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001654#ifndef NDEBUG
1655 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1656 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1657 getEffectiveSCEVType(Operands[0]->getType()) &&
1658 "SCEVAddRecExpr operand types don't match!");
1659#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001660
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001661 if (Operands.back()->isZero()) {
1662 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001663 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001664 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001665
Dan Gohmand9cc7492008-08-08 18:33:12 +00001666 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001667 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001668 const Loop* NestedLoop = NestedAR->getLoop();
1669 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001670 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1671 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001672 SCEVHandle NestedARHandle(NestedAR);
1673 Operands[0] = NestedAR->getStart();
1674 NestedOperands[0] = getAddRecExpr(Operands, L);
1675 return getAddRecExpr(NestedOperands, NestedLoop);
1676 }
1677 }
1678
Dan Gohman35738ac2009-05-04 22:30:44 +00001679 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001680 SCEVAddRecExpr *&Result = SCEVAddRecExprs[std::make_pair(L, SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001681 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 return Result;
1683}
1684
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001685SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1686 const SCEVHandle &RHS) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001687 SmallVector<SCEVHandle, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001688 Ops.push_back(LHS);
1689 Ops.push_back(RHS);
1690 return getSMaxExpr(Ops);
1691}
1692
Dan Gohmana82752c2009-06-14 22:47:23 +00001693SCEVHandle
1694ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001695 assert(!Ops.empty() && "Cannot get empty smax!");
1696 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001697#ifndef NDEBUG
1698 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1699 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1700 getEffectiveSCEVType(Ops[0]->getType()) &&
1701 "SCEVSMaxExpr operand types don't match!");
1702#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001703
1704 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001705 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001706
1707 // If there are any constants, fold them together.
1708 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001709 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001710 ++Idx;
1711 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001712 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001713 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001714 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001715 APIntOps::smax(LHSC->getValue()->getValue(),
1716 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001717 Ops[0] = getConstant(Fold);
1718 Ops.erase(Ops.begin()+1); // Erase the folded element
1719 if (Ops.size() == 1) return Ops[0];
1720 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001721 }
1722
1723 // If we are left with a constant -inf, strip it off.
1724 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1725 Ops.erase(Ops.begin());
1726 --Idx;
1727 }
1728 }
1729
1730 if (Ops.size() == 1) return Ops[0];
1731
1732 // Find the first SMax
1733 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1734 ++Idx;
1735
1736 // Check to see if one of the operands is an SMax. If so, expand its operands
1737 // onto our operand list, and recurse to simplify.
1738 if (Idx < Ops.size()) {
1739 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001740 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001741 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1742 Ops.erase(Ops.begin()+Idx);
1743 DeletedSMax = true;
1744 }
1745
1746 if (DeletedSMax)
1747 return getSMaxExpr(Ops);
1748 }
1749
1750 // Okay, check to see if the same value occurs in the operand list twice. If
1751 // so, delete one. Since we sorted the list, these values are required to
1752 // be adjacent.
1753 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1754 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1755 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1756 --i; --e;
1757 }
1758
1759 if (Ops.size() == 1) return Ops[0];
1760
1761 assert(!Ops.empty() && "Reduced smax down to nothing!");
1762
Nick Lewycky3e630762008-02-20 06:48:22 +00001763 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001764 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001765 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001766 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scSMaxExpr,
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001767 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001768 if (Result == 0) Result = new SCEVSMaxExpr(Ops, this);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001769 return Result;
1770}
1771
Nick Lewycky3e630762008-02-20 06:48:22 +00001772SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1773 const SCEVHandle &RHS) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001774 SmallVector<SCEVHandle, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001775 Ops.push_back(LHS);
1776 Ops.push_back(RHS);
1777 return getUMaxExpr(Ops);
1778}
1779
Dan Gohmana82752c2009-06-14 22:47:23 +00001780SCEVHandle
1781ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001782 assert(!Ops.empty() && "Cannot get empty umax!");
1783 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001784#ifndef NDEBUG
1785 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1786 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1787 getEffectiveSCEVType(Ops[0]->getType()) &&
1788 "SCEVUMaxExpr operand types don't match!");
1789#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001790
1791 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001792 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001793
1794 // If there are any constants, fold them together.
1795 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001796 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001797 ++Idx;
1798 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001799 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001800 // We found two constants, fold them together!
1801 ConstantInt *Fold = ConstantInt::get(
1802 APIntOps::umax(LHSC->getValue()->getValue(),
1803 RHSC->getValue()->getValue()));
1804 Ops[0] = getConstant(Fold);
1805 Ops.erase(Ops.begin()+1); // Erase the folded element
1806 if (Ops.size() == 1) return Ops[0];
1807 LHSC = cast<SCEVConstant>(Ops[0]);
1808 }
1809
1810 // If we are left with a constant zero, strip it off.
1811 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1812 Ops.erase(Ops.begin());
1813 --Idx;
1814 }
1815 }
1816
1817 if (Ops.size() == 1) return Ops[0];
1818
1819 // Find the first UMax
1820 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1821 ++Idx;
1822
1823 // Check to see if one of the operands is a UMax. If so, expand its operands
1824 // onto our operand list, and recurse to simplify.
1825 if (Idx < Ops.size()) {
1826 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001827 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001828 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1829 Ops.erase(Ops.begin()+Idx);
1830 DeletedUMax = true;
1831 }
1832
1833 if (DeletedUMax)
1834 return getUMaxExpr(Ops);
1835 }
1836
1837 // Okay, check to see if the same value occurs in the operand list twice. If
1838 // so, delete one. Since we sorted the list, these values are required to
1839 // be adjacent.
1840 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1841 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1842 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1843 --i; --e;
1844 }
1845
1846 if (Ops.size() == 1) return Ops[0];
1847
1848 assert(!Ops.empty() && "Reduced umax down to nothing!");
1849
1850 // Okay, it looks like we really DO need a umax expr. Check to see if we
1851 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001852 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001853 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scUMaxExpr,
Nick Lewycky3e630762008-02-20 06:48:22 +00001854 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001855 if (Result == 0) Result = new SCEVUMaxExpr(Ops, this);
Nick Lewycky3e630762008-02-20 06:48:22 +00001856 return Result;
1857}
1858
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001859SCEVHandle ScalarEvolution::getSMinExpr(const SCEVHandle &LHS,
1860 const SCEVHandle &RHS) {
1861 // ~smax(~x, ~y) == smin(x, y).
1862 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1863}
1864
1865SCEVHandle ScalarEvolution::getUMinExpr(const SCEVHandle &LHS,
1866 const SCEVHandle &RHS) {
1867 // ~umax(~x, ~y) == umin(x, y)
1868 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1869}
1870
Dan Gohman246b2562007-10-22 18:31:58 +00001871SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001872 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001873 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001874 if (isa<ConstantPointerNull>(V))
1875 return getIntegerSCEV(0, V->getType());
Owen Anderson08367b62009-06-22 18:25:46 +00001876 SCEVUnknown *&Result = SCEVUnknowns[V];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001877 if (Result == 0) Result = new SCEVUnknown(V, this);
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001878 return Result;
1879}
1880
Chris Lattner53e677a2004-04-02 20:23:17 +00001881//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001882// Basic SCEV Analysis and PHI Idiom Recognition Code
1883//
1884
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001885/// isSCEVable - Test if values of the given type are analyzable within
1886/// the SCEV framework. This primarily includes integer types, and it
1887/// can optionally include pointer types if the ScalarEvolution class
1888/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001889bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001890 // Integers are always SCEVable.
1891 if (Ty->isInteger())
1892 return true;
1893
1894 // Pointers are SCEVable if TargetData information is available
1895 // to provide pointer size information.
1896 if (isa<PointerType>(Ty))
1897 return TD != NULL;
1898
1899 // Otherwise it's not SCEVable.
1900 return false;
1901}
1902
1903/// getTypeSizeInBits - Return the size in bits of the specified type,
1904/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001905uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001906 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1907
1908 // If we have a TargetData, use it!
1909 if (TD)
1910 return TD->getTypeSizeInBits(Ty);
1911
1912 // Otherwise, we support only integer types.
1913 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1914 return Ty->getPrimitiveSizeInBits();
1915}
1916
1917/// getEffectiveSCEVType - Return a type with the same bitwidth as
1918/// the given type and which represents how SCEV will treat the given
1919/// type, for which isSCEVable must return true. For pointer types,
1920/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001921const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001922 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1923
1924 if (Ty->isInteger())
1925 return Ty;
1926
1927 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1928 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001929}
Chris Lattner53e677a2004-04-02 20:23:17 +00001930
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001931SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00001932 return CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001933}
1934
Dan Gohman92fa56e2009-05-04 22:20:30 +00001935/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00001936/// computed.
1937bool ScalarEvolution::hasSCEV(Value *V) const {
1938 return Scalars.count(V);
1939}
1940
Chris Lattner53e677a2004-04-02 20:23:17 +00001941/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1942/// expression and create a new one.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001943SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001944 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001945
Dan Gohman35738ac2009-05-04 22:30:44 +00001946 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001947 if (I != Scalars.end()) return I->second;
1948 SCEVHandle S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00001949 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00001950 return S;
1951}
1952
Dan Gohman2d1be872009-04-16 03:18:22 +00001953/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1954/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001955SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1956 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001957 Constant *C;
1958 if (Val == 0)
1959 C = Constant::getNullValue(Ty);
1960 else if (Ty->isFloatingPoint())
1961 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1962 APFloat::IEEEdouble, Val));
1963 else
1964 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001965 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001966}
1967
1968/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1969///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001970SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001971 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001972 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001973
1974 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001975 Ty = getEffectiveSCEVType(Ty);
1976 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001977}
1978
1979/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001980SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001981 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001982 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001983
1984 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001985 Ty = getEffectiveSCEVType(Ty);
1986 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001987 return getMinusSCEV(AllOnes, V);
1988}
1989
1990/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1991///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001992SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001993 const SCEVHandle &RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001994 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001995 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001996}
1997
1998/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1999/// input value to the specified type. If the type must be extended, it is zero
2000/// extended.
2001SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002002ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002003 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002004 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002005 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2006 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002007 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002008 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002009 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002010 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002011 return getTruncateExpr(V, Ty);
2012 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002013}
2014
2015/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2016/// input value to the specified type. If the type must be extended, it is sign
2017/// extended.
2018SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002019ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002020 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002021 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002022 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2023 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002024 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002025 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002026 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002027 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002028 return getTruncateExpr(V, Ty);
2029 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002030}
2031
Dan Gohman467c4302009-05-13 03:46:30 +00002032/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2033/// input value to the specified type. If the type must be extended, it is zero
2034/// extended. The conversion must not be narrowing.
2035SCEVHandle
2036ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
2037 const Type *SrcTy = V->getType();
2038 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2039 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2040 "Cannot noop or zero extend with non-integer arguments!");
2041 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2042 "getNoopOrZeroExtend cannot truncate!");
2043 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2044 return V; // No conversion
2045 return getZeroExtendExpr(V, Ty);
2046}
2047
2048/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2049/// input value to the specified type. If the type must be extended, it is sign
2050/// extended. The conversion must not be narrowing.
2051SCEVHandle
2052ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
2053 const Type *SrcTy = V->getType();
2054 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2055 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2056 "Cannot noop or sign extend with non-integer arguments!");
2057 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2058 "getNoopOrSignExtend cannot truncate!");
2059 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2060 return V; // No conversion
2061 return getSignExtendExpr(V, Ty);
2062}
2063
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002064/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2065/// the input value to the specified type. If the type must be extended,
2066/// it is extended with unspecified bits. The conversion must not be
2067/// narrowing.
2068SCEVHandle
2069ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
2070 const Type *SrcTy = V->getType();
2071 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2072 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2073 "Cannot noop or any extend with non-integer arguments!");
2074 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2075 "getNoopOrAnyExtend cannot truncate!");
2076 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2077 return V; // No conversion
2078 return getAnyExtendExpr(V, Ty);
2079}
2080
Dan Gohman467c4302009-05-13 03:46:30 +00002081/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2082/// input value to the specified type. The conversion must not be widening.
2083SCEVHandle
2084ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
2085 const Type *SrcTy = V->getType();
2086 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2087 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2088 "Cannot truncate or noop with non-integer arguments!");
2089 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2090 "getTruncateOrNoop cannot extend!");
2091 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2092 return V; // No conversion
2093 return getTruncateExpr(V, Ty);
2094}
2095
Dan Gohmana334aa72009-06-22 00:31:57 +00002096/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2097/// the types using zero-extension, and then perform a umax operation
2098/// with them.
2099SCEVHandle ScalarEvolution::getUMaxFromMismatchedTypes(const SCEVHandle &LHS,
2100 const SCEVHandle &RHS) {
2101 SCEVHandle PromotedLHS = LHS;
2102 SCEVHandle PromotedRHS = RHS;
2103
2104 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2105 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2106 else
2107 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2108
2109 return getUMaxExpr(PromotedLHS, PromotedRHS);
2110}
2111
Dan Gohmanc9759e82009-06-22 15:03:27 +00002112/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2113/// the types using zero-extension, and then perform a umin operation
2114/// with them.
2115SCEVHandle ScalarEvolution::getUMinFromMismatchedTypes(const SCEVHandle &LHS,
2116 const SCEVHandle &RHS) {
2117 SCEVHandle PromotedLHS = LHS;
2118 SCEVHandle PromotedRHS = RHS;
2119
2120 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2121 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2122 else
2123 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2124
2125 return getUMinExpr(PromotedLHS, PromotedRHS);
2126}
2127
Chris Lattner4dc534c2005-02-13 04:37:18 +00002128/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2129/// the specified instruction and replaces any references to the symbolic value
2130/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002131void ScalarEvolution::
Chris Lattner4dc534c2005-02-13 04:37:18 +00002132ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
2133 const SCEVHandle &NewVal) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002134 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2135 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002136 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002137
Chris Lattner4dc534c2005-02-13 04:37:18 +00002138 SCEVHandle NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002139 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002140 if (NV == SI->second) return; // No change.
2141
2142 SI->second = NV; // Update the scalars map!
2143
2144 // Any instruction values that use this instruction might also need to be
2145 // updated!
2146 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2147 UI != E; ++UI)
2148 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2149}
Chris Lattner53e677a2004-04-02 20:23:17 +00002150
2151/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2152/// a loop header, making it a potential recurrence, or it doesn't.
2153///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002154SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002155 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002156 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002157 if (L->getHeader() == PN->getParent()) {
2158 // If it lives in the loop header, it has two incoming values, one
2159 // from outside the loop, and one from inside.
2160 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2161 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002162
Chris Lattner53e677a2004-04-02 20:23:17 +00002163 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002164 SCEVHandle SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002165 assert(Scalars.find(PN) == Scalars.end() &&
2166 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002167 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002168
2169 // Using this symbolic name for the PHI, analyze the value coming around
2170 // the back-edge.
2171 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2172
2173 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2174 // has a special value for the first iteration of the loop.
2175
2176 // If the value coming around the backedge is an add with the symbolic
2177 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002178 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002179 // If there is a single occurrence of the symbolic value, replace it
2180 // with a recurrence.
2181 unsigned FoundIndex = Add->getNumOperands();
2182 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2183 if (Add->getOperand(i) == SymbolicName)
2184 if (FoundIndex == e) {
2185 FoundIndex = i;
2186 break;
2187 }
2188
2189 if (FoundIndex != Add->getNumOperands()) {
2190 // Create an add with everything but the specified operand.
Dan Gohmana82752c2009-06-14 22:47:23 +00002191 SmallVector<SCEVHandle, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002192 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2193 if (i != FoundIndex)
2194 Ops.push_back(Add->getOperand(i));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002195 SCEVHandle Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002196
2197 // This is not a valid addrec if the step amount is varying each
2198 // loop iteration, but is not itself an addrec in this loop.
2199 if (Accum->isLoopInvariant(L) ||
2200 (isa<SCEVAddRecExpr>(Accum) &&
2201 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2202 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002203 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002204
2205 // Okay, for the entire analysis of this edge we assumed the PHI
2206 // to be symbolic. We now need to go back and update all of the
2207 // entries for the scalars that use the PHI (except for the PHI
2208 // itself) to use the new analyzed value instead of the "symbolic"
2209 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002210 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002211 return PHISCEV;
2212 }
2213 }
Dan Gohman622ed672009-05-04 22:02:23 +00002214 } else if (const SCEVAddRecExpr *AddRec =
2215 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002216 // Otherwise, this could be a loop like this:
2217 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2218 // In this case, j = {1,+,1} and BEValue is j.
2219 // Because the other in-value of i (0) fits the evolution of BEValue
2220 // i really is an addrec evolution.
2221 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2222 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2223
2224 // If StartVal = j.start - j.stride, we can use StartVal as the
2225 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002226 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002227 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00002228 SCEVHandle PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002229 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002230
2231 // Okay, for the entire analysis of this edge we assumed the PHI
2232 // to be symbolic. We now need to go back and update all of the
2233 // entries for the scalars that use the PHI (except for the PHI
2234 // itself) to use the new analyzed value instead of the "symbolic"
2235 // value.
2236 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2237 return PHISCEV;
2238 }
2239 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002240 }
2241
2242 return SymbolicName;
2243 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002244
Chris Lattner53e677a2004-04-02 20:23:17 +00002245 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002246 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002247}
2248
Dan Gohman26466c02009-05-08 20:26:55 +00002249/// createNodeForGEP - Expand GEP instructions into add and multiply
2250/// operations. This allows them to be analyzed by regular SCEV code.
2251///
Dan Gohmanfb791602009-05-08 20:58:38 +00002252SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002253
2254 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002255 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002256 // Don't attempt to analyze GEPs over unsized objects.
2257 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2258 return getUnknown(GEP);
Dan Gohman26466c02009-05-08 20:26:55 +00002259 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002260 gep_type_iterator GTI = gep_type_begin(GEP);
2261 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2262 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002263 I != E; ++I) {
2264 Value *Index = *I;
2265 // Compute the (potentially symbolic) offset in bytes for this index.
2266 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2267 // For a struct, add the member offset.
2268 const StructLayout &SL = *TD->getStructLayout(STy);
2269 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2270 uint64_t Offset = SL.getElementOffset(FieldNo);
2271 TotalOffset = getAddExpr(TotalOffset,
2272 getIntegerSCEV(Offset, IntPtrTy));
2273 } else {
2274 // For an array, add the element offset, explicitly scaled.
2275 SCEVHandle LocalOffset = getSCEV(Index);
2276 if (!isa<PointerType>(LocalOffset->getType()))
2277 // Getelementptr indicies are signed.
2278 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2279 IntPtrTy);
2280 LocalOffset =
2281 getMulExpr(LocalOffset,
Duncan Sands777d2302009-05-09 07:06:46 +00002282 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman26466c02009-05-08 20:26:55 +00002283 IntPtrTy));
2284 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2285 }
2286 }
2287 return getAddExpr(getSCEV(Base), TotalOffset);
2288}
2289
Nick Lewycky83bb0052007-11-22 07:59:40 +00002290/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2291/// guaranteed to end in (at every loop iteration). It is, at the same time,
2292/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2293/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002294uint32_t
2295ScalarEvolution::GetMinTrailingZeros(const SCEVHandle &S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002296 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002297 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002298
Dan Gohman622ed672009-05-04 22:02:23 +00002299 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002300 return std::min(GetMinTrailingZeros(T->getOperand()),
2301 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002302
Dan Gohman622ed672009-05-04 22:02:23 +00002303 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002304 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2305 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2306 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002307 }
2308
Dan Gohman622ed672009-05-04 22:02:23 +00002309 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002310 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2311 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2312 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002313 }
2314
Dan Gohman622ed672009-05-04 22:02:23 +00002315 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002316 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002317 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002318 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002319 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002320 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002321 }
2322
Dan Gohman622ed672009-05-04 22:02:23 +00002323 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002324 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002325 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2326 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002327 for (unsigned i = 1, e = M->getNumOperands();
2328 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002329 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002330 BitWidth);
2331 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002332 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002333
Dan Gohman622ed672009-05-04 22:02:23 +00002334 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002335 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002336 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002337 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002338 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002339 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002340 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002341
Dan Gohman622ed672009-05-04 22:02:23 +00002342 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002343 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002344 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002345 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002346 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002347 return MinOpRes;
2348 }
2349
Dan Gohman622ed672009-05-04 22:02:23 +00002350 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002351 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002352 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002353 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002354 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002355 return MinOpRes;
2356 }
2357
Dan Gohman2c364ad2009-06-19 23:29:04 +00002358 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2359 // For a SCEVUnknown, ask ValueTracking.
2360 unsigned BitWidth = getTypeSizeInBits(U->getType());
2361 APInt Mask = APInt::getAllOnesValue(BitWidth);
2362 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2363 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2364 return Zeros.countTrailingOnes();
2365 }
2366
2367 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002368 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002369}
Chris Lattner53e677a2004-04-02 20:23:17 +00002370
Dan Gohman2c364ad2009-06-19 23:29:04 +00002371uint32_t
2372ScalarEvolution::GetMinLeadingZeros(const SCEVHandle &S) {
2373 // TODO: Handle other SCEV expression types here.
2374
2375 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2376 return C->getValue()->getValue().countLeadingZeros();
2377
2378 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2379 // A zero-extension cast adds zero bits.
2380 return GetMinLeadingZeros(C->getOperand()) +
2381 (getTypeSizeInBits(C->getType()) -
2382 getTypeSizeInBits(C->getOperand()->getType()));
2383 }
2384
2385 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2386 // For a SCEVUnknown, ask ValueTracking.
2387 unsigned BitWidth = getTypeSizeInBits(U->getType());
2388 APInt Mask = APInt::getAllOnesValue(BitWidth);
2389 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2390 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2391 return Zeros.countLeadingOnes();
2392 }
2393
2394 return 1;
2395}
2396
2397uint32_t
2398ScalarEvolution::GetMinSignBits(const SCEVHandle &S) {
2399 // TODO: Handle other SCEV expression types here.
2400
2401 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2402 const APInt &A = C->getValue()->getValue();
2403 return A.isNegative() ? A.countLeadingOnes() :
2404 A.countLeadingZeros();
2405 }
2406
2407 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2408 // A sign-extension cast adds sign bits.
2409 return GetMinSignBits(C->getOperand()) +
2410 (getTypeSizeInBits(C->getType()) -
2411 getTypeSizeInBits(C->getOperand()->getType()));
2412 }
2413
2414 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2415 // For a SCEVUnknown, ask ValueTracking.
2416 return ComputeNumSignBits(U->getValue(), TD);
2417 }
2418
2419 return 1;
2420}
2421
Chris Lattner53e677a2004-04-02 20:23:17 +00002422/// createSCEV - We know that there is no SCEV for the specified value.
2423/// Analyze the expression.
2424///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002425SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002426 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002427 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002428
Dan Gohman6c459a22008-06-22 19:56:46 +00002429 unsigned Opcode = Instruction::UserOp1;
2430 if (Instruction *I = dyn_cast<Instruction>(V))
2431 Opcode = I->getOpcode();
2432 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2433 Opcode = CE->getOpcode();
2434 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002435 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002436
Dan Gohman6c459a22008-06-22 19:56:46 +00002437 User *U = cast<User>(V);
2438 switch (Opcode) {
2439 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002440 return getAddExpr(getSCEV(U->getOperand(0)),
2441 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002442 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002443 return getMulExpr(getSCEV(U->getOperand(0)),
2444 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002445 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002446 return getUDivExpr(getSCEV(U->getOperand(0)),
2447 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002448 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002449 return getMinusSCEV(getSCEV(U->getOperand(0)),
2450 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002451 case Instruction::And:
2452 // For an expression like x&255 that merely masks off the high bits,
2453 // use zext(trunc(x)) as the SCEV expression.
2454 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002455 if (CI->isNullValue())
2456 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002457 if (CI->isAllOnesValue())
2458 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002459 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002460
2461 // Instcombine's ShrinkDemandedConstant may strip bits out of
2462 // constants, obscuring what would otherwise be a low-bits mask.
2463 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2464 // knew about to reconstruct a low-bits mask value.
2465 unsigned LZ = A.countLeadingZeros();
2466 unsigned BitWidth = A.getBitWidth();
2467 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2468 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2469 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2470
2471 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2472
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002473 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002474 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002475 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002476 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002477 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002478 }
2479 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002480
Dan Gohman6c459a22008-06-22 19:56:46 +00002481 case Instruction::Or:
2482 // If the RHS of the Or is a constant, we may have something like:
2483 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2484 // optimizations will transparently handle this case.
2485 //
2486 // In order for this transformation to be safe, the LHS must be of the
2487 // form X*(2^n) and the Or constant must be less than 2^n.
2488 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2489 SCEVHandle LHS = getSCEV(U->getOperand(0));
2490 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002491 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002492 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002493 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002494 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002495 break;
2496 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002497 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002498 // If the RHS of the xor is a signbit, then this is just an add.
2499 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002500 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002501 return getAddExpr(getSCEV(U->getOperand(0)),
2502 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002503
2504 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002505 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002506 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002507
2508 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2509 // This is a variant of the check for xor with -1, and it handles
2510 // the case where instcombine has trimmed non-demanded bits out
2511 // of an xor with -1.
2512 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2513 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2514 if (BO->getOpcode() == Instruction::And &&
2515 LCI->getValue() == CI->getValue())
2516 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002517 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002518 const Type *UTy = U->getType();
2519 SCEVHandle Z0 = Z->getOperand();
2520 const Type *Z0Ty = Z0->getType();
2521 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2522
2523 // If C is a low-bits mask, the zero extend is zerving to
2524 // mask off the high bits. Complement the operand and
2525 // re-apply the zext.
2526 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2527 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2528
2529 // If C is a single bit, it may be in the sign-bit position
2530 // before the zero-extend. In this case, represent the xor
2531 // using an add, which is equivalent, and re-apply the zext.
2532 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2533 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2534 Trunc.isSignBit())
2535 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2536 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002537 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002538 }
2539 break;
2540
2541 case Instruction::Shl:
2542 // Turn shift left of a constant amount into a multiply.
2543 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2544 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2545 Constant *X = ConstantInt::get(
2546 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002547 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002548 }
2549 break;
2550
Nick Lewycky01eaf802008-07-07 06:15:49 +00002551 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002552 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002553 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2554 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2555 Constant *X = ConstantInt::get(
2556 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002557 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002558 }
2559 break;
2560
Dan Gohman4ee29af2009-04-21 02:26:00 +00002561 case Instruction::AShr:
2562 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2563 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2564 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2565 if (L->getOpcode() == Instruction::Shl &&
2566 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002567 unsigned BitWidth = getTypeSizeInBits(U->getType());
2568 uint64_t Amt = BitWidth - CI->getZExtValue();
2569 if (Amt == BitWidth)
2570 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2571 if (Amt > BitWidth)
2572 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002573 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002574 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002575 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002576 U->getType());
2577 }
2578 break;
2579
Dan Gohman6c459a22008-06-22 19:56:46 +00002580 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002581 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002582
2583 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002584 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002585
2586 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002587 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002588
2589 case Instruction::BitCast:
2590 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002591 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002592 return getSCEV(U->getOperand(0));
2593 break;
2594
Dan Gohman2d1be872009-04-16 03:18:22 +00002595 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002596 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002597 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002598 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002599
2600 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002601 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002602 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2603 U->getType());
2604
Dan Gohman26466c02009-05-08 20:26:55 +00002605 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002606 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002607 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002608
Dan Gohman6c459a22008-06-22 19:56:46 +00002609 case Instruction::PHI:
2610 return createNodeForPHI(cast<PHINode>(U));
2611
2612 case Instruction::Select:
2613 // This could be a smax or umax that was lowered earlier.
2614 // Try to recover it.
2615 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2616 Value *LHS = ICI->getOperand(0);
2617 Value *RHS = ICI->getOperand(1);
2618 switch (ICI->getPredicate()) {
2619 case ICmpInst::ICMP_SLT:
2620 case ICmpInst::ICMP_SLE:
2621 std::swap(LHS, RHS);
2622 // fall through
2623 case ICmpInst::ICMP_SGT:
2624 case ICmpInst::ICMP_SGE:
2625 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002626 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002627 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002628 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002629 break;
2630 case ICmpInst::ICMP_ULT:
2631 case ICmpInst::ICMP_ULE:
2632 std::swap(LHS, RHS);
2633 // fall through
2634 case ICmpInst::ICMP_UGT:
2635 case ICmpInst::ICMP_UGE:
2636 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002637 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002638 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002639 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002640 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002641 case ICmpInst::ICMP_NE:
2642 // n != 0 ? n : 1 -> umax(n, 1)
2643 if (LHS == U->getOperand(1) &&
2644 isa<ConstantInt>(U->getOperand(2)) &&
2645 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2646 isa<ConstantInt>(RHS) &&
2647 cast<ConstantInt>(RHS)->isZero())
2648 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2649 break;
2650 case ICmpInst::ICMP_EQ:
2651 // n == 0 ? 1 : n -> umax(n, 1)
2652 if (LHS == U->getOperand(2) &&
2653 isa<ConstantInt>(U->getOperand(1)) &&
2654 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2655 isa<ConstantInt>(RHS) &&
2656 cast<ConstantInt>(RHS)->isZero())
2657 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2658 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002659 default:
2660 break;
2661 }
2662 }
2663
2664 default: // We cannot analyze this expression.
2665 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002666 }
2667
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002668 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002669}
2670
2671
2672
2673//===----------------------------------------------------------------------===//
2674// Iteration Count Computation Code
2675//
2676
Dan Gohman46bdfb02009-02-24 18:55:53 +00002677/// getBackedgeTakenCount - If the specified loop has a predictable
2678/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2679/// object. The backedge-taken count is the number of times the loop header
2680/// will be branched to from within the loop. This is one less than the
2681/// trip count of the loop, since it doesn't count the first iteration,
2682/// when the header is branched to from outside the loop.
2683///
2684/// Note that it is not valid to call this method on a loop without a
2685/// loop-invariant backedge-taken count (see
2686/// hasLoopInvariantBackedgeTakenCount).
2687///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002688SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002689 return getBackedgeTakenInfo(L).Exact;
2690}
2691
2692/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2693/// return the least SCEV value that is known never to be less than the
2694/// actual backedge taken count.
2695SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2696 return getBackedgeTakenInfo(L).Max;
2697}
2698
2699const ScalarEvolution::BackedgeTakenInfo &
2700ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002701 // Initially insert a CouldNotCompute for this loop. If the insertion
2702 // succeeds, procede to actually compute a backedge-taken count and
2703 // update the value. The temporary CouldNotCompute value tells SCEV
2704 // code elsewhere that it shouldn't attempt to request a new
2705 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002706 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002707 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2708 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002709 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002710 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002711 assert(ItCount.Exact->isLoopInvariant(L) &&
2712 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002713 "Computed trip count isn't loop invariant for loop!");
2714 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002715
Dan Gohman01ecca22009-04-27 20:16:15 +00002716 // Update the value in the map.
2717 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00002718 } else {
2719 if (ItCount.Max != CouldNotCompute)
2720 // Update the value in the map.
2721 Pair.first->second = ItCount;
2722 if (isa<PHINode>(L->getHeader()->begin()))
2723 // Only count loops that have phi nodes as not being computable.
2724 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00002725 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002726
2727 // Now that we know more about the trip count for this loop, forget any
2728 // existing SCEV values for PHI nodes in this loop since they are only
2729 // conservative estimates made without the benefit
2730 // of trip count information.
2731 if (ItCount.hasAnyInfo())
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002732 forgetLoopPHIs(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002733 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002734 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002735}
2736
Dan Gohman46bdfb02009-02-24 18:55:53 +00002737/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002738/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002739/// ScalarEvolution's ability to compute a trip count, or if the loop
2740/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002741void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002742 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002743 forgetLoopPHIs(L);
2744}
2745
2746/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2747/// PHI nodes in the given loop. This is used when the trip count of
2748/// the loop may have changed.
2749void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002750 BasicBlock *Header = L->getHeader();
2751
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002752 // Push all Loop-header PHIs onto the Worklist stack, except those
2753 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2754 // a PHI either means that it has an unrecognized structure, or it's
2755 // a PHI that's in the progress of being computed by createNodeForPHI.
2756 // In the former case, additional loop trip count information isn't
2757 // going to change anything. In the later case, createNodeForPHI will
2758 // perform the necessary updates on its own when it gets to that point.
Dan Gohman35738ac2009-05-04 22:30:44 +00002759 SmallVector<Instruction *, 16> Worklist;
2760 for (BasicBlock::iterator I = Header->begin();
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002761 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2762 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2763 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2764 Worklist.push_back(PN);
2765 }
Dan Gohman35738ac2009-05-04 22:30:44 +00002766
2767 while (!Worklist.empty()) {
2768 Instruction *I = Worklist.pop_back_val();
2769 if (Scalars.erase(I))
2770 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2771 UI != UE; ++UI)
2772 Worklist.push_back(cast<Instruction>(UI));
2773 }
Dan Gohman60f8a632009-02-17 20:49:49 +00002774}
2775
Dan Gohman46bdfb02009-02-24 18:55:53 +00002776/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2777/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002778ScalarEvolution::BackedgeTakenInfo
2779ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00002780 SmallVector<BasicBlock*, 8> ExitingBlocks;
2781 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00002782
Dan Gohmana334aa72009-06-22 00:31:57 +00002783 // Examine all exits and pick the most conservative values.
2784 SCEVHandle BECount = CouldNotCompute;
2785 SCEVHandle MaxBECount = CouldNotCompute;
2786 bool CouldNotComputeBECount = false;
2787 bool CouldNotComputeMaxBECount = false;
2788 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2789 BackedgeTakenInfo NewBTI =
2790 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00002791
Dan Gohmana334aa72009-06-22 00:31:57 +00002792 if (NewBTI.Exact == CouldNotCompute) {
2793 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00002794 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00002795 CouldNotComputeBECount = true;
2796 BECount = CouldNotCompute;
2797 } else if (!CouldNotComputeBECount) {
2798 if (BECount == CouldNotCompute)
2799 BECount = NewBTI.Exact;
2800 else {
2801 // TODO: More analysis could be done here. For example, a
2802 // loop with a short-circuiting && operator has an exact count
2803 // of the min of both sides.
2804 CouldNotComputeBECount = true;
2805 BECount = CouldNotCompute;
2806 }
2807 }
2808 if (NewBTI.Max == CouldNotCompute) {
2809 // We couldn't compute an maximum value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00002810 // we won't be able to compute an maximum value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00002811 CouldNotComputeMaxBECount = true;
2812 MaxBECount = CouldNotCompute;
2813 } else if (!CouldNotComputeMaxBECount) {
2814 if (MaxBECount == CouldNotCompute)
2815 MaxBECount = NewBTI.Max;
2816 else
2817 MaxBECount = getUMaxFromMismatchedTypes(MaxBECount, NewBTI.Max);
2818 }
2819 }
2820
2821 return BackedgeTakenInfo(BECount, MaxBECount);
2822}
2823
2824/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2825/// of the specified loop will execute if it exits via the specified block.
2826ScalarEvolution::BackedgeTakenInfo
2827ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2828 BasicBlock *ExitingBlock) {
2829
2830 // Okay, we've chosen an exiting block. See what condition causes us to
2831 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00002832 //
2833 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002834 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002835 if (ExitBr == 0) return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00002836 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002837
2838 // At this point, we know we have a conditional branch that determines whether
2839 // the loop is exited. However, we don't know if the branch is executed each
2840 // time through the loop. If not, then the execution count of the branch will
2841 // not be equal to the trip count of the loop.
2842 //
2843 // Currently we check for this by checking to see if the Exit branch goes to
2844 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002845 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00002846 // loop header. This is common for un-rotated loops.
2847 //
2848 // If both of those tests fail, walk up the unique predecessor chain to the
2849 // header, stopping if there is an edge that doesn't exit the loop. If the
2850 // header is reached, the execution count of the branch will be equal to the
2851 // trip count of the loop.
2852 //
2853 // More extensive analysis could be done to handle more cases here.
2854 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00002855 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002856 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00002857 ExitBr->getParent() != L->getHeader()) {
2858 // The simple checks failed, try climbing the unique predecessor chain
2859 // up to the header.
2860 bool Ok = false;
2861 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
2862 BasicBlock *Pred = BB->getUniquePredecessor();
2863 if (!Pred)
2864 return CouldNotCompute;
2865 TerminatorInst *PredTerm = Pred->getTerminator();
2866 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
2867 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
2868 if (PredSucc == BB)
2869 continue;
2870 // If the predecessor has a successor that isn't BB and isn't
2871 // outside the loop, assume the worst.
2872 if (L->contains(PredSucc))
2873 return CouldNotCompute;
2874 }
2875 if (Pred == L->getHeader()) {
2876 Ok = true;
2877 break;
2878 }
2879 BB = Pred;
2880 }
2881 if (!Ok)
2882 return CouldNotCompute;
2883 }
2884
2885 // Procede to the next level to examine the exit condition expression.
2886 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
2887 ExitBr->getSuccessor(0),
2888 ExitBr->getSuccessor(1));
2889}
2890
2891/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
2892/// backedge of the specified loop will execute if its exit condition
2893/// were a conditional branch of ExitCond, TBB, and FBB.
2894ScalarEvolution::BackedgeTakenInfo
2895ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
2896 Value *ExitCond,
2897 BasicBlock *TBB,
2898 BasicBlock *FBB) {
2899 // Check if the controlling expression for this loop is an and or or. In
2900 // such cases, an exact backedge-taken count may be infeasible, but a
2901 // maximum count may still be feasible.
2902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
2903 if (BO->getOpcode() == Instruction::And) {
2904 // Recurse on the operands of the and.
2905 BackedgeTakenInfo BTI0 =
2906 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2907 BackedgeTakenInfo BTI1 =
2908 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
2909 SCEVHandle BECount = CouldNotCompute;
2910 SCEVHandle MaxBECount = CouldNotCompute;
2911 if (L->contains(TBB)) {
2912 // Both conditions must be true for the loop to continue executing.
2913 // Choose the less conservative count.
Dan Gohman60e9b072009-06-22 15:09:28 +00002914 if (BTI0.Exact == CouldNotCompute)
2915 BECount = BTI1.Exact;
2916 else if (BTI1.Exact == CouldNotCompute)
Dan Gohmana334aa72009-06-22 00:31:57 +00002917 BECount = BTI0.Exact;
Dan Gohman60e9b072009-06-22 15:09:28 +00002918 else
2919 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00002920 if (BTI0.Max == CouldNotCompute)
2921 MaxBECount = BTI1.Max;
2922 else if (BTI1.Max == CouldNotCompute)
2923 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00002924 else
2925 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00002926 } else {
2927 // Both conditions must be true for the loop to exit.
2928 assert(L->contains(FBB) && "Loop block has no successor in loop!");
2929 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2930 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2931 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2932 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2933 }
2934
2935 return BackedgeTakenInfo(BECount, MaxBECount);
2936 }
2937 if (BO->getOpcode() == Instruction::Or) {
2938 // Recurse on the operands of the or.
2939 BackedgeTakenInfo BTI0 =
2940 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2941 BackedgeTakenInfo BTI1 =
2942 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
2943 SCEVHandle BECount = CouldNotCompute;
2944 SCEVHandle MaxBECount = CouldNotCompute;
2945 if (L->contains(FBB)) {
2946 // Both conditions must be false for the loop to continue executing.
2947 // Choose the less conservative count.
Dan Gohman60e9b072009-06-22 15:09:28 +00002948 if (BTI0.Exact == CouldNotCompute)
2949 BECount = BTI1.Exact;
2950 else if (BTI1.Exact == CouldNotCompute)
Dan Gohmana334aa72009-06-22 00:31:57 +00002951 BECount = BTI0.Exact;
Dan Gohman60e9b072009-06-22 15:09:28 +00002952 else
2953 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00002954 if (BTI0.Max == CouldNotCompute)
2955 MaxBECount = BTI1.Max;
2956 else if (BTI1.Max == CouldNotCompute)
2957 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00002958 else
2959 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00002960 } else {
2961 // Both conditions must be false for the loop to exit.
2962 assert(L->contains(TBB) && "Loop block has no successor in loop!");
2963 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2964 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2965 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2966 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2967 }
2968
2969 return BackedgeTakenInfo(BECount, MaxBECount);
2970 }
2971 }
2972
2973 // With an icmp, it may be feasible to compute an exact backedge-taken count.
2974 // Procede to the next level to examine the icmp.
2975 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
2976 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002977
Eli Friedman361e54d2009-05-09 12:32:42 +00002978 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00002979 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
2980}
2981
2982/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
2983/// backedge of the specified loop will execute if its exit condition
2984/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
2985ScalarEvolution::BackedgeTakenInfo
2986ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
2987 ICmpInst *ExitCond,
2988 BasicBlock *TBB,
2989 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002990
Reid Spencere4d87aa2006-12-23 06:05:41 +00002991 // If the condition was exit on true, convert the condition to exit on false
2992 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00002993 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00002994 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002995 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002996 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002997
2998 // Handle common loops like: for (X = "string"; *X; ++X)
2999 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3000 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
3001 SCEVHandle ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003002 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003003 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3004 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3005 return BackedgeTakenInfo(ItCnt,
3006 isa<SCEVConstant>(ItCnt) ? ItCnt :
3007 getConstant(APInt::getMaxValue(BitWidth)-1));
3008 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003009 }
3010
Chris Lattner53e677a2004-04-02 20:23:17 +00003011 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
3012 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
3013
3014 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003015 LHS = getSCEVAtScope(LHS, L);
3016 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003017
Reid Spencere4d87aa2006-12-23 06:05:41 +00003018 // At this point, we would like to compute how many iterations of the
3019 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003020 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3021 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003022 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003023 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003024 }
3025
Chris Lattner53e677a2004-04-02 20:23:17 +00003026 // If we have a comparison of a chrec against a constant, try to use value
3027 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003028 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3029 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003030 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003031 // Form the constant range.
3032 ConstantRange CompRange(
3033 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003034
Eli Friedman361e54d2009-05-09 12:32:42 +00003035 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
3036 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003037 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003038
Chris Lattner53e677a2004-04-02 20:23:17 +00003039 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003040 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003041 // Convert to: while (X-Y != 0)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003042 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003043 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003044 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003045 }
3046 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003047 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003048 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003049 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003050 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003051 }
3052 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003053 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3054 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003055 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003056 }
3057 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003058 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3059 getNotSCEV(RHS), L, true);
3060 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003061 break;
3062 }
3063 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003064 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3065 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003066 break;
3067 }
3068 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003069 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3070 getNotSCEV(RHS), L, false);
3071 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003072 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003073 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003074 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003075#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003076 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003077 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003078 errs() << "[unsigned] ";
3079 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00003080 << Instruction::getOpcodeName(Instruction::ICmp)
3081 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003082#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003083 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003084 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003085 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003086 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003087}
3088
Chris Lattner673e02b2004-10-12 01:49:27 +00003089static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003090EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3091 ScalarEvolution &SE) {
3092 SCEVHandle InVal = SE.getConstant(C);
3093 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003094 assert(isa<SCEVConstant>(Val) &&
3095 "Evaluation of SCEV at constant didn't fold correctly?");
3096 return cast<SCEVConstant>(Val)->getValue();
3097}
3098
3099/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3100/// and a GEP expression (missing the pointer index) indexing into it, return
3101/// the addressed element of the initializer or null if the index expression is
3102/// invalid.
3103static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003104GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003105 const std::vector<ConstantInt*> &Indices) {
3106 Constant *Init = GV->getInitializer();
3107 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003108 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003109 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3110 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3111 Init = cast<Constant>(CS->getOperand(Idx));
3112 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3113 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3114 Init = cast<Constant>(CA->getOperand(Idx));
3115 } else if (isa<ConstantAggregateZero>(Init)) {
3116 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3117 assert(Idx < STy->getNumElements() && "Bad struct index!");
3118 Init = Constant::getNullValue(STy->getElementType(Idx));
3119 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3120 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3121 Init = Constant::getNullValue(ATy->getElementType());
3122 } else {
3123 assert(0 && "Unknown constant aggregate type!");
3124 }
3125 return 0;
3126 } else {
3127 return 0; // Unknown initializer type
3128 }
3129 }
3130 return Init;
3131}
3132
Dan Gohman46bdfb02009-02-24 18:55:53 +00003133/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3134/// 'icmp op load X, cst', try to see if we can compute the backedge
3135/// execution count.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003136SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003137ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
3138 const Loop *L,
3139 ICmpInst::Predicate predicate) {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003140 if (LI->isVolatile()) return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003141
3142 // Check to see if the loaded pointer is a getelementptr of a global.
3143 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003144 if (!GEP) return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003145
3146 // Make sure that it is really a constant global we are gepping, with an
3147 // initializer, and make sure the first IDX is really 0.
3148 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3149 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3150 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3151 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003152 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003153
3154 // Okay, we allow one non-constant index into the GEP instruction.
3155 Value *VarIdx = 0;
3156 std::vector<ConstantInt*> Indexes;
3157 unsigned VarIdxNum = 0;
3158 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3159 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3160 Indexes.push_back(CI);
3161 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003162 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003163 VarIdx = GEP->getOperand(i);
3164 VarIdxNum = i-2;
3165 Indexes.push_back(0);
3166 }
3167
3168 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3169 // Check to see if X is a loop variant variable value now.
3170 SCEVHandle Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003171 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003172
3173 // We can only recognize very limited forms of loop index expressions, in
3174 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003175 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003176 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3177 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3178 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003179 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003180
3181 unsigned MaxSteps = MaxBruteForceIterations;
3182 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003183 ConstantInt *ItCst =
Dan Gohman6de29f82009-06-15 22:12:54 +00003184 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003185 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003186
3187 // Form the GEP offset.
3188 Indexes[VarIdxNum] = Val;
3189
3190 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3191 if (Result == 0) break; // Cannot compute!
3192
3193 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003194 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003195 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003196 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003197#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003198 errs() << "\n***\n*** Computed loop count " << *ItCst
3199 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3200 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003201#endif
3202 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003203 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003204 }
3205 }
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003206 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003207}
3208
3209
Chris Lattner3221ad02004-04-17 22:58:41 +00003210/// CanConstantFold - Return true if we can constant fold an instruction of the
3211/// specified type, assuming that all operands were constants.
3212static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003213 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003214 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3215 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003216
Chris Lattner3221ad02004-04-17 22:58:41 +00003217 if (const CallInst *CI = dyn_cast<CallInst>(I))
3218 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003219 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003220 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003221}
3222
Chris Lattner3221ad02004-04-17 22:58:41 +00003223/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3224/// in the loop that V is derived from. We allow arbitrary operations along the
3225/// way, but the operands of an operation must either be constants or a value
3226/// derived from a constant PHI. If this expression does not fit with these
3227/// constraints, return null.
3228static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3229 // If this is not an instruction, or if this is an instruction outside of the
3230 // loop, it can't be derived from a loop PHI.
3231 Instruction *I = dyn_cast<Instruction>(V);
3232 if (I == 0 || !L->contains(I->getParent())) return 0;
3233
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003234 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003235 if (L->getHeader() == I->getParent())
3236 return PN;
3237 else
3238 // We don't currently keep track of the control flow needed to evaluate
3239 // PHIs, so we cannot handle PHIs inside of loops.
3240 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003241 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003242
3243 // If we won't be able to constant fold this expression even if the operands
3244 // are constants, return early.
3245 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003246
Chris Lattner3221ad02004-04-17 22:58:41 +00003247 // Otherwise, we can evaluate this instruction if all of its operands are
3248 // constant or derived from a PHI node themselves.
3249 PHINode *PHI = 0;
3250 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3251 if (!(isa<Constant>(I->getOperand(Op)) ||
3252 isa<GlobalValue>(I->getOperand(Op)))) {
3253 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3254 if (P == 0) return 0; // Not evolving from PHI
3255 if (PHI == 0)
3256 PHI = P;
3257 else if (PHI != P)
3258 return 0; // Evolving from multiple different PHIs.
3259 }
3260
3261 // This is a expression evolving from a constant PHI!
3262 return PHI;
3263}
3264
3265/// EvaluateExpression - Given an expression that passes the
3266/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3267/// in the loop has the value PHIVal. If we can't fold this expression for some
3268/// reason, return null.
3269static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3270 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003271 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003272 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003273 Instruction *I = cast<Instruction>(V);
3274
3275 std::vector<Constant*> Operands;
3276 Operands.resize(I->getNumOperands());
3277
3278 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3279 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3280 if (Operands[i] == 0) return 0;
3281 }
3282
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003283 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3284 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3285 &Operands[0], Operands.size());
3286 else
3287 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3288 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00003289}
3290
3291/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3292/// in the header of its containing loop, we know the loop executes a
3293/// constant number of times, and the PHI node is just a recurrence
3294/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003295Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003296getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00003297 std::map<PHINode*, Constant*>::iterator I =
3298 ConstantEvolutionLoopExitValue.find(PN);
3299 if (I != ConstantEvolutionLoopExitValue.end())
3300 return I->second;
3301
Dan Gohman46bdfb02009-02-24 18:55:53 +00003302 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003303 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3304
3305 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3306
3307 // Since the loop is canonicalized, the PHI node must have two entries. One
3308 // entry must be a constant (coming in from outside of the loop), and the
3309 // second must be derived from the same PHI.
3310 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3311 Constant *StartCST =
3312 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3313 if (StartCST == 0)
3314 return RetVal = 0; // Must be a constant.
3315
3316 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3317 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3318 if (PN2 != PN)
3319 return RetVal = 0; // Not derived from same PHI.
3320
3321 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003322 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003323 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003324
Dan Gohman46bdfb02009-02-24 18:55:53 +00003325 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003326 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003327 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3328 if (IterationNum == NumIterations)
3329 return RetVal = PHIVal; // Got exit value!
3330
3331 // Compute the value of the PHI node for the next iteration.
3332 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3333 if (NextPHI == PHIVal)
3334 return RetVal = NextPHI; // Stopped evolving!
3335 if (NextPHI == 0)
3336 return 0; // Couldn't evaluate!
3337 PHIVal = NextPHI;
3338 }
3339}
3340
Dan Gohman46bdfb02009-02-24 18:55:53 +00003341/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003342/// constant number of times (the condition evolves only from constants),
3343/// try to evaluate a few iterations of the loop until we get the exit
3344/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003345/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003346SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003347ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003348 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003349 if (PN == 0) return CouldNotCompute;
Chris Lattner7980fb92004-04-17 18:36:24 +00003350
3351 // Since the loop is canonicalized, the PHI node must have two entries. One
3352 // entry must be a constant (coming in from outside of the loop), and the
3353 // second must be derived from the same PHI.
3354 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3355 Constant *StartCST =
3356 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003357 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003358
3359 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3360 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003361 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003362
3363 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3364 // the loop symbolically to determine when the condition gets a value of
3365 // "ExitWhen".
3366 unsigned IterationNum = 0;
3367 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3368 for (Constant *PHIVal = StartCST;
3369 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003370 ConstantInt *CondVal =
3371 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003372
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003373 // Couldn't symbolically evaluate.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003374 if (!CondVal) return CouldNotCompute;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003375
Reid Spencere8019bb2007-03-01 07:25:48 +00003376 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003377 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00003378 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003379 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003380 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003381
Chris Lattner3221ad02004-04-17 22:58:41 +00003382 // Compute the value of the PHI node for the next iteration.
3383 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3384 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003385 return CouldNotCompute; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003386 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003387 }
3388
3389 // Too many iterations were needed to evaluate.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003390 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003391}
3392
Dan Gohman66a7e852009-05-08 20:38:54 +00003393/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3394/// at the specified scope in the program. The L value specifies a loop
3395/// nest to evaluate the expression at, where null is the top-level or a
3396/// specified loop is immediately inside of the loop.
3397///
3398/// This method can be used to compute the exit value for a variable defined
3399/// in a loop by querying what the value will hold in the parent loop.
3400///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003401/// In the case that a relevant loop exit value cannot be computed, the
3402/// original value V is returned.
Dan Gohman35738ac2009-05-04 22:30:44 +00003403SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003404 // FIXME: this should be turned into a virtual method on SCEV!
3405
Chris Lattner3221ad02004-04-17 22:58:41 +00003406 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003407
Nick Lewycky3e630762008-02-20 06:48:22 +00003408 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003409 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003410 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003411 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003412 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003413 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3414 if (PHINode *PN = dyn_cast<PHINode>(I))
3415 if (PN->getParent() == LI->getHeader()) {
3416 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003417 // to see if the loop that contains it has a known backedge-taken
3418 // count. If so, we may be able to force computation of the exit
3419 // value.
3420 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003421 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003422 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003423 // Okay, we know how many times the containing loop executes. If
3424 // this is a constant evolving PHI node, get the final value at
3425 // the specified iteration number.
3426 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003427 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003428 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003429 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003430 }
3431 }
3432
Reid Spencer09906f32006-12-04 21:33:23 +00003433 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003434 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003435 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003436 // result. This is particularly useful for computing loop exit values.
3437 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003438 // Check to see if we've folded this instruction at this loop before.
3439 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3440 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3441 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3442 if (!Pair.second)
3443 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3444
Chris Lattner3221ad02004-04-17 22:58:41 +00003445 std::vector<Constant*> Operands;
3446 Operands.reserve(I->getNumOperands());
3447 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3448 Value *Op = I->getOperand(i);
3449 if (Constant *C = dyn_cast<Constant>(Op)) {
3450 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003451 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003452 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003453 // non-integer and non-pointer, don't even try to analyze them
3454 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003455 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003456 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003457
Chris Lattner3221ad02004-04-17 22:58:41 +00003458 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00003459 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003460 Constant *C = SC->getValue();
3461 if (C->getType() != Op->getType())
3462 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3463 Op->getType(),
3464 false),
3465 C, Op->getType());
3466 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003467 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003468 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3469 if (C->getType() != Op->getType())
3470 C =
3471 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3472 Op->getType(),
3473 false),
3474 C, Op->getType());
3475 Operands.push_back(C);
3476 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003477 return V;
3478 } else {
3479 return V;
3480 }
3481 }
3482 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003483
3484 Constant *C;
3485 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3486 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3487 &Operands[0], Operands.size());
3488 else
3489 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3490 &Operands[0], Operands.size());
Dan Gohman6bce6432009-05-08 20:47:27 +00003491 Pair.first->second = C;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003492 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003493 }
3494 }
3495
3496 // This is some other type of SCEVUnknown, just return it.
3497 return V;
3498 }
3499
Dan Gohman622ed672009-05-04 22:02:23 +00003500 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003501 // Avoid performing the look-up in the common case where the specified
3502 // expression has no loop-variant portions.
3503 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3504 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3505 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003506 // Okay, at least one of these operands is loop variant but might be
3507 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmana82752c2009-06-14 22:47:23 +00003508 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003509 NewOps.push_back(OpAtScope);
3510
3511 for (++i; i != e; ++i) {
3512 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003513 NewOps.push_back(OpAtScope);
3514 }
3515 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003516 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003517 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003518 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003519 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003520 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003521 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003522 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003523 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003524 }
3525 }
3526 // If we got here, all operands are loop invariant.
3527 return Comm;
3528 }
3529
Dan Gohman622ed672009-05-04 22:02:23 +00003530 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003531 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003532 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003533 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3534 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003535 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003536 }
3537
3538 // If this is a loop recurrence for a loop that does not contain L, then we
3539 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003540 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003541 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3542 // To evaluate this recurrence, we need to know how many times the AddRec
3543 // loop iterates. Compute this now.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003544 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003545 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003546
Eli Friedmanb42a6262008-08-04 23:49:06 +00003547 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003548 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003549 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003550 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003551 }
3552
Dan Gohman622ed672009-05-04 22:02:23 +00003553 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003554 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003555 if (Op == Cast->getOperand())
3556 return Cast; // must be loop invariant
3557 return getZeroExtendExpr(Op, Cast->getType());
3558 }
3559
Dan Gohman622ed672009-05-04 22:02:23 +00003560 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003561 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003562 if (Op == Cast->getOperand())
3563 return Cast; // must be loop invariant
3564 return getSignExtendExpr(Op, Cast->getType());
3565 }
3566
Dan Gohman622ed672009-05-04 22:02:23 +00003567 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003568 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003569 if (Op == Cast->getOperand())
3570 return Cast; // must be loop invariant
3571 return getTruncateExpr(Op, Cast->getType());
3572 }
3573
3574 assert(0 && "Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003575 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003576}
3577
Dan Gohman66a7e852009-05-08 20:38:54 +00003578/// getSCEVAtScope - This is a convenience function which does
3579/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003580SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3581 return getSCEVAtScope(getSCEV(V), L);
3582}
3583
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003584/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3585/// following equation:
3586///
3587/// A * X = B (mod N)
3588///
3589/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3590/// A and B isn't important.
3591///
3592/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3593static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3594 ScalarEvolution &SE) {
3595 uint32_t BW = A.getBitWidth();
3596 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3597 assert(A != 0 && "A must be non-zero.");
3598
3599 // 1. D = gcd(A, N)
3600 //
3601 // The gcd of A and N may have only one prime factor: 2. The number of
3602 // trailing zeros in A is its multiplicity
3603 uint32_t Mult2 = A.countTrailingZeros();
3604 // D = 2^Mult2
3605
3606 // 2. Check if B is divisible by D.
3607 //
3608 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3609 // is not less than multiplicity of this prime factor for D.
3610 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003611 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003612
3613 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3614 // modulo (N / D).
3615 //
3616 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3617 // bit width during computations.
3618 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3619 APInt Mod(BW + 1, 0);
3620 Mod.set(BW - Mult2); // Mod = N / D
3621 APInt I = AD.multiplicativeInverse(Mod);
3622
3623 // 4. Compute the minimum unsigned root of the equation:
3624 // I * (B / D) mod (N / D)
3625 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3626
3627 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3628 // bits.
3629 return SE.getConstant(Result.trunc(BW));
3630}
Chris Lattner53e677a2004-04-02 20:23:17 +00003631
3632/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3633/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3634/// might be the same) or two SCEVCouldNotCompute objects.
3635///
3636static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00003637SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003638 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00003639 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3640 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3641 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003642
Chris Lattner53e677a2004-04-02 20:23:17 +00003643 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00003644 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003645 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003646 return std::make_pair(CNC, CNC);
3647 }
3648
Reid Spencere8019bb2007-03-01 07:25:48 +00003649 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00003650 const APInt &L = LC->getValue()->getValue();
3651 const APInt &M = MC->getValue()->getValue();
3652 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00003653 APInt Two(BitWidth, 2);
3654 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003655
Reid Spencere8019bb2007-03-01 07:25:48 +00003656 {
3657 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00003658 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00003659 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3660 // The B coefficient is M-N/2
3661 APInt B(M);
3662 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003663
Reid Spencere8019bb2007-03-01 07:25:48 +00003664 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00003665 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00003666
Reid Spencere8019bb2007-03-01 07:25:48 +00003667 // Compute the B^2-4ac term.
3668 APInt SqrtTerm(B);
3669 SqrtTerm *= B;
3670 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00003671
Reid Spencere8019bb2007-03-01 07:25:48 +00003672 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3673 // integer value or else APInt::sqrt() will assert.
3674 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003675
Reid Spencere8019bb2007-03-01 07:25:48 +00003676 // Compute the two solutions for the quadratic formula.
3677 // The divisions must be performed as signed divisions.
3678 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00003679 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003680 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003681 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003682 return std::make_pair(CNC, CNC);
3683 }
3684
Reid Spencere8019bb2007-03-01 07:25:48 +00003685 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3686 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003687
Dan Gohman246b2562007-10-22 18:31:58 +00003688 return std::make_pair(SE.getConstant(Solution1),
3689 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00003690 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00003691}
3692
3693/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003694/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman35738ac2009-05-04 22:30:44 +00003695SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003696 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00003697 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003698 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00003699 if (C->getValue()->isZero()) return C;
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003700 return CouldNotCompute; // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003701 }
3702
Dan Gohman35738ac2009-05-04 22:30:44 +00003703 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003704 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003705 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003706
3707 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003708 // If this is an affine expression, the execution count of this branch is
3709 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00003710 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003711 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00003712 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003713 // equivalent to:
3714 //
3715 // Step*N = -Start (mod 2^BW)
3716 //
3717 // where BW is the common bit width of Start and Step.
3718
Chris Lattner53e677a2004-04-02 20:23:17 +00003719 // Get the initial value for the loop.
3720 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003721 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003722
Dan Gohman622ed672009-05-04 22:02:23 +00003723 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003724 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00003725
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003726 // First, handle unitary steps.
3727 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003728 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003729 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3730 return Start; // N = Start (as unsigned)
3731
3732 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00003733 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003734 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003735 -StartC->getValue()->getValue(),
3736 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003737 }
Chris Lattner42a75512007-01-15 02:27:26 +00003738 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003739 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3740 // the quadratic equation to solve it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003741 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3742 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00003743 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3744 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003745 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003746#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003747 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3748 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003749#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00003750 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003751 if (ConstantInt *CB =
3752 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003753 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003754 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003755 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003756
Chris Lattner53e677a2004-04-02 20:23:17 +00003757 // We can only use this value if the chrec ends up with an exact zero
3758 // value at this index. When solving for "X*X != 5", for example, we
3759 // should not accept a root of 2.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003760 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00003761 if (Val->isZero())
3762 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00003763 }
3764 }
3765 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003766
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003767 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003768}
3769
3770/// HowFarToNonZero - Return the number of times a backedge checking the
3771/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003772/// CouldNotCompute
Dan Gohman35738ac2009-05-04 22:30:44 +00003773SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003774 // Loops that look like: while (X == 0) are very strange indeed. We don't
3775 // handle them yet except for the trivial case. This could be expanded in the
3776 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003777
Chris Lattner53e677a2004-04-02 20:23:17 +00003778 // If the value is a constant, check to see if it is known to be non-zero
3779 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00003780 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00003781 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003782 return getIntegerSCEV(0, C->getType());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003783 return CouldNotCompute; // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003784 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003785
Chris Lattner53e677a2004-04-02 20:23:17 +00003786 // We could implement others, but I really doubt anyone writes loops like
3787 // this, and if they did, they would already be constant folded.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003788 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003789}
3790
Dan Gohman859b4822009-05-18 15:36:09 +00003791/// getLoopPredecessor - If the given loop's header has exactly one unique
3792/// predecessor outside the loop, return it. Otherwise return null.
3793///
3794BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3795 BasicBlock *Header = L->getHeader();
3796 BasicBlock *Pred = 0;
3797 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3798 PI != E; ++PI)
3799 if (!L->contains(*PI)) {
3800 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3801 Pred = *PI;
3802 }
3803 return Pred;
3804}
3805
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003806/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3807/// (which may not be an immediate predecessor) which has exactly one
3808/// successor from which BB is reachable, or null if no such block is
3809/// found.
3810///
3811BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003812ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003813 // If the block has a unique predecessor, then there is no path from the
3814 // predecessor to the block that does not go through the direct edge
3815 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003816 if (BasicBlock *Pred = BB->getSinglePredecessor())
3817 return Pred;
3818
3819 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00003820 // If the header has a unique predecessor outside the loop, it must be
3821 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003822 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00003823 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003824
3825 return 0;
3826}
3827
Dan Gohman763bad12009-06-20 00:35:32 +00003828/// HasSameValue - SCEV structural equivalence is usually sufficient for
3829/// testing whether two expressions are equal, however for the purposes of
3830/// looking for a condition guarding a loop, it can be useful to be a little
3831/// more general, since a front-end may have replicated the controlling
3832/// expression.
3833///
3834static bool HasSameValue(const SCEVHandle &A, const SCEVHandle &B) {
3835 // Quick check to see if they are the same SCEV.
3836 if (A == B) return true;
3837
3838 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3839 // two different instructions with the same value. Check for this case.
3840 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3841 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3842 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3843 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3844 if (AI->isIdenticalTo(BI))
3845 return true;
3846
3847 // Otherwise assume they may have a different value.
3848 return false;
3849}
3850
Dan Gohmanc2390b12009-02-12 22:19:27 +00003851/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003852/// a conditional between LHS and RHS. This is used to help avoid max
3853/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003854bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003855 ICmpInst::Predicate Pred,
Dan Gohman35738ac2009-05-04 22:30:44 +00003856 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00003857 // Interpret a null as meaning no loop, where there is obviously no guard
3858 // (interprocedural conditions notwithstanding).
3859 if (!L) return false;
3860
Dan Gohman859b4822009-05-18 15:36:09 +00003861 BasicBlock *Predecessor = getLoopPredecessor(L);
3862 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003863
Dan Gohman859b4822009-05-18 15:36:09 +00003864 // Starting at the loop predecessor, climb up the predecessor chain, as long
3865 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003866 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00003867 for (; Predecessor;
3868 PredecessorDest = Predecessor,
3869 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00003870
3871 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00003872 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003873 if (!LoopEntryPredicate ||
3874 LoopEntryPredicate->isUnconditional())
3875 continue;
3876
3877 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3878 if (!ICI) continue;
3879
3880 // Now that we found a conditional branch that dominates the loop, check to
3881 // see if it is the comparison we are looking for.
3882 Value *PreCondLHS = ICI->getOperand(0);
3883 Value *PreCondRHS = ICI->getOperand(1);
3884 ICmpInst::Predicate Cond;
Dan Gohman859b4822009-05-18 15:36:09 +00003885 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohman38372182008-08-12 20:17:31 +00003886 Cond = ICI->getPredicate();
3887 else
3888 Cond = ICI->getInversePredicate();
3889
Dan Gohmanc2390b12009-02-12 22:19:27 +00003890 if (Cond == Pred)
3891 ; // An exact match.
3892 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3893 ; // The actual condition is beyond sufficient.
3894 else
3895 // Check a few special cases.
3896 switch (Cond) {
3897 case ICmpInst::ICMP_UGT:
3898 if (Pred == ICmpInst::ICMP_ULT) {
3899 std::swap(PreCondLHS, PreCondRHS);
3900 Cond = ICmpInst::ICMP_ULT;
3901 break;
3902 }
3903 continue;
3904 case ICmpInst::ICMP_SGT:
3905 if (Pred == ICmpInst::ICMP_SLT) {
3906 std::swap(PreCondLHS, PreCondRHS);
3907 Cond = ICmpInst::ICMP_SLT;
3908 break;
3909 }
3910 continue;
3911 case ICmpInst::ICMP_NE:
3912 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3913 // so check for this case by checking if the NE is comparing against
3914 // a minimum or maximum constant.
3915 if (!ICmpInst::isTrueWhenEqual(Pred))
3916 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3917 const APInt &A = CI->getValue();
3918 switch (Pred) {
3919 case ICmpInst::ICMP_SLT:
3920 if (A.isMaxSignedValue()) break;
3921 continue;
3922 case ICmpInst::ICMP_SGT:
3923 if (A.isMinSignedValue()) break;
3924 continue;
3925 case ICmpInst::ICMP_ULT:
3926 if (A.isMaxValue()) break;
3927 continue;
3928 case ICmpInst::ICMP_UGT:
3929 if (A.isMinValue()) break;
3930 continue;
3931 default:
3932 continue;
3933 }
3934 Cond = ICmpInst::ICMP_NE;
3935 // NE is symmetric but the original comparison may not be. Swap
3936 // the operands if necessary so that they match below.
3937 if (isa<SCEVConstant>(LHS))
3938 std::swap(PreCondLHS, PreCondRHS);
3939 break;
3940 }
3941 continue;
3942 default:
3943 // We weren't able to reconcile the condition.
3944 continue;
3945 }
Dan Gohman38372182008-08-12 20:17:31 +00003946
3947 if (!PreCondLHS->getType()->isInteger()) continue;
3948
3949 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3950 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
Dan Gohman763bad12009-06-20 00:35:32 +00003951 if ((HasSameValue(LHS, PreCondLHSSCEV) &&
3952 HasSameValue(RHS, PreCondRHSSCEV)) ||
3953 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
3954 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV))))
Dan Gohman38372182008-08-12 20:17:31 +00003955 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003956 }
3957
Dan Gohman38372182008-08-12 20:17:31 +00003958 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003959}
3960
Dan Gohman51f53b72009-06-21 23:46:38 +00003961/// getBECount - Subtract the end and start values and divide by the step,
3962/// rounding up, to get the number of times the backedge is executed. Return
3963/// CouldNotCompute if an intermediate computation overflows.
3964SCEVHandle ScalarEvolution::getBECount(const SCEVHandle &Start,
3965 const SCEVHandle &End,
3966 const SCEVHandle &Step) {
3967 const Type *Ty = Start->getType();
3968 SCEVHandle NegOne = getIntegerSCEV(-1, Ty);
3969 SCEVHandle Diff = getMinusSCEV(End, Start);
3970 SCEVHandle RoundUp = getAddExpr(Step, NegOne);
3971
3972 // Add an adjustment to the difference between End and Start so that
3973 // the division will effectively round up.
3974 SCEVHandle Add = getAddExpr(Diff, RoundUp);
3975
3976 // Check Add for unsigned overflow.
3977 // TODO: More sophisticated things could be done here.
3978 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
3979 SCEVHandle OperandExtendedAdd =
3980 getAddExpr(getZeroExtendExpr(Diff, WideTy),
3981 getZeroExtendExpr(RoundUp, WideTy));
3982 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
3983 return CouldNotCompute;
3984
3985 return getUDivExpr(Add, Step);
3986}
3987
Chris Lattnerdb25de42005-08-15 23:33:51 +00003988/// HowManyLessThans - Return the number of times a backedge containing the
3989/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003990/// CouldNotCompute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003991ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohman35738ac2009-05-04 22:30:44 +00003992HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3993 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003994 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003995 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003996
Dan Gohman35738ac2009-05-04 22:30:44 +00003997 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003998 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003999 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004000
4001 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004002 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004003 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
4004 SCEVHandle Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004005
4006 // TODO: handle non-constant strides.
4007 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4008 if (!CStep || CStep->isZero())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004009 return CouldNotCompute;
Dan Gohman70a1fe72009-05-18 15:22:39 +00004010 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004011 // With unit stride, the iteration never steps past the limit value.
4012 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4013 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4014 // Test whether a positive iteration iteration can step past the limit
4015 // value and past the maximum value for its type in a single step.
4016 if (isSigned) {
4017 APInt Max = APInt::getSignedMaxValue(BitWidth);
4018 if ((Max - CStep->getValue()->getValue())
4019 .slt(CLimit->getValue()->getValue()))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004020 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004021 } else {
4022 APInt Max = APInt::getMaxValue(BitWidth);
4023 if ((Max - CStep->getValue()->getValue())
4024 .ult(CLimit->getValue()->getValue()))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004025 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004026 }
4027 } else
4028 // TODO: handle non-constant limit values below.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004029 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004030 } else
4031 // TODO: handle negative strides below.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004032 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004033
Dan Gohmana1af7572009-04-30 20:47:05 +00004034 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4035 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4036 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004037 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004038
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004039 // First, we get the value of the LHS in the first iteration: n
4040 SCEVHandle Start = AddRec->getOperand(0);
4041
Dan Gohmana1af7572009-04-30 20:47:05 +00004042 // Determine the minimum constant start value.
4043 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
4044 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4045 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004046
Dan Gohmana1af7572009-04-30 20:47:05 +00004047 // If we know that the condition is true in order to enter the loop,
4048 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004049 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4050 // the division must round up.
Dan Gohmana1af7572009-04-30 20:47:05 +00004051 SCEVHandle End = RHS;
4052 if (!isLoopGuardedByCond(L,
4053 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4054 getMinusSCEV(Start, Step), RHS))
4055 End = isSigned ? getSMaxExpr(RHS, Start)
4056 : getUMaxExpr(RHS, Start);
4057
4058 // Determine the maximum constant end value.
Dan Gohman3964acc2009-06-20 00:32:22 +00004059 SCEVHandle MaxEnd =
4060 isa<SCEVConstant>(End) ? End :
4061 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4062 .ashr(GetMinSignBits(End) - 1) :
4063 APInt::getMaxValue(BitWidth)
4064 .lshr(GetMinLeadingZeros(End)));
Dan Gohmana1af7572009-04-30 20:47:05 +00004065
4066 // Finally, we subtract these two values and divide, rounding up, to get
4067 // the number of times the backedge is executed.
Dan Gohman51f53b72009-06-21 23:46:38 +00004068 SCEVHandle BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004069
4070 // The maximum backedge count is similar, except using the minimum start
4071 // value and the maximum end value.
Dan Gohman51f53b72009-06-21 23:46:38 +00004072 SCEVHandle MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmana1af7572009-04-30 20:47:05 +00004073
4074 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004075 }
4076
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004077 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004078}
4079
Chris Lattner53e677a2004-04-02 20:23:17 +00004080/// getNumIterationsInRange - Return the number of iterations of this loop that
4081/// produce values in the specified constant range. Another way of looking at
4082/// this is that it returns the first iteration number where the value is not in
4083/// the condition, thus computing the exit count. If the iteration count can't
4084/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00004085SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
4086 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004087 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004088 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004089
4090 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004091 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004092 if (!SC->getValue()->isZero()) {
Dan Gohmana82752c2009-06-14 22:47:23 +00004093 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004094 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
4095 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004096 if (const SCEVAddRecExpr *ShiftedAddRec =
4097 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004098 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004099 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004100 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004101 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004102 }
4103
4104 // The only time we can solve this is when we have all constant indices.
4105 // Otherwise, we cannot determine the overflow conditions.
4106 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4107 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004108 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004109
4110
4111 // Okay at this point we know that all elements of the chrec are constants and
4112 // that the start element is zero.
4113
4114 // First check to see if the range contains zero. If not, the first
4115 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004116 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004117 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004118 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004119
Chris Lattner53e677a2004-04-02 20:23:17 +00004120 if (isAffine()) {
4121 // If this is an affine expression then we have this situation:
4122 // Solve {0,+,A} in Range === Ax in Range
4123
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004124 // We know that zero is in the range. If A is positive then we know that
4125 // the upper value of the range must be the first possible exit value.
4126 // If A is negative then the lower of the range is the last possible loop
4127 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004128 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004129 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4130 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004131
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004132 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004133 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00004134 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004135
4136 // Evaluate at the exit value. If we really did fall out of the valid
4137 // range, then we computed our trip count, otherwise wrap around or other
4138 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004139 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004140 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004141 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004142
4143 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004144 assert(Range.contains(
4145 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004146 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004147 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004148 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004149 } else if (isQuadratic()) {
4150 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4151 // quadratic equation to solve it. To do this, we must frame our problem in
4152 // terms of figuring out when zero is crossed, instead of when
4153 // Range.getUpper() is crossed.
Dan Gohmana82752c2009-06-14 22:47:23 +00004154 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004155 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
4156 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004157
4158 // Next, solve the constructed addrec
4159 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004160 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004161 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4162 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004163 if (R1) {
4164 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004165 if (ConstantInt *CB =
4166 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004167 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004168 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004169 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004170
Chris Lattner53e677a2004-04-02 20:23:17 +00004171 // Make sure the root is not off by one. The returned iteration should
4172 // not be in the range, but the previous one should be. When solving
4173 // for "X*X < 5", for example, we should not return a root of 2.
4174 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004175 R1->getValue(),
4176 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004177 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004178 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00004179 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004180
Dan Gohman246b2562007-10-22 18:31:58 +00004181 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004182 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004183 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004184 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004185 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004186
Chris Lattner53e677a2004-04-02 20:23:17 +00004187 // If R1 was not in the range, then it is a good return value. Make
4188 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00004189 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004190 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004191 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004192 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004193 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004194 }
4195 }
4196 }
4197
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004198 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004199}
4200
4201
4202
4203//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004204// SCEVCallbackVH Class Implementation
4205//===----------------------------------------------------------------------===//
4206
Dan Gohman1959b752009-05-19 19:22:47 +00004207void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman35738ac2009-05-04 22:30:44 +00004208 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4209 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4210 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004211 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4212 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004213 SE->Scalars.erase(getValPtr());
4214 // this now dangles!
4215}
4216
Dan Gohman1959b752009-05-19 19:22:47 +00004217void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004218 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4219
4220 // Forget all the expressions associated with users of the old value,
4221 // so that future queries will recompute the expressions using the new
4222 // value.
4223 SmallVector<User *, 16> Worklist;
4224 Value *Old = getValPtr();
4225 bool DeleteOld = false;
4226 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4227 UI != UE; ++UI)
4228 Worklist.push_back(*UI);
4229 while (!Worklist.empty()) {
4230 User *U = Worklist.pop_back_val();
4231 // Deleting the Old value will cause this to dangle. Postpone
4232 // that until everything else is done.
4233 if (U == Old) {
4234 DeleteOld = true;
4235 continue;
4236 }
4237 if (PHINode *PN = dyn_cast<PHINode>(U))
4238 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004239 if (Instruction *I = dyn_cast<Instruction>(U))
4240 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004241 if (SE->Scalars.erase(U))
4242 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4243 UI != UE; ++UI)
4244 Worklist.push_back(*UI);
4245 }
4246 if (DeleteOld) {
4247 if (PHINode *PN = dyn_cast<PHINode>(Old))
4248 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004249 if (Instruction *I = dyn_cast<Instruction>(Old))
4250 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004251 SE->Scalars.erase(Old);
4252 // this now dangles!
4253 }
4254 // this may dangle!
4255}
4256
Dan Gohman1959b752009-05-19 19:22:47 +00004257ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004258 : CallbackVH(V), SE(se) {}
4259
4260//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004261// ScalarEvolution Class Implementation
4262//===----------------------------------------------------------------------===//
4263
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004264ScalarEvolution::ScalarEvolution()
Owen Anderson4a7893b2009-06-18 22:25:12 +00004265 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute(0)) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004266}
4267
Chris Lattner53e677a2004-04-02 20:23:17 +00004268bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004269 this->F = &F;
4270 LI = &getAnalysis<LoopInfo>();
4271 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004272 return false;
4273}
4274
4275void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004276 Scalars.clear();
4277 BackedgeTakenCounts.clear();
4278 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004279 ValuesAtScopes.clear();
Owen Anderson08367b62009-06-22 18:25:46 +00004280
4281 for (std::map<ConstantInt*, SCEVConstant*>::iterator
4282 I = SCEVConstants.begin(), E = SCEVConstants.end(); I != E; ++I)
4283 delete I->second;
4284 for (std::map<std::pair<const SCEV*, const Type*>,
4285 SCEVTruncateExpr*>::iterator I = SCEVTruncates.begin(),
4286 E = SCEVTruncates.end(); I != E; ++I)
4287 delete I->second;
4288 for (std::map<std::pair<const SCEV*, const Type*>,
4289 SCEVZeroExtendExpr*>::iterator I = SCEVZeroExtends.begin(),
4290 E = SCEVZeroExtends.end(); I != E; ++I)
4291 delete I->second;
4292 for (std::map<std::pair<unsigned, std::vector<const SCEV*> >,
4293 SCEVCommutativeExpr*>::iterator I = SCEVCommExprs.begin(),
4294 E = SCEVCommExprs.end(); I != E; ++I)
4295 delete I->second;
4296 for (std::map<std::pair<const SCEV*, const SCEV*>, SCEVUDivExpr*>::iterator
4297 I = SCEVUDivs.begin(), E = SCEVUDivs.end(); I != E; ++I)
4298 delete I->second;
4299 for (std::map<std::pair<const SCEV*, const Type*>,
4300 SCEVSignExtendExpr*>::iterator I = SCEVSignExtends.begin(),
4301 E = SCEVSignExtends.end(); I != E; ++I)
4302 delete I->second;
4303 for (std::map<std::pair<const Loop *, std::vector<const SCEV*> >,
4304 SCEVAddRecExpr*>::iterator I = SCEVAddRecExprs.begin(),
4305 E = SCEVAddRecExprs.end(); I != E; ++I)
4306 delete I->second;
4307 for (std::map<Value*, SCEVUnknown*>::iterator I = SCEVUnknowns.begin(),
4308 E = SCEVUnknowns.end(); I != E; ++I)
4309 delete I->second;
4310
4311 SCEVConstants.clear();
4312 SCEVTruncates.clear();
4313 SCEVZeroExtends.clear();
4314 SCEVCommExprs.clear();
4315 SCEVUDivs.clear();
4316 SCEVSignExtends.clear();
4317 SCEVAddRecExprs.clear();
4318 SCEVUnknowns.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00004319}
4320
4321void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4322 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004323 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004324}
4325
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004326bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004327 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004328}
4329
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004330static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004331 const Loop *L) {
4332 // Print all inner loops first
4333 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4334 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004335
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004336 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004337
Devang Patelb7211a22007-08-21 00:31:24 +00004338 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004339 L->getExitBlocks(ExitBlocks);
4340 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004341 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004342
Dan Gohman46bdfb02009-02-24 18:55:53 +00004343 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4344 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004345 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004346 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004347 }
4348
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004349 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004350}
4351
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004352void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004353 // ScalarEvolution's implementaiton of the print method is to print
4354 // out SCEV values of all instructions that are interesting. Doing
4355 // this potentially causes it to create new SCEV objects though,
4356 // which technically conflicts with the const qualifier. This isn't
4357 // observable from outside the class though (the hasSCEV function
4358 // notwithstanding), so casting away the const isn't dangerous.
4359 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004360
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004361 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004362 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004363 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00004364 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00004365 OS << " --> ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004366 SCEVHandle SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004367 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004368
Dan Gohman0c689c52009-06-19 17:49:54 +00004369 const Loop *L = LI->getLoopFor((*I).getParent());
4370
4371 SCEVHandle AtUse = SE.getSCEVAtScope(SV, L);
4372 if (AtUse != SV) {
4373 OS << " --> ";
4374 AtUse->print(OS);
4375 }
4376
4377 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00004378 OS << "\t\t" "Exits: ";
Dan Gohman0c689c52009-06-19 17:49:54 +00004379 SCEVHandle ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00004380 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004381 OS << "<<Unknown>>";
4382 } else {
4383 OS << *ExitValue;
4384 }
4385 }
4386
Chris Lattner53e677a2004-04-02 20:23:17 +00004387 OS << "\n";
4388 }
4389
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004390 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4391 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4392 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004393}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004394
4395void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4396 raw_os_ostream OS(o);
4397 print(OS, M);
4398}