blob: ae3eb48bf5270b1f36269191df53a533497693c0 [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"
71#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000073#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000075#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000079#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000080#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000081#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000085#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000086#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000087#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
103 cl::init(100));
104
Dan Gohman844731a2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000107char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Chris Lattner53e677a2004-04-02 20:23:17 +0000116SCEV::~SCEV() {}
117void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000125}
126
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Chris Lattner53e677a2004-04-02 20:23:17 +0000133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanf8a8be82009-04-21 23:15:49 +0000135SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000144 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
Chris Lattner4dc534c2005-02-13 04:37:18 +0000152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000154 const SCEVHandle &Conc,
155 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000156 return this;
157}
158
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000159void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000160 OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
165}
166
167
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value. Don't use a SCEVHandle here, or else the object will
170// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000172
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000174SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000175 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176}
Chris Lattner53e677a2004-04-02 20:23:17 +0000177
Dan Gohman246b2562007-10-22 18:31:58 +0000178SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000179 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000180 if (R == 0) R = new SCEVConstant(V);
181 return R;
182}
Chris Lattner53e677a2004-04-02 20:23:17 +0000183
Dan Gohman246b2562007-10-22 18:31:58 +0000184SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000186}
187
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000190void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191 WriteAsOperand(OS, V, false);
192}
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Dan Gohman84923602009-04-21 01:25:57 +0000194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195 const SCEVHandle &op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
197
198SCEVCastExpr::~SCEVCastExpr() {}
199
200bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201 return Op->dominates(BB, DT);
202}
203
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000204// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205// particular input. Don't use a SCEVHandle here, or else the object will
206// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000207static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
208 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000209
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000211 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215}
Chris Lattner53e677a2004-04-02 20:23:17 +0000216
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000218 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000232 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000240}
241
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000242void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000243 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000244}
245
Dan Gohmand19534a2007-06-15 14:38:12 +0000246// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247// particular input. Don't use a SCEVHandle here, or else the object will never
248// be deleted!
249static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
250 SCEVSignExtendExpr*> > SCEVSignExtends;
251
252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000253 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000256 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000257}
258
259SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
261}
262
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000263void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000264 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000265}
266
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000267// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268// particular input. Don't use a SCEVHandle here, or else the object will never
269// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000270static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
271 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000272
273SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000274 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
275 std::vector<SCEV*>(Operands.begin(),
276 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000277}
278
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
286}
287
Chris Lattner4dc534c2005-02-13 04:37:18 +0000288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000295 if (H != getOperand(i)) {
296 std::vector<SCEVHandle> NewOps;
297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000304
305 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000306 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000307 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000308 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000313 else
314 assert(0 && "Unknown commutative expr!");
315 }
316 }
317 return this;
318}
319
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000320bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
324 }
325 return true;
326}
327
Chris Lattner4dc534c2005-02-13 04:37:18 +0000328
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000333 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000335SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
338
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000343void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000344 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345}
346
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000348 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000349}
350
351// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352// particular input. Don't use a SCEVHandle here, or else the object will never
353// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000354static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000358 SCEVAddRecExprs->erase(std::make_pair(L,
359 std::vector<SCEV*>(Operands.begin(),
360 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361}
362
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000363bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365 if (!getOperand(i)->dominates(BB, DT))
366 return false;
367 }
368 return true;
369}
370
371
Chris Lattner4dc534c2005-02-13 04:37:18 +0000372SCEVHandle SCEVAddRecExpr::
373replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000374 const SCEVHandle &Conc,
375 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000377 SCEVHandle H =
378 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000379 if (H != getOperand(i)) {
380 std::vector<SCEVHandle> NewOps;
381 NewOps.reserve(getNumOperands());
382 for (unsigned j = 0; j != i; ++j)
383 NewOps.push_back(getOperand(j));
384 NewOps.push_back(H);
385 for (++i; i != e; ++i)
386 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000387 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000388
Dan Gohman246b2562007-10-22 18:31:58 +0000389 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000390 }
391 }
392 return this;
393}
394
395
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000396bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
397 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000398 // contain L and if the start is invariant.
399 return !QueryLoop->contains(L->getHeader()) &&
400 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000401}
402
403
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000404void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000405 OS << "{" << *Operands[0];
406 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
407 OS << ",+," << *Operands[i];
408 OS << "}<" << L->getHeader()->getName() + ">";
409}
Chris Lattner53e677a2004-04-02 20:23:17 +0000410
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000411// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
412// value. Don't use a SCEVHandle here, or else the object will never be
413// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000414static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000415
Chris Lattnerb3364092006-10-04 21:49:37 +0000416SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000417
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000418bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
419 // All non-instruction values are loop invariant. All instructions are loop
420 // invariant if they are not contained in the specified loop.
421 if (Instruction *I = dyn_cast<Instruction>(V))
422 return !L->contains(I->getParent());
423 return true;
424}
Chris Lattner53e677a2004-04-02 20:23:17 +0000425
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
430}
431
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000432const Type *SCEVUnknown::getType() const {
433 return V->getType();
434}
Chris Lattner53e677a2004-04-02 20:23:17 +0000435
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000436void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman2d1be872009-04-16 03:18:22 +0000437 if (isa<PointerType>(V->getType()))
438 OS << "(ptrtoint " << *V->getType() << " ";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000439 WriteAsOperand(OS, V, false);
Dan Gohman2d1be872009-04-16 03:18:22 +0000440 if (isa<PointerType>(V->getType()))
441 OS << " to iPTR)";
Chris Lattner53e677a2004-04-02 20:23:17 +0000442}
443
Chris Lattner8d741b82004-06-20 06:23:15 +0000444//===----------------------------------------------------------------------===//
445// SCEV Utilities
446//===----------------------------------------------------------------------===//
447
448namespace {
449 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450 /// than the complexity of the RHS. This comparator is used to canonicalize
451 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000452 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000453 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000454 return LHS->getSCEVType() < RHS->getSCEVType();
455 }
456 };
457}
458
459/// GroupByComplexity - Given a list of SCEV objects, order them by their
460/// complexity, and group objects of the same complexity together by value.
461/// When this routine is finished, we know that any duplicates in the vector are
462/// consecutive and that complexity is monotonically increasing.
463///
464/// Note that we go take special precautions to ensure that we get determinstic
465/// results from this routine. In other words, we don't want the results of
466/// this to depend on where the addresses of various SCEV objects happened to
467/// land in memory.
468///
469static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
470 if (Ops.size() < 2) return; // Noop
471 if (Ops.size() == 2) {
472 // This is the common case, which also happens to be trivially simple.
473 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000474 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000475 std::swap(Ops[0], Ops[1]);
476 return;
477 }
478
479 // Do the rough sort by complexity.
480 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
481
482 // Now that we are sorted by complexity, group elements of the same
483 // complexity. Note that this is, at worst, N^2, but the vector is likely to
484 // be extremely short in practice. Note that we take this approach because we
485 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000486 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000487 SCEV *S = Ops[i];
488 unsigned Complexity = S->getSCEVType();
489
490 // If there are any objects of the same complexity and same value as this
491 // one, group them.
492 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
493 if (Ops[j] == S) { // Found a duplicate.
494 // Move it to immediately after i'th element.
495 std::swap(Ops[i+1], Ops[j]);
496 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000497 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000498 }
499 }
500 }
501}
502
Chris Lattner53e677a2004-04-02 20:23:17 +0000503
Chris Lattner53e677a2004-04-02 20:23:17 +0000504
505//===----------------------------------------------------------------------===//
506// Simple SCEV method implementations
507//===----------------------------------------------------------------------===//
508
Eli Friedmanb42a6262008-08-04 23:49:06 +0000509/// BinomialCoefficient - Compute BC(It, K). The result has width W.
510// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000511static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000512 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000513 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000514 // Handle the simplest case efficiently.
515 if (K == 1)
516 return SE.getTruncateOrZeroExtend(It, ResultTy);
517
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000518 // We are using the following formula for BC(It, K):
519 //
520 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
521 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000522 // Suppose, W is the bitwidth of the return value. We must be prepared for
523 // overflow. Hence, we must assure that the result of our computation is
524 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
525 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000526 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000527 // However, this code doesn't use exactly that formula; the formula it uses
528 // is something like the following, where T is the number of factors of 2 in
529 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
530 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000531 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000532 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000533 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000534 // This formula is trivially equivalent to the previous formula. However,
535 // this formula can be implemented much more efficiently. The trick is that
536 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
537 // arithmetic. To do exact division in modular arithmetic, all we have
538 // to do is multiply by the inverse. Therefore, this step can be done at
539 // width W.
540 //
541 // The next issue is how to safely do the division by 2^T. The way this
542 // is done is by doing the multiplication step at a width of at least W + T
543 // bits. This way, the bottom W+T bits of the product are accurate. Then,
544 // when we perform the division by 2^T (which is equivalent to a right shift
545 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
546 // truncated out after the division by 2^T.
547 //
548 // In comparison to just directly using the first formula, this technique
549 // is much more efficient; using the first formula requires W * K bits,
550 // but this formula less than W + K bits. Also, the first formula requires
551 // a division step, whereas this formula only requires multiplies and shifts.
552 //
553 // It doesn't matter whether the subtraction step is done in the calculation
554 // width or the input iteration count's width; if the subtraction overflows,
555 // the result must be zero anyway. We prefer here to do it in the width of
556 // the induction variable because it helps a lot for certain cases; CodeGen
557 // isn't smart enough to ignore the overflow, which leads to much less
558 // efficient code if the width of the subtraction is wider than the native
559 // register width.
560 //
561 // (It's possible to not widen at all by pulling out factors of 2 before
562 // the multiplication; for example, K=2 can be calculated as
563 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
564 // extra arithmetic, so it's not an obvious win, and it gets
565 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000566
Eli Friedmanb42a6262008-08-04 23:49:06 +0000567 // Protection from insane SCEVs; this bound is conservative,
568 // but it probably doesn't matter.
569 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000570 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000571
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000572 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000573
Eli Friedmanb42a6262008-08-04 23:49:06 +0000574 // Calculate K! / 2^T and T; we divide out the factors of two before
575 // multiplying for calculating K! / 2^T to avoid overflow.
576 // Other overflow doesn't matter because we only care about the bottom
577 // W bits of the result.
578 APInt OddFactorial(W, 1);
579 unsigned T = 1;
580 for (unsigned i = 3; i <= K; ++i) {
581 APInt Mult(W, i);
582 unsigned TwoFactors = Mult.countTrailingZeros();
583 T += TwoFactors;
584 Mult = Mult.lshr(TwoFactors);
585 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000586 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000587
Eli Friedmanb42a6262008-08-04 23:49:06 +0000588 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000589 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000590
591 // Calcuate 2^T, at width T+W.
592 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
593
594 // Calculate the multiplicative inverse of K! / 2^T;
595 // this multiplication factor will perform the exact division by
596 // K! / 2^T.
597 APInt Mod = APInt::getSignedMinValue(W+1);
598 APInt MultiplyFactor = OddFactorial.zext(W+1);
599 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
600 MultiplyFactor = MultiplyFactor.trunc(W);
601
602 // Calculate the product, at width T+W
603 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
604 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
605 for (unsigned i = 1; i != K; ++i) {
606 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
607 Dividend = SE.getMulExpr(Dividend,
608 SE.getTruncateOrZeroExtend(S, CalculationTy));
609 }
610
611 // Divide by 2^T
612 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
613
614 // Truncate the result, and divide by K! / 2^T.
615
616 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
617 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000618}
619
Chris Lattner53e677a2004-04-02 20:23:17 +0000620/// evaluateAtIteration - Return the value of this chain of recurrences at
621/// the specified iteration number. We can evaluate this recurrence by
622/// multiplying each element in the chain by the binomial coefficient
623/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
624///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000625/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000626///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000627/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000628///
Dan Gohman246b2562007-10-22 18:31:58 +0000629SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
630 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000631 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000632 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000633 // The computation is correct in the face of overflow provided that the
634 // multiplication is performed _after_ the evaluation of the binomial
635 // coefficient.
Dan Gohman2d1be872009-04-16 03:18:22 +0000636 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000637 if (isa<SCEVCouldNotCompute>(Coeff))
638 return Coeff;
639
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000641 }
642 return Result;
643}
644
Chris Lattner53e677a2004-04-02 20:23:17 +0000645//===----------------------------------------------------------------------===//
646// SCEV Expression folder implementations
647//===----------------------------------------------------------------------===//
648
Dan Gohman246b2562007-10-22 18:31:58 +0000649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000650 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000651 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000652 assert(isSCEVable(Ty) &&
653 "This is not a conversion to a SCEVable type!");
654 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000655
Chris Lattner53e677a2004-04-02 20:23:17 +0000656 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000657 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000658 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000659
Dan Gohman20900ca2009-04-22 16:20:48 +0000660 // trunc(trunc(x)) --> trunc(x)
661 if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
662 return getTruncateExpr(ST->getOperand(), Ty);
663
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000664 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
665 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
666 return getTruncateOrSignExtend(SS->getOperand(), Ty);
667
668 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
669 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
670 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
671
Chris Lattner53e677a2004-04-02 20:23:17 +0000672 // If the input value is a chrec scev made out of constants, truncate
673 // all of the constants.
674 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
675 std::vector<SCEVHandle> Operands;
676 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
677 // FIXME: This should allow truncation of other expression types!
678 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000679 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000680 else
681 break;
682 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000683 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000684 }
685
Chris Lattnerb3364092006-10-04 21:49:37 +0000686 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000687 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
688 return Result;
689}
690
Dan Gohman8170a682009-04-16 19:25:55 +0000691SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
692 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000693 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000694 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000695 assert(isSCEVable(Ty) &&
696 "This is not a conversion to a SCEVable type!");
697 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000698
Dan Gohman2d1be872009-04-16 03:18:22 +0000699 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000700 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000701 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
702 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
703 return getUnknown(C);
704 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000705
Dan Gohman20900ca2009-04-22 16:20:48 +0000706 // zext(zext(x)) --> zext(x)
707 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
708 return getZeroExtendExpr(SZ->getOperand(), Ty);
709
Dan Gohman01ecca22009-04-27 20:16:15 +0000710 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000711 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000712 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000713 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman01ecca22009-04-27 20:16:15 +0000714 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
715 if (AR->isAffine()) {
716 // Check whether the backedge-taken count is SCEVCouldNotCompute.
717 // Note that this serves two purposes: It filters out loops that are
718 // simply not analyzable, and it covers the case where this code is
719 // being called from within backedge-taken count analysis, such that
720 // attempting to ask for the backedge-taken count would likely result
721 // in infinite recursion. In the later case, the analysis code will
722 // cope with a conservative value, and it will take care to purge
723 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000724 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
725 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000726 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000727 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000728 SCEVHandle Start = AR->getStart();
729 SCEVHandle Step = AR->getStepRecurrence(*this);
730
731 // Check whether the backedge-taken count can be losslessly casted to
732 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000733 SCEVHandle CastedMaxBECount =
734 getTruncateOrZeroExtend(MaxBECount, Start->getType());
735 if (MaxBECount ==
736 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000737 const Type *WideTy =
738 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000739 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000740 SCEVHandle ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000741 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000742 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000743 SCEVHandle Add = getAddExpr(Start, ZMul);
744 if (getZeroExtendExpr(Add, WideTy) ==
745 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000746 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000747 getZeroExtendExpr(Step, WideTy))))
748 // Return the expression with the addrec on the outside.
749 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
750 getZeroExtendExpr(Step, Ty),
751 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000752
753 // Similar to above, only this time treat the step value as signed.
754 // This covers loops that count down.
755 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000756 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000757 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000758 Add = getAddExpr(Start, SMul);
759 if (getZeroExtendExpr(Add, WideTy) ==
760 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000761 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000762 getSignExtendExpr(Step, WideTy))))
763 // Return the expression with the addrec on the outside.
764 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
765 getSignExtendExpr(Step, Ty),
766 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000767 }
768 }
769 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000770
Chris Lattnerb3364092006-10-04 21:49:37 +0000771 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000772 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
773 return Result;
774}
775
Dan Gohman01ecca22009-04-27 20:16:15 +0000776SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
777 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000778 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000779 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000780 assert(isSCEVable(Ty) &&
781 "This is not a conversion to a SCEVable type!");
782 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000783
Dan Gohman2d1be872009-04-16 03:18:22 +0000784 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000785 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000786 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
787 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
788 return getUnknown(C);
789 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000790
Dan Gohman20900ca2009-04-22 16:20:48 +0000791 // sext(sext(x)) --> sext(x)
792 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
793 return getSignExtendExpr(SS->getOperand(), Ty);
794
Dan Gohman01ecca22009-04-27 20:16:15 +0000795 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000796 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000797 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000798 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman01ecca22009-04-27 20:16:15 +0000799 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
800 if (AR->isAffine()) {
801 // Check whether the backedge-taken count is SCEVCouldNotCompute.
802 // Note that this serves two purposes: It filters out loops that are
803 // simply not analyzable, and it covers the case where this code is
804 // being called from within backedge-taken count analysis, such that
805 // attempting to ask for the backedge-taken count would likely result
806 // in infinite recursion. In the later case, the analysis code will
807 // cope with a conservative value, and it will take care to purge
808 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000809 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
810 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000811 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000812 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000813 SCEVHandle Start = AR->getStart();
814 SCEVHandle Step = AR->getStepRecurrence(*this);
815
816 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000817 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000818 SCEVHandle CastedMaxBECount =
819 getTruncateOrZeroExtend(MaxBECount, Start->getType());
820 if (MaxBECount ==
821 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000822 const Type *WideTy =
823 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000824 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000825 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000826 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000827 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000828 SCEVHandle Add = getAddExpr(Start, SMul);
829 if (getSignExtendExpr(Add, WideTy) ==
830 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000831 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000832 getSignExtendExpr(Step, WideTy))))
833 // Return the expression with the addrec on the outside.
834 return getAddRecExpr(getSignExtendExpr(Start, Ty),
835 getSignExtendExpr(Step, Ty),
836 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000837 }
838 }
839 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000840
841 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
842 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
843 return Result;
844}
845
Chris Lattner53e677a2004-04-02 20:23:17 +0000846// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000847SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000848 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000849 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000850
851 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000852 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000853
854 // If there are any constants, fold them together.
855 unsigned Idx = 0;
856 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
857 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000858 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000859 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
860 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000861 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
862 RHSC->getValue()->getValue());
863 Ops[0] = getConstant(Fold);
864 Ops.erase(Ops.begin()+1); // Erase the folded element
865 if (Ops.size() == 1) return Ops[0];
866 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000867 }
868
869 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000870 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000871 Ops.erase(Ops.begin());
872 --Idx;
873 }
874 }
875
Chris Lattner627018b2004-04-07 16:16:11 +0000876 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000877
Chris Lattner53e677a2004-04-02 20:23:17 +0000878 // Okay, check to see if the same value occurs in the operand list twice. If
879 // so, merge them together into an multiply expression. Since we sorted the
880 // list, these values are required to be adjacent.
881 const Type *Ty = Ops[0]->getType();
882 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
883 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
884 // Found a match, merge the two values into a multiply, and add any
885 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000886 SCEVHandle Two = getIntegerSCEV(2, Ty);
887 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000888 if (Ops.size() == 2)
889 return Mul;
890 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
891 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000892 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000893 }
894
Dan Gohmanf50cd742007-06-18 19:30:09 +0000895 // Now we know the first non-constant operand. Skip past any cast SCEVs.
896 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
897 ++Idx;
898
899 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000900 if (Idx < Ops.size()) {
901 bool DeletedAdd = false;
902 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
903 // If we have an add, expand the add operands onto the end of the operands
904 // list.
905 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
906 Ops.erase(Ops.begin()+Idx);
907 DeletedAdd = true;
908 }
909
910 // If we deleted at least one add, we added operands to the end of the list,
911 // and they are not necessarily sorted. Recurse to resort and resimplify
912 // any operands we just aquired.
913 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000914 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000915 }
916
917 // Skip over the add expression until we get to a multiply.
918 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
919 ++Idx;
920
921 // If we are adding something to a multiply expression, make sure the
922 // something is not already an operand of the multiply. If so, merge it into
923 // the multiply.
924 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
925 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
926 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
927 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
928 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000929 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000930 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
931 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
932 if (Mul->getNumOperands() != 2) {
933 // If the multiply has more than two operands, we must get the
934 // Y*Z term.
935 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
936 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000937 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000938 }
Dan Gohman246b2562007-10-22 18:31:58 +0000939 SCEVHandle One = getIntegerSCEV(1, Ty);
940 SCEVHandle AddOne = getAddExpr(InnerMul, One);
941 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000942 if (Ops.size() == 2) return OuterMul;
943 if (AddOp < Idx) {
944 Ops.erase(Ops.begin()+AddOp);
945 Ops.erase(Ops.begin()+Idx-1);
946 } else {
947 Ops.erase(Ops.begin()+Idx);
948 Ops.erase(Ops.begin()+AddOp-1);
949 }
950 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000951 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000952 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000953
Chris Lattner53e677a2004-04-02 20:23:17 +0000954 // Check this multiply against other multiplies being added together.
955 for (unsigned OtherMulIdx = Idx+1;
956 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
957 ++OtherMulIdx) {
958 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
959 // If MulOp occurs in OtherMul, we can fold the two multiplies
960 // together.
961 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
962 OMulOp != e; ++OMulOp)
963 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
964 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
965 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
966 if (Mul->getNumOperands() != 2) {
967 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
968 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000969 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000970 }
971 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
972 if (OtherMul->getNumOperands() != 2) {
973 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
974 OtherMul->op_end());
975 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000976 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000977 }
Dan Gohman246b2562007-10-22 18:31:58 +0000978 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
979 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000980 if (Ops.size() == 2) return OuterMul;
981 Ops.erase(Ops.begin()+Idx);
982 Ops.erase(Ops.begin()+OtherMulIdx-1);
983 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000984 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000985 }
986 }
987 }
988 }
989
990 // If there are any add recurrences in the operands list, see if any other
991 // added values are loop invariant. If so, we can fold them into the
992 // recurrence.
993 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
994 ++Idx;
995
996 // Scan over all recurrences, trying to fold loop invariants into them.
997 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
998 // Scan all of the other operands to this add and add them to the vector if
999 // they are loop invariant w.r.t. the recurrence.
1000 std::vector<SCEVHandle> LIOps;
1001 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1002 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1003 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1004 LIOps.push_back(Ops[i]);
1005 Ops.erase(Ops.begin()+i);
1006 --i; --e;
1007 }
1008
1009 // If we found some loop invariants, fold them into the recurrence.
1010 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001011 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001012 LIOps.push_back(AddRec->getStart());
1013
1014 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001015 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001016
Dan Gohman246b2562007-10-22 18:31:58 +00001017 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001018 // If all of the other operands were loop invariant, we are done.
1019 if (Ops.size() == 1) return NewRec;
1020
1021 // Otherwise, add the folded AddRec by the non-liv parts.
1022 for (unsigned i = 0;; ++i)
1023 if (Ops[i] == AddRec) {
1024 Ops[i] = NewRec;
1025 break;
1026 }
Dan Gohman246b2562007-10-22 18:31:58 +00001027 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001028 }
1029
1030 // Okay, if there weren't any loop invariants to be folded, check to see if
1031 // there are multiple AddRec's with the same loop induction variable being
1032 // added together. If so, we can fold them.
1033 for (unsigned OtherIdx = Idx+1;
1034 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1035 if (OtherIdx != Idx) {
1036 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1037 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1038 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1039 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1040 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1041 if (i >= NewOps.size()) {
1042 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1043 OtherAddRec->op_end());
1044 break;
1045 }
Dan Gohman246b2562007-10-22 18:31:58 +00001046 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001047 }
Dan Gohman246b2562007-10-22 18:31:58 +00001048 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001049
1050 if (Ops.size() == 2) return NewAddRec;
1051
1052 Ops.erase(Ops.begin()+Idx);
1053 Ops.erase(Ops.begin()+OtherIdx-1);
1054 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001055 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001056 }
1057 }
1058
1059 // Otherwise couldn't fold anything into this recurrence. Move onto the
1060 // next one.
1061 }
1062
1063 // Okay, it looks like we really DO need an add expr. Check to see if we
1064 // already have one, otherwise create a new one.
1065 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001066 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1067 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +00001068 if (Result == 0) Result = new SCEVAddExpr(Ops);
1069 return Result;
1070}
1071
1072
Dan Gohman246b2562007-10-22 18:31:58 +00001073SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001074 assert(!Ops.empty() && "Cannot get empty mul!");
1075
1076 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +00001077 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001078
1079 // If there are any constants, fold them together.
1080 unsigned Idx = 0;
1081 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1082
1083 // C1*(C2+V) -> C1*C2 + C1*V
1084 if (Ops.size() == 2)
1085 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1086 if (Add->getNumOperands() == 2 &&
1087 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001088 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1089 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001090
1091
1092 ++Idx;
1093 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1094 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001095 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1096 RHSC->getValue()->getValue());
1097 Ops[0] = getConstant(Fold);
1098 Ops.erase(Ops.begin()+1); // Erase the folded element
1099 if (Ops.size() == 1) return Ops[0];
1100 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001101 }
1102
1103 // If we are left with a constant one being multiplied, strip it off.
1104 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1105 Ops.erase(Ops.begin());
1106 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001107 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001108 // If we have a multiply of zero, it will always be zero.
1109 return Ops[0];
1110 }
1111 }
1112
1113 // Skip over the add expression until we get to a multiply.
1114 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1115 ++Idx;
1116
1117 if (Ops.size() == 1)
1118 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001119
Chris Lattner53e677a2004-04-02 20:23:17 +00001120 // If there are mul operands inline them all into this expression.
1121 if (Idx < Ops.size()) {
1122 bool DeletedMul = false;
1123 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1124 // If we have an mul, expand the mul operands onto the end of the operands
1125 // list.
1126 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1127 Ops.erase(Ops.begin()+Idx);
1128 DeletedMul = true;
1129 }
1130
1131 // If we deleted at least one mul, we added operands to the end of the list,
1132 // and they are not necessarily sorted. Recurse to resort and resimplify
1133 // any operands we just aquired.
1134 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001135 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001136 }
1137
1138 // If there are any add recurrences in the operands list, see if any other
1139 // added values are loop invariant. If so, we can fold them into the
1140 // recurrence.
1141 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1142 ++Idx;
1143
1144 // Scan over all recurrences, trying to fold loop invariants into them.
1145 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1146 // Scan all of the other operands to this mul and add them to the vector if
1147 // they are loop invariant w.r.t. the recurrence.
1148 std::vector<SCEVHandle> LIOps;
1149 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1150 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1151 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1152 LIOps.push_back(Ops[i]);
1153 Ops.erase(Ops.begin()+i);
1154 --i; --e;
1155 }
1156
1157 // If we found some loop invariants, fold them into the recurrence.
1158 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001159 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001160 std::vector<SCEVHandle> NewOps;
1161 NewOps.reserve(AddRec->getNumOperands());
1162 if (LIOps.size() == 1) {
1163 SCEV *Scale = LIOps[0];
1164 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001165 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001166 } else {
1167 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1168 std::vector<SCEVHandle> MulOps(LIOps);
1169 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001170 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001171 }
1172 }
1173
Dan Gohman246b2562007-10-22 18:31:58 +00001174 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001175
1176 // If all of the other operands were loop invariant, we are done.
1177 if (Ops.size() == 1) return NewRec;
1178
1179 // Otherwise, multiply the folded AddRec by the non-liv parts.
1180 for (unsigned i = 0;; ++i)
1181 if (Ops[i] == AddRec) {
1182 Ops[i] = NewRec;
1183 break;
1184 }
Dan Gohman246b2562007-10-22 18:31:58 +00001185 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001186 }
1187
1188 // Okay, if there weren't any loop invariants to be folded, check to see if
1189 // there are multiple AddRec's with the same loop induction variable being
1190 // multiplied together. If so, we can fold them.
1191 for (unsigned OtherIdx = Idx+1;
1192 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1193 if (OtherIdx != Idx) {
1194 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1195 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1196 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1197 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001198 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001199 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001200 SCEVHandle B = F->getStepRecurrence(*this);
1201 SCEVHandle D = G->getStepRecurrence(*this);
1202 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1203 getMulExpr(G, B),
1204 getMulExpr(B, D));
1205 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1206 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001207 if (Ops.size() == 2) return NewAddRec;
1208
1209 Ops.erase(Ops.begin()+Idx);
1210 Ops.erase(Ops.begin()+OtherIdx-1);
1211 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001212 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001213 }
1214 }
1215
1216 // Otherwise couldn't fold anything into this recurrence. Move onto the
1217 // next one.
1218 }
1219
1220 // Okay, it looks like we really DO need an mul expr. Check to see if we
1221 // already have one, otherwise create a new one.
1222 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001223 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1224 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001225 if (Result == 0)
1226 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001227 return Result;
1228}
1229
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001230SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001231 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1232 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001233 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001234
1235 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1236 Constant *LHSCV = LHSC->getValue();
1237 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001238 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001239 }
1240 }
1241
Nick Lewycky789558d2009-01-13 09:18:58 +00001242 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1243
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001244 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1245 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001246 return Result;
1247}
1248
1249
1250/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1251/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001252SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001253 const SCEVHandle &Step, const Loop *L) {
1254 std::vector<SCEVHandle> Operands;
1255 Operands.push_back(Start);
1256 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1257 if (StepChrec->getLoop() == L) {
1258 Operands.insert(Operands.end(), StepChrec->op_begin(),
1259 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001260 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001261 }
1262
1263 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001264 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001265}
1266
1267/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1268/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001269SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001270 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001271 if (Operands.size() == 1) return Operands[0];
1272
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001273 if (Operands.back()->isZero()) {
1274 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001275 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001276 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001277
Dan Gohmand9cc7492008-08-08 18:33:12 +00001278 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1279 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1280 const Loop* NestedLoop = NestedAR->getLoop();
1281 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1282 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1283 NestedAR->op_end());
1284 SCEVHandle NestedARHandle(NestedAR);
1285 Operands[0] = NestedAR->getStart();
1286 NestedOperands[0] = getAddRecExpr(Operands, L);
1287 return getAddRecExpr(NestedOperands, NestedLoop);
1288 }
1289 }
1290
Chris Lattner53e677a2004-04-02 20:23:17 +00001291 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001292 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1293 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001294 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1295 return Result;
1296}
1297
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001298SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1299 const SCEVHandle &RHS) {
1300 std::vector<SCEVHandle> Ops;
1301 Ops.push_back(LHS);
1302 Ops.push_back(RHS);
1303 return getSMaxExpr(Ops);
1304}
1305
1306SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1307 assert(!Ops.empty() && "Cannot get empty smax!");
1308 if (Ops.size() == 1) return Ops[0];
1309
1310 // Sort by complexity, this groups all similar expression types together.
1311 GroupByComplexity(Ops);
1312
1313 // If there are any constants, fold them together.
1314 unsigned Idx = 0;
1315 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1316 ++Idx;
1317 assert(Idx < Ops.size());
1318 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1319 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001320 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001321 APIntOps::smax(LHSC->getValue()->getValue(),
1322 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001323 Ops[0] = getConstant(Fold);
1324 Ops.erase(Ops.begin()+1); // Erase the folded element
1325 if (Ops.size() == 1) return Ops[0];
1326 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001327 }
1328
1329 // If we are left with a constant -inf, strip it off.
1330 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1331 Ops.erase(Ops.begin());
1332 --Idx;
1333 }
1334 }
1335
1336 if (Ops.size() == 1) return Ops[0];
1337
1338 // Find the first SMax
1339 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1340 ++Idx;
1341
1342 // Check to see if one of the operands is an SMax. If so, expand its operands
1343 // onto our operand list, and recurse to simplify.
1344 if (Idx < Ops.size()) {
1345 bool DeletedSMax = false;
1346 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1347 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1348 Ops.erase(Ops.begin()+Idx);
1349 DeletedSMax = true;
1350 }
1351
1352 if (DeletedSMax)
1353 return getSMaxExpr(Ops);
1354 }
1355
1356 // Okay, check to see if the same value occurs in the operand list twice. If
1357 // so, delete one. Since we sorted the list, these values are required to
1358 // be adjacent.
1359 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1360 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1361 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1362 --i; --e;
1363 }
1364
1365 if (Ops.size() == 1) return Ops[0];
1366
1367 assert(!Ops.empty() && "Reduced smax down to nothing!");
1368
Nick Lewycky3e630762008-02-20 06:48:22 +00001369 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001370 // already have one, otherwise create a new one.
1371 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1372 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1373 SCEVOps)];
1374 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1375 return Result;
1376}
1377
Nick Lewycky3e630762008-02-20 06:48:22 +00001378SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1379 const SCEVHandle &RHS) {
1380 std::vector<SCEVHandle> Ops;
1381 Ops.push_back(LHS);
1382 Ops.push_back(RHS);
1383 return getUMaxExpr(Ops);
1384}
1385
1386SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1387 assert(!Ops.empty() && "Cannot get empty umax!");
1388 if (Ops.size() == 1) return Ops[0];
1389
1390 // Sort by complexity, this groups all similar expression types together.
1391 GroupByComplexity(Ops);
1392
1393 // If there are any constants, fold them together.
1394 unsigned Idx = 0;
1395 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1396 ++Idx;
1397 assert(Idx < Ops.size());
1398 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1399 // We found two constants, fold them together!
1400 ConstantInt *Fold = ConstantInt::get(
1401 APIntOps::umax(LHSC->getValue()->getValue(),
1402 RHSC->getValue()->getValue()));
1403 Ops[0] = getConstant(Fold);
1404 Ops.erase(Ops.begin()+1); // Erase the folded element
1405 if (Ops.size() == 1) return Ops[0];
1406 LHSC = cast<SCEVConstant>(Ops[0]);
1407 }
1408
1409 // If we are left with a constant zero, strip it off.
1410 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1411 Ops.erase(Ops.begin());
1412 --Idx;
1413 }
1414 }
1415
1416 if (Ops.size() == 1) return Ops[0];
1417
1418 // Find the first UMax
1419 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1420 ++Idx;
1421
1422 // Check to see if one of the operands is a UMax. If so, expand its operands
1423 // onto our operand list, and recurse to simplify.
1424 if (Idx < Ops.size()) {
1425 bool DeletedUMax = false;
1426 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1427 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1428 Ops.erase(Ops.begin()+Idx);
1429 DeletedUMax = true;
1430 }
1431
1432 if (DeletedUMax)
1433 return getUMaxExpr(Ops);
1434 }
1435
1436 // Okay, check to see if the same value occurs in the operand list twice. If
1437 // so, delete one. Since we sorted the list, these values are required to
1438 // be adjacent.
1439 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1440 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1441 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1442 --i; --e;
1443 }
1444
1445 if (Ops.size() == 1) return Ops[0];
1446
1447 assert(!Ops.empty() && "Reduced umax down to nothing!");
1448
1449 // Okay, it looks like we really DO need a umax expr. Check to see if we
1450 // already have one, otherwise create a new one.
1451 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1452 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1453 SCEVOps)];
1454 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1455 return Result;
1456}
1457
Dan Gohman246b2562007-10-22 18:31:58 +00001458SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001459 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001460 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001461 if (isa<ConstantPointerNull>(V))
1462 return getIntegerSCEV(0, V->getType());
Chris Lattnerb3364092006-10-04 21:49:37 +00001463 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001464 if (Result == 0) Result = new SCEVUnknown(V);
1465 return Result;
1466}
1467
Chris Lattner53e677a2004-04-02 20:23:17 +00001468//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001469// Basic SCEV Analysis and PHI Idiom Recognition Code
1470//
1471
Dan Gohman5cec4db2007-06-19 14:28:31 +00001472/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001473/// client before it removes an instruction from the program, to make sure
1474/// that no dangling references are left around.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001475void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001476 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001477
Dan Gohman5cec4db2007-06-19 14:28:31 +00001478 if (Scalars.erase(V)) {
1479 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001480 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001481 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001482 }
1483
1484 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001485 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001486 Worklist.pop_back();
1487
Dan Gohman5cec4db2007-06-19 14:28:31 +00001488 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001489 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001490 Instruction *Inst = cast<Instruction>(*UI);
1491 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001492 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001493 ConstantEvolutionLoopExitValue.erase(PN);
1494 Worklist.push_back(Inst);
1495 }
1496 }
1497 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001498}
1499
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001500/// isSCEVable - Test if values of the given type are analyzable within
1501/// the SCEV framework. This primarily includes integer types, and it
1502/// can optionally include pointer types if the ScalarEvolution class
1503/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001504bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001505 // Integers are always SCEVable.
1506 if (Ty->isInteger())
1507 return true;
1508
1509 // Pointers are SCEVable if TargetData information is available
1510 // to provide pointer size information.
1511 if (isa<PointerType>(Ty))
1512 return TD != NULL;
1513
1514 // Otherwise it's not SCEVable.
1515 return false;
1516}
1517
1518/// getTypeSizeInBits - Return the size in bits of the specified type,
1519/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001520uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001521 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1522
1523 // If we have a TargetData, use it!
1524 if (TD)
1525 return TD->getTypeSizeInBits(Ty);
1526
1527 // Otherwise, we support only integer types.
1528 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1529 return Ty->getPrimitiveSizeInBits();
1530}
1531
1532/// getEffectiveSCEVType - Return a type with the same bitwidth as
1533/// the given type and which represents how SCEV will treat the given
1534/// type, for which isSCEVable must return true. For pointer types,
1535/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001536const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001537 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1538
1539 if (Ty->isInteger())
1540 return Ty;
1541
1542 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1543 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001544}
Chris Lattner53e677a2004-04-02 20:23:17 +00001545
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001546SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001547 return UnknownValue;
1548}
1549
Torok Edwine3d12852009-05-01 08:33:47 +00001550// hasSCEV - Return true if the SCEV for this value has already been
1551/// computed.
1552bool ScalarEvolution::hasSCEV(Value *V) const {
1553 return Scalars.count(V);
1554}
1555
Chris Lattner53e677a2004-04-02 20:23:17 +00001556/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1557/// expression and create a new one.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001558SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001559 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001560
1561 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1562 if (I != Scalars.end()) return I->second;
1563 SCEVHandle S = createSCEV(V);
1564 Scalars.insert(std::make_pair(V, S));
1565 return S;
1566}
1567
Dan Gohman2d1be872009-04-16 03:18:22 +00001568/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1569/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001570SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1571 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001572 Constant *C;
1573 if (Val == 0)
1574 C = Constant::getNullValue(Ty);
1575 else if (Ty->isFloatingPoint())
1576 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1577 APFloat::IEEEdouble, Val));
1578 else
1579 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001580 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001581}
1582
1583/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1584///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001585SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001586 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001587 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001588
1589 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001590 Ty = getEffectiveSCEVType(Ty);
1591 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001592}
1593
1594/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001595SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001596 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001597 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001598
1599 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001600 Ty = getEffectiveSCEVType(Ty);
1601 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001602 return getMinusSCEV(AllOnes, V);
1603}
1604
1605/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1606///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001607SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001608 const SCEVHandle &RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001609 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001610 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001611}
1612
1613/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1614/// input value to the specified type. If the type must be extended, it is zero
1615/// extended.
1616SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001617ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001618 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001619 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001620 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1621 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001622 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001623 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001624 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001625 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001626 return getTruncateExpr(V, Ty);
1627 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001628}
1629
1630/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1631/// input value to the specified type. If the type must be extended, it is sign
1632/// extended.
1633SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001634ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001635 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001636 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001637 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1638 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001639 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001640 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001641 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001642 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001643 return getTruncateExpr(V, Ty);
1644 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001645}
1646
Chris Lattner4dc534c2005-02-13 04:37:18 +00001647/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1648/// the specified instruction and replaces any references to the symbolic value
1649/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001650void ScalarEvolution::
Chris Lattner4dc534c2005-02-13 04:37:18 +00001651ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1652 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001654 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001655
Chris Lattner4dc534c2005-02-13 04:37:18 +00001656 SCEVHandle NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001657 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001658 if (NV == SI->second) return; // No change.
1659
1660 SI->second = NV; // Update the scalars map!
1661
1662 // Any instruction values that use this instruction might also need to be
1663 // updated!
1664 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1665 UI != E; ++UI)
1666 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1667}
Chris Lattner53e677a2004-04-02 20:23:17 +00001668
1669/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1670/// a loop header, making it a potential recurrence, or it doesn't.
1671///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001672SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001673 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001674 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00001675 if (L->getHeader() == PN->getParent()) {
1676 // If it lives in the loop header, it has two incoming values, one
1677 // from outside the loop, and one from inside.
1678 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1679 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001680
Chris Lattner53e677a2004-04-02 20:23:17 +00001681 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001682 SCEVHandle SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001683 assert(Scalars.find(PN) == Scalars.end() &&
1684 "PHI node already processed?");
1685 Scalars.insert(std::make_pair(PN, SymbolicName));
1686
1687 // Using this symbolic name for the PHI, analyze the value coming around
1688 // the back-edge.
1689 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1690
1691 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1692 // has a special value for the first iteration of the loop.
1693
1694 // If the value coming around the backedge is an add with the symbolic
1695 // value we just inserted, then we found a simple induction variable!
1696 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1697 // If there is a single occurrence of the symbolic value, replace it
1698 // with a recurrence.
1699 unsigned FoundIndex = Add->getNumOperands();
1700 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1701 if (Add->getOperand(i) == SymbolicName)
1702 if (FoundIndex == e) {
1703 FoundIndex = i;
1704 break;
1705 }
1706
1707 if (FoundIndex != Add->getNumOperands()) {
1708 // Create an add with everything but the specified operand.
1709 std::vector<SCEVHandle> Ops;
1710 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1711 if (i != FoundIndex)
1712 Ops.push_back(Add->getOperand(i));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001713 SCEVHandle Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001714
1715 // This is not a valid addrec if the step amount is varying each
1716 // loop iteration, but is not itself an addrec in this loop.
1717 if (Accum->isLoopInvariant(L) ||
1718 (isa<SCEVAddRecExpr>(Accum) &&
1719 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1720 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001721 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001722
1723 // Okay, for the entire analysis of this edge we assumed the PHI
1724 // to be symbolic. We now need to go back and update all of the
1725 // entries for the scalars that use the PHI (except for the PHI
1726 // itself) to use the new analyzed value instead of the "symbolic"
1727 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001728 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001729 return PHISCEV;
1730 }
1731 }
Chris Lattner97156e72006-04-26 18:34:07 +00001732 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1733 // Otherwise, this could be a loop like this:
1734 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1735 // In this case, j = {1,+,1} and BEValue is j.
1736 // Because the other in-value of i (0) fits the evolution of BEValue
1737 // i really is an addrec evolution.
1738 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1739 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1740
1741 // If StartVal = j.start - j.stride, we can use StartVal as the
1742 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001743 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00001744 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001745 SCEVHandle PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001746 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001747
1748 // Okay, for the entire analysis of this edge we assumed the PHI
1749 // to be symbolic. We now need to go back and update all of the
1750 // entries for the scalars that use the PHI (except for the PHI
1751 // itself) to use the new analyzed value instead of the "symbolic"
1752 // value.
1753 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1754 return PHISCEV;
1755 }
1756 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001757 }
1758
1759 return SymbolicName;
1760 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001761
Chris Lattner53e677a2004-04-02 20:23:17 +00001762 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001763 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001764}
1765
Nick Lewycky83bb0052007-11-22 07:59:40 +00001766/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1767/// guaranteed to end in (at every loop iteration). It is, at the same time,
1768/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1769/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001770static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001771 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001772 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001773
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001774 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001775 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1776 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001777
1778 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001779 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1780 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1781 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001782 }
1783
1784 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001785 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1786 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1787 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001788 }
1789
Chris Lattnera17f0392006-12-12 02:26:09 +00001790 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001791 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001792 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001793 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001794 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001795 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001796 }
1797
1798 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001799 // The result is the sum of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001800 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1801 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00001802 for (unsigned i = 1, e = M->getNumOperands();
1803 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001804 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky83bb0052007-11-22 07:59:40 +00001805 BitWidth);
1806 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001807 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001808
Chris Lattnera17f0392006-12-12 02:26:09 +00001809 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001810 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001811 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001812 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001813 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001814 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001815 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001816
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001817 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1818 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001819 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001820 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001821 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001822 return MinOpRes;
1823 }
1824
Nick Lewycky3e630762008-02-20 06:48:22 +00001825 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1826 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001827 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky3e630762008-02-20 06:48:22 +00001828 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001829 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky3e630762008-02-20 06:48:22 +00001830 return MinOpRes;
1831 }
1832
Nick Lewycky789558d2009-01-13 09:18:58 +00001833 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001834 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001835}
Chris Lattner53e677a2004-04-02 20:23:17 +00001836
1837/// createSCEV - We know that there is no SCEV for the specified value.
1838/// Analyze the expression.
1839///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001840SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001841 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001842 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00001843
Dan Gohman6c459a22008-06-22 19:56:46 +00001844 unsigned Opcode = Instruction::UserOp1;
1845 if (Instruction *I = dyn_cast<Instruction>(V))
1846 Opcode = I->getOpcode();
1847 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1848 Opcode = CE->getOpcode();
1849 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001850 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001851
Dan Gohman6c459a22008-06-22 19:56:46 +00001852 User *U = cast<User>(V);
1853 switch (Opcode) {
1854 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001855 return getAddExpr(getSCEV(U->getOperand(0)),
1856 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001857 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001858 return getMulExpr(getSCEV(U->getOperand(0)),
1859 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001860 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001861 return getUDivExpr(getSCEV(U->getOperand(0)),
1862 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001863 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001864 return getMinusSCEV(getSCEV(U->getOperand(0)),
1865 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00001866 case Instruction::And:
1867 // For an expression like x&255 that merely masks off the high bits,
1868 // use zext(trunc(x)) as the SCEV expression.
1869 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001870 if (CI->isNullValue())
1871 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00001872 if (CI->isAllOnesValue())
1873 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00001874 const APInt &A = CI->getValue();
1875 unsigned Ones = A.countTrailingOnes();
1876 if (APIntOps::isMask(Ones, A))
1877 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001878 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1879 IntegerType::get(Ones)),
1880 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00001881 }
1882 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00001883 case Instruction::Or:
1884 // If the RHS of the Or is a constant, we may have something like:
1885 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1886 // optimizations will transparently handle this case.
1887 //
1888 // In order for this transformation to be safe, the LHS must be of the
1889 // form X*(2^n) and the Or constant must be less than 2^n.
1890 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1891 SCEVHandle LHS = getSCEV(U->getOperand(0));
1892 const APInt &CIVal = CI->getValue();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001893 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00001894 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001895 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001896 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001897 break;
1898 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001899 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001900 // If the RHS of the xor is a signbit, then this is just an add.
1901 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001902 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001903 return getAddExpr(getSCEV(U->getOperand(0)),
1904 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001905
1906 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001907 else if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001908 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001909 }
1910 break;
1911
1912 case Instruction::Shl:
1913 // Turn shift left of a constant amount into a multiply.
1914 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1915 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1916 Constant *X = ConstantInt::get(
1917 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001918 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00001919 }
1920 break;
1921
Nick Lewycky01eaf802008-07-07 06:15:49 +00001922 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00001923 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001924 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1925 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1926 Constant *X = ConstantInt::get(
1927 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001928 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001929 }
1930 break;
1931
Dan Gohman4ee29af2009-04-21 02:26:00 +00001932 case Instruction::AShr:
1933 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1934 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1935 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1936 if (L->getOpcode() == Instruction::Shl &&
1937 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001938 unsigned BitWidth = getTypeSizeInBits(U->getType());
1939 uint64_t Amt = BitWidth - CI->getZExtValue();
1940 if (Amt == BitWidth)
1941 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1942 if (Amt > BitWidth)
1943 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00001944 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001945 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001946 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00001947 U->getType());
1948 }
1949 break;
1950
Dan Gohman6c459a22008-06-22 19:56:46 +00001951 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001952 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001953
1954 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001955 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001956
1957 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001958 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001959
1960 case Instruction::BitCast:
1961 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001962 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00001963 return getSCEV(U->getOperand(0));
1964 break;
1965
Dan Gohman2d1be872009-04-16 03:18:22 +00001966 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001967 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00001968 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001969 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00001970
1971 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001972 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00001973 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1974 U->getType());
1975
1976 case Instruction::GetElementPtr: {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001977 if (!TD) break; // Without TD we can't analyze pointers.
1978 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001979 Value *Base = U->getOperand(0);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001980 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman2d1be872009-04-16 03:18:22 +00001981 gep_type_iterator GTI = gep_type_begin(U);
1982 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1983 E = U->op_end();
1984 I != E; ++I) {
1985 Value *Index = *I;
1986 // Compute the (potentially symbolic) offset in bytes for this index.
1987 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1988 // For a struct, add the member offset.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001989 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman2d1be872009-04-16 03:18:22 +00001990 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1991 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001992 TotalOffset = getAddExpr(TotalOffset,
1993 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman2d1be872009-04-16 03:18:22 +00001994 } else {
1995 // For an array, add the element offset, explicitly scaled.
1996 SCEVHandle LocalOffset = getSCEV(Index);
1997 if (!isa<PointerType>(LocalOffset->getType()))
1998 // Getelementptr indicies are signed.
1999 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2000 IntPtrTy);
2001 LocalOffset =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002002 getMulExpr(LocalOffset,
2003 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2004 IntPtrTy));
2005 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman2d1be872009-04-16 03:18:22 +00002006 }
2007 }
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002008 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman2d1be872009-04-16 03:18:22 +00002009 }
2010
Dan Gohman6c459a22008-06-22 19:56:46 +00002011 case Instruction::PHI:
2012 return createNodeForPHI(cast<PHINode>(U));
2013
2014 case Instruction::Select:
2015 // This could be a smax or umax that was lowered earlier.
2016 // Try to recover it.
2017 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2018 Value *LHS = ICI->getOperand(0);
2019 Value *RHS = ICI->getOperand(1);
2020 switch (ICI->getPredicate()) {
2021 case ICmpInst::ICMP_SLT:
2022 case ICmpInst::ICMP_SLE:
2023 std::swap(LHS, RHS);
2024 // fall through
2025 case ICmpInst::ICMP_SGT:
2026 case ICmpInst::ICMP_SGE:
2027 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002028 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002029 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00002030 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002031 return getNotSCEV(getSMaxExpr(
2032 getNotSCEV(getSCEV(LHS)),
2033 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002034 break;
2035 case ICmpInst::ICMP_ULT:
2036 case ICmpInst::ICMP_ULE:
2037 std::swap(LHS, RHS);
2038 // fall through
2039 case ICmpInst::ICMP_UGT:
2040 case ICmpInst::ICMP_UGE:
2041 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002042 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002043 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2044 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002045 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2046 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002047 break;
2048 default:
2049 break;
2050 }
2051 }
2052
2053 default: // We cannot analyze this expression.
2054 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002055 }
2056
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002057 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002058}
2059
2060
2061
2062//===----------------------------------------------------------------------===//
2063// Iteration Count Computation Code
2064//
2065
Dan Gohman46bdfb02009-02-24 18:55:53 +00002066/// getBackedgeTakenCount - If the specified loop has a predictable
2067/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2068/// object. The backedge-taken count is the number of times the loop header
2069/// will be branched to from within the loop. This is one less than the
2070/// trip count of the loop, since it doesn't count the first iteration,
2071/// when the header is branched to from outside the loop.
2072///
2073/// Note that it is not valid to call this method on a loop without a
2074/// loop-invariant backedge-taken count (see
2075/// hasLoopInvariantBackedgeTakenCount).
2076///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002077SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002078 return getBackedgeTakenInfo(L).Exact;
2079}
2080
2081/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2082/// return the least SCEV value that is known never to be less than the
2083/// actual backedge taken count.
2084SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2085 return getBackedgeTakenInfo(L).Max;
2086}
2087
2088const ScalarEvolution::BackedgeTakenInfo &
2089ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002090 // Initially insert a CouldNotCompute for this loop. If the insertion
2091 // succeeds, procede to actually compute a backedge-taken count and
2092 // update the value. The temporary CouldNotCompute value tells SCEV
2093 // code elsewhere that it shouldn't attempt to request a new
2094 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002095 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002096 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2097 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002098 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2099 if (ItCount.Exact != UnknownValue) {
2100 assert(ItCount.Exact->isLoopInvariant(L) &&
2101 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002102 "Computed trip count isn't loop invariant for loop!");
2103 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002104
Dan Gohman01ecca22009-04-27 20:16:15 +00002105 // Update the value in the map.
2106 Pair.first->second = ItCount;
Chris Lattner53e677a2004-04-02 20:23:17 +00002107 } else if (isa<PHINode>(L->getHeader()->begin())) {
2108 // Only count loops that have phi nodes as not being computable.
2109 ++NumTripCountsNotComputed;
2110 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002111
2112 // Now that we know more about the trip count for this loop, forget any
2113 // existing SCEV values for PHI nodes in this loop since they are only
2114 // conservative estimates made without the benefit
2115 // of trip count information.
2116 if (ItCount.hasAnyInfo())
2117 for (BasicBlock::iterator I = L->getHeader()->begin();
2118 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2119 deleteValueFromRecords(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002120 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002121 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002122}
2123
Dan Gohman46bdfb02009-02-24 18:55:53 +00002124/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002125/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002126/// ScalarEvolution's ability to compute a trip count, or if the loop
2127/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002128void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002129 BackedgeTakenCounts.erase(L);
Dan Gohman60f8a632009-02-17 20:49:49 +00002130}
2131
Dan Gohman46bdfb02009-02-24 18:55:53 +00002132/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2133/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002134ScalarEvolution::BackedgeTakenInfo
2135ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002136 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00002137 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002138 L->getExitBlocks(ExitBlocks);
2139 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002140
2141 // Okay, there is one exit block. Try to find the condition that causes the
2142 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002143 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00002144
2145 BasicBlock *ExitingBlock = 0;
2146 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2147 PI != E; ++PI)
2148 if (L->contains(*PI)) {
2149 if (ExitingBlock == 0)
2150 ExitingBlock = *PI;
2151 else
2152 return UnknownValue; // More than one block exiting!
2153 }
2154 assert(ExitingBlock && "No exits from loop, something is broken!");
2155
2156 // Okay, we've computed the exiting block. See what condition causes us to
2157 // exit.
2158 //
2159 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002160 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2161 if (ExitBr == 0) return UnknownValue;
2162 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002163
2164 // At this point, we know we have a conditional branch that determines whether
2165 // the loop is exited. However, we don't know if the branch is executed each
2166 // time through the loop. If not, then the execution count of the branch will
2167 // not be equal to the trip count of the loop.
2168 //
2169 // Currently we check for this by checking to see if the Exit branch goes to
2170 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002171 // times as the loop. We also handle the case where the exit block *is* the
2172 // loop header. This is common for un-rotated loops. More extensive analysis
2173 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002174 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002175 ExitBr->getSuccessor(1) != L->getHeader() &&
2176 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00002177 return UnknownValue;
2178
Reid Spencere4d87aa2006-12-23 06:05:41 +00002179 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2180
Nick Lewycky3b711652008-02-21 08:34:02 +00002181 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002182 // Note that ICmpInst deals with pointer comparisons too so we must check
2183 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002184 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman46bdfb02009-02-24 18:55:53 +00002185 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Chris Lattner7980fb92004-04-17 18:36:24 +00002186 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002187
Reid Spencere4d87aa2006-12-23 06:05:41 +00002188 // If the condition was exit on true, convert the condition to exit on false
2189 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002190 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002191 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002192 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002193 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002194
2195 // Handle common loops like: for (X = "string"; *X; ++X)
2196 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2197 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2198 SCEVHandle ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002199 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Chris Lattner673e02b2004-10-12 01:49:27 +00002200 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2201 }
2202
Chris Lattner53e677a2004-04-02 20:23:17 +00002203 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2204 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2205
2206 // Try to evaluate any dependencies out of the loop.
2207 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2208 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2209 Tmp = getSCEVAtScope(RHS, L);
2210 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2211
Reid Spencere4d87aa2006-12-23 06:05:41 +00002212 // At this point, we would like to compute how many iterations of the
2213 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002214 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2215 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002216 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002217 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002218 }
2219
Chris Lattner53e677a2004-04-02 20:23:17 +00002220 // If we have a comparison of a chrec against a constant, try to use value
2221 // ranges to answer this query.
2222 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2223 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2224 if (AddRec->getLoop() == L) {
2225 // Form the comparison range using the constant of the correct type so
2226 // that the ConstantRange class knows to do a signed or unsigned
2227 // comparison.
2228 ConstantInt *CompVal = RHSC->getValue();
2229 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002230 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002231 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002232 if (CompVal) {
2233 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002234 ConstantRange CompRange(
2235 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002236
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002237 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002238 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2239 }
2240 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002241
Chris Lattner53e677a2004-04-02 20:23:17 +00002242 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002243 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002244 // Convert to: while (X-Y != 0)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002245 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002246 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002247 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002248 }
2249 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002250 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002251 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002252 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002253 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002254 }
2255 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002256 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2257 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002258 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002259 }
2260 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002261 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2262 getNotSCEV(RHS), L, true);
2263 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002264 break;
2265 }
2266 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002267 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2268 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002269 break;
2270 }
2271 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002272 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2273 getNotSCEV(RHS), L, false);
2274 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002275 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002276 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002277 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002278#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002279 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002280 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002281 errs() << "[unsigned] ";
2282 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002283 << Instruction::getOpcodeName(Instruction::ICmp)
2284 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002285#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002286 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002287 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00002288 return
2289 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2290 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002291}
2292
Chris Lattner673e02b2004-10-12 01:49:27 +00002293static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002294EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2295 ScalarEvolution &SE) {
2296 SCEVHandle InVal = SE.getConstant(C);
2297 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002298 assert(isa<SCEVConstant>(Val) &&
2299 "Evaluation of SCEV at constant didn't fold correctly?");
2300 return cast<SCEVConstant>(Val)->getValue();
2301}
2302
2303/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2304/// and a GEP expression (missing the pointer index) indexing into it, return
2305/// the addressed element of the initializer or null if the index expression is
2306/// invalid.
2307static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002308GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002309 const std::vector<ConstantInt*> &Indices) {
2310 Constant *Init = GV->getInitializer();
2311 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002312 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002313 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2314 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2315 Init = cast<Constant>(CS->getOperand(Idx));
2316 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2317 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2318 Init = cast<Constant>(CA->getOperand(Idx));
2319 } else if (isa<ConstantAggregateZero>(Init)) {
2320 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2321 assert(Idx < STy->getNumElements() && "Bad struct index!");
2322 Init = Constant::getNullValue(STy->getElementType(Idx));
2323 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2324 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2325 Init = Constant::getNullValue(ATy->getElementType());
2326 } else {
2327 assert(0 && "Unknown constant aggregate type!");
2328 }
2329 return 0;
2330 } else {
2331 return 0; // Unknown initializer type
2332 }
2333 }
2334 return Init;
2335}
2336
Dan Gohman46bdfb02009-02-24 18:55:53 +00002337/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2338/// 'icmp op load X, cst', try to see if we can compute the backedge
2339/// execution count.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002340SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002341ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2342 const Loop *L,
2343 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002344 if (LI->isVolatile()) return UnknownValue;
2345
2346 // Check to see if the loaded pointer is a getelementptr of a global.
2347 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2348 if (!GEP) return UnknownValue;
2349
2350 // Make sure that it is really a constant global we are gepping, with an
2351 // initializer, and make sure the first IDX is really 0.
2352 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2353 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2354 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2355 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2356 return UnknownValue;
2357
2358 // Okay, we allow one non-constant index into the GEP instruction.
2359 Value *VarIdx = 0;
2360 std::vector<ConstantInt*> Indexes;
2361 unsigned VarIdxNum = 0;
2362 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2363 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2364 Indexes.push_back(CI);
2365 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2366 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2367 VarIdx = GEP->getOperand(i);
2368 VarIdxNum = i-2;
2369 Indexes.push_back(0);
2370 }
2371
2372 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2373 // Check to see if X is a loop variant variable value now.
2374 SCEVHandle Idx = getSCEV(VarIdx);
2375 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2376 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2377
2378 // We can only recognize very limited forms of loop index expressions, in
2379 // particular, only affine AddRec's like {C1,+,C2}.
2380 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2381 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2382 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2383 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2384 return UnknownValue;
2385
2386 unsigned MaxSteps = MaxBruteForceIterations;
2387 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002388 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002389 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002390 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00002391
2392 // Form the GEP offset.
2393 Indexes[VarIdxNum] = Val;
2394
2395 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2396 if (Result == 0) break; // Cannot compute!
2397
2398 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002399 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002400 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002401 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002402#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002403 errs() << "\n***\n*** Computed loop count " << *ItCst
2404 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2405 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002406#endif
2407 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002408 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002409 }
2410 }
2411 return UnknownValue;
2412}
2413
2414
Chris Lattner3221ad02004-04-17 22:58:41 +00002415/// CanConstantFold - Return true if we can constant fold an instruction of the
2416/// specified type, assuming that all operands were constants.
2417static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002418 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002419 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2420 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002421
Chris Lattner3221ad02004-04-17 22:58:41 +00002422 if (const CallInst *CI = dyn_cast<CallInst>(I))
2423 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002424 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002425 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002426}
2427
Chris Lattner3221ad02004-04-17 22:58:41 +00002428/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2429/// in the loop that V is derived from. We allow arbitrary operations along the
2430/// way, but the operands of an operation must either be constants or a value
2431/// derived from a constant PHI. If this expression does not fit with these
2432/// constraints, return null.
2433static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2434 // If this is not an instruction, or if this is an instruction outside of the
2435 // loop, it can't be derived from a loop PHI.
2436 Instruction *I = dyn_cast<Instruction>(V);
2437 if (I == 0 || !L->contains(I->getParent())) return 0;
2438
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002439 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002440 if (L->getHeader() == I->getParent())
2441 return PN;
2442 else
2443 // We don't currently keep track of the control flow needed to evaluate
2444 // PHIs, so we cannot handle PHIs inside of loops.
2445 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002446 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002447
2448 // If we won't be able to constant fold this expression even if the operands
2449 // are constants, return early.
2450 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002451
Chris Lattner3221ad02004-04-17 22:58:41 +00002452 // Otherwise, we can evaluate this instruction if all of its operands are
2453 // constant or derived from a PHI node themselves.
2454 PHINode *PHI = 0;
2455 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2456 if (!(isa<Constant>(I->getOperand(Op)) ||
2457 isa<GlobalValue>(I->getOperand(Op)))) {
2458 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2459 if (P == 0) return 0; // Not evolving from PHI
2460 if (PHI == 0)
2461 PHI = P;
2462 else if (PHI != P)
2463 return 0; // Evolving from multiple different PHIs.
2464 }
2465
2466 // This is a expression evolving from a constant PHI!
2467 return PHI;
2468}
2469
2470/// EvaluateExpression - Given an expression that passes the
2471/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2472/// in the loop has the value PHIVal. If we can't fold this expression for some
2473/// reason, return null.
2474static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2475 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002476 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00002477 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00002478 Instruction *I = cast<Instruction>(V);
2479
2480 std::vector<Constant*> Operands;
2481 Operands.resize(I->getNumOperands());
2482
2483 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2484 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2485 if (Operands[i] == 0) return 0;
2486 }
2487
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002488 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2489 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2490 &Operands[0], Operands.size());
2491 else
2492 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2493 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002494}
2495
2496/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2497/// in the header of its containing loop, we know the loop executes a
2498/// constant number of times, and the PHI node is just a recurrence
2499/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002500Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002501getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002502 std::map<PHINode*, Constant*>::iterator I =
2503 ConstantEvolutionLoopExitValue.find(PN);
2504 if (I != ConstantEvolutionLoopExitValue.end())
2505 return I->second;
2506
Dan Gohman46bdfb02009-02-24 18:55:53 +00002507 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002508 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2509
2510 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2511
2512 // Since the loop is canonicalized, the PHI node must have two entries. One
2513 // entry must be a constant (coming in from outside of the loop), and the
2514 // second must be derived from the same PHI.
2515 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2516 Constant *StartCST =
2517 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2518 if (StartCST == 0)
2519 return RetVal = 0; // Must be a constant.
2520
2521 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2522 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2523 if (PN2 != PN)
2524 return RetVal = 0; // Not derived from same PHI.
2525
2526 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002527 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00002528 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002529
Dan Gohman46bdfb02009-02-24 18:55:53 +00002530 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00002531 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002532 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2533 if (IterationNum == NumIterations)
2534 return RetVal = PHIVal; // Got exit value!
2535
2536 // Compute the value of the PHI node for the next iteration.
2537 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2538 if (NextPHI == PHIVal)
2539 return RetVal = NextPHI; // Stopped evolving!
2540 if (NextPHI == 0)
2541 return 0; // Couldn't evaluate!
2542 PHIVal = NextPHI;
2543 }
2544}
2545
Dan Gohman46bdfb02009-02-24 18:55:53 +00002546/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00002547/// constant number of times (the condition evolves only from constants),
2548/// try to evaluate a few iterations of the loop until we get the exit
2549/// condition gets a value of ExitWhen (true or false). If we cannot
2550/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002551SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002552ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00002553 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2554 if (PN == 0) return UnknownValue;
2555
2556 // Since the loop is canonicalized, the PHI node must have two entries. One
2557 // entry must be a constant (coming in from outside of the loop), and the
2558 // second must be derived from the same PHI.
2559 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2560 Constant *StartCST =
2561 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2562 if (StartCST == 0) return UnknownValue; // Must be a constant.
2563
2564 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2565 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2566 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2567
2568 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2569 // the loop symbolically to determine when the condition gets a value of
2570 // "ExitWhen".
2571 unsigned IterationNum = 0;
2572 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2573 for (Constant *PHIVal = StartCST;
2574 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002575 ConstantInt *CondVal =
2576 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002577
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002578 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002579 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002580
Reid Spencere8019bb2007-03-01 07:25:48 +00002581 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002582 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002583 ++NumBruteForceTripCountsComputed;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002584 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002585 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002586
Chris Lattner3221ad02004-04-17 22:58:41 +00002587 // Compute the value of the PHI node for the next iteration.
2588 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2589 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002590 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002591 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002592 }
2593
2594 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002595 return UnknownValue;
2596}
2597
2598/// getSCEVAtScope - Compute the value of the specified expression within the
2599/// indicated loop (which may be null to indicate in no loop). If the
2600/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002601SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002602 // FIXME: this should be turned into a virtual method on SCEV!
2603
Chris Lattner3221ad02004-04-17 22:58:41 +00002604 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002605
Nick Lewycky3e630762008-02-20 06:48:22 +00002606 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002607 // exit value from the loop without using SCEVs.
2608 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2609 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002610 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00002611 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2612 if (PHINode *PN = dyn_cast<PHINode>(I))
2613 if (PN->getParent() == LI->getHeader()) {
2614 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00002615 // to see if the loop that contains it has a known backedge-taken
2616 // count. If so, we may be able to force computation of the exit
2617 // value.
2618 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2619 if (SCEVConstant *BTCC =
2620 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002621 // Okay, we know how many times the containing loop executes. If
2622 // this is a constant evolving PHI node, get the final value at
2623 // the specified iteration number.
2624 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00002625 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002626 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002627 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002628 }
2629 }
2630
Reid Spencer09906f32006-12-04 21:33:23 +00002631 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002632 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002633 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002634 // result. This is particularly useful for computing loop exit values.
2635 if (CanConstantFold(I)) {
2636 std::vector<Constant*> Operands;
2637 Operands.reserve(I->getNumOperands());
2638 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2639 Value *Op = I->getOperand(i);
2640 if (Constant *C = dyn_cast<Constant>(Op)) {
2641 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002642 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002643 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00002644 // non-integer and non-pointer, don't even try to analyze them
2645 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00002646 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00002647 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00002648
Chris Lattner3221ad02004-04-17 22:58:41 +00002649 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman4acd12a2009-04-30 16:40:30 +00002650 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
2651 Constant *C = SC->getValue();
2652 if (C->getType() != Op->getType())
2653 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2654 Op->getType(),
2655 false),
2656 C, Op->getType());
2657 Operands.push_back(C);
2658 } else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2659 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2660 if (C->getType() != Op->getType())
2661 C =
2662 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2663 Op->getType(),
2664 false),
2665 C, Op->getType());
2666 Operands.push_back(C);
2667 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00002668 return V;
2669 } else {
2670 return V;
2671 }
2672 }
2673 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002674
2675 Constant *C;
2676 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2677 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2678 &Operands[0], Operands.size());
2679 else
2680 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2681 &Operands[0], Operands.size());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002682 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002683 }
2684 }
2685
2686 // This is some other type of SCEVUnknown, just return it.
2687 return V;
2688 }
2689
Chris Lattner53e677a2004-04-02 20:23:17 +00002690 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2691 // Avoid performing the look-up in the common case where the specified
2692 // expression has no loop-variant portions.
2693 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2694 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2695 if (OpAtScope != Comm->getOperand(i)) {
2696 if (OpAtScope == UnknownValue) return UnknownValue;
2697 // Okay, at least one of these operands is loop variant but might be
2698 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002699 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002700 NewOps.push_back(OpAtScope);
2701
2702 for (++i; i != e; ++i) {
2703 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2704 if (OpAtScope == UnknownValue) return UnknownValue;
2705 NewOps.push_back(OpAtScope);
2706 }
2707 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002708 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002709 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002710 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002711 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002712 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002713 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002714 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002715 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002716 }
2717 }
2718 // If we got here, all operands are loop invariant.
2719 return Comm;
2720 }
2721
Nick Lewycky789558d2009-01-13 09:18:58 +00002722 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2723 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002724 if (LHS == UnknownValue) return LHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002725 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002726 if (RHS == UnknownValue) return RHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002727 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2728 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002729 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002730 }
2731
2732 // If this is a loop recurrence for a loop that does not contain L, then we
2733 // are dealing with the final value computed by the loop.
2734 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2735 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2736 // To evaluate this recurrence, we need to know how many times the AddRec
2737 // loop iterates. Compute this now.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002738 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2739 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002740
Eli Friedmanb42a6262008-08-04 23:49:06 +00002741 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002742 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002743 }
2744 return UnknownValue;
2745 }
2746
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002747 if (SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
2748 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2749 if (Op == UnknownValue) return Op;
2750 if (Op == Cast->getOperand())
2751 return Cast; // must be loop invariant
2752 return getZeroExtendExpr(Op, Cast->getType());
2753 }
2754
2755 if (SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
2756 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2757 if (Op == UnknownValue) return Op;
2758 if (Op == Cast->getOperand())
2759 return Cast; // must be loop invariant
2760 return getSignExtendExpr(Op, Cast->getType());
2761 }
2762
2763 if (SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
2764 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2765 if (Op == UnknownValue) return Op;
2766 if (Op == Cast->getOperand())
2767 return Cast; // must be loop invariant
2768 return getTruncateExpr(Op, Cast->getType());
2769 }
2770
2771 assert(0 && "Unknown SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002772}
2773
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002774/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2775/// at the specified scope in the program. The L value specifies a loop
2776/// nest to evaluate the expression at, where null is the top-level or a
2777/// specified loop is immediately inside of the loop.
2778///
2779/// This method can be used to compute the exit value for a variable defined
2780/// in a loop by querying what the value will hold in the parent loop.
2781///
2782/// If this value is not computable at this scope, a SCEVCouldNotCompute
2783/// object is returned.
2784SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2785 return getSCEVAtScope(getSCEV(V), L);
2786}
2787
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002788/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2789/// following equation:
2790///
2791/// A * X = B (mod N)
2792///
2793/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2794/// A and B isn't important.
2795///
2796/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2797static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2798 ScalarEvolution &SE) {
2799 uint32_t BW = A.getBitWidth();
2800 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2801 assert(A != 0 && "A must be non-zero.");
2802
2803 // 1. D = gcd(A, N)
2804 //
2805 // The gcd of A and N may have only one prime factor: 2. The number of
2806 // trailing zeros in A is its multiplicity
2807 uint32_t Mult2 = A.countTrailingZeros();
2808 // D = 2^Mult2
2809
2810 // 2. Check if B is divisible by D.
2811 //
2812 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2813 // is not less than multiplicity of this prime factor for D.
2814 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002815 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002816
2817 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2818 // modulo (N / D).
2819 //
2820 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2821 // bit width during computations.
2822 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2823 APInt Mod(BW + 1, 0);
2824 Mod.set(BW - Mult2); // Mod = N / D
2825 APInt I = AD.multiplicativeInverse(Mod);
2826
2827 // 4. Compute the minimum unsigned root of the equation:
2828 // I * (B / D) mod (N / D)
2829 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2830
2831 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2832 // bits.
2833 return SE.getConstant(Result.trunc(BW));
2834}
Chris Lattner53e677a2004-04-02 20:23:17 +00002835
2836/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2837/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2838/// might be the same) or two SCEVCouldNotCompute objects.
2839///
2840static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002841SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002842 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002843 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2844 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2845 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002846
Chris Lattner53e677a2004-04-02 20:23:17 +00002847 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002848 if (!LC || !MC || !NC) {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002849 SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00002850 return std::make_pair(CNC, CNC);
2851 }
2852
Reid Spencere8019bb2007-03-01 07:25:48 +00002853 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002854 const APInt &L = LC->getValue()->getValue();
2855 const APInt &M = MC->getValue()->getValue();
2856 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002857 APInt Two(BitWidth, 2);
2858 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002859
Reid Spencere8019bb2007-03-01 07:25:48 +00002860 {
2861 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002862 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002863 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2864 // The B coefficient is M-N/2
2865 APInt B(M);
2866 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002867
Reid Spencere8019bb2007-03-01 07:25:48 +00002868 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002869 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002870
Reid Spencere8019bb2007-03-01 07:25:48 +00002871 // Compute the B^2-4ac term.
2872 APInt SqrtTerm(B);
2873 SqrtTerm *= B;
2874 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002875
Reid Spencere8019bb2007-03-01 07:25:48 +00002876 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2877 // integer value or else APInt::sqrt() will assert.
2878 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002879
Reid Spencere8019bb2007-03-01 07:25:48 +00002880 // Compute the two solutions for the quadratic formula.
2881 // The divisions must be performed as signed divisions.
2882 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002883 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002884 if (TwoA.isMinValue()) {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002885 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002886 return std::make_pair(CNC, CNC);
2887 }
2888
Reid Spencere8019bb2007-03-01 07:25:48 +00002889 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2890 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002891
Dan Gohman246b2562007-10-22 18:31:58 +00002892 return std::make_pair(SE.getConstant(Solution1),
2893 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002894 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002895}
2896
2897/// HowFarToZero - Return the number of times a backedge comparing the specified
2898/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002899SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002900 // If the value is a constant
2901 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2902 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002903 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002904 return UnknownValue; // Otherwise it will loop infinitely.
2905 }
2906
2907 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2908 if (!AddRec || AddRec->getLoop() != L)
2909 return UnknownValue;
2910
2911 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002912 // If this is an affine expression, the execution count of this branch is
2913 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002914 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002915 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002916 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002917 // equivalent to:
2918 //
2919 // Step*N = -Start (mod 2^BW)
2920 //
2921 // where BW is the common bit width of Start and Step.
2922
Chris Lattner53e677a2004-04-02 20:23:17 +00002923 // Get the initial value for the loop.
2924 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002925 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002926
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002927 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002928
Chris Lattner53e677a2004-04-02 20:23:17 +00002929 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002930 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002931
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002932 // First, handle unitary steps.
2933 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002934 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002935 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2936 return Start; // N = Start (as unsigned)
2937
2938 // Then, try to solve the above equation provided that Start is constant.
2939 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2940 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002941 -StartC->getValue()->getValue(),
2942 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002943 }
Chris Lattner42a75512007-01-15 02:27:26 +00002944 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002945 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2946 // the quadratic equation to solve it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002947 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2948 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002949 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2950 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2951 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002952#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002953 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2954 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002955#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002956 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002957 if (ConstantInt *CB =
2958 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002959 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002960 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002961 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002962
Chris Lattner53e677a2004-04-02 20:23:17 +00002963 // We can only use this value if the chrec ends up with an exact zero
2964 // value at this index. When solving for "X*X != 5", for example, we
2965 // should not accept a root of 2.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002966 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002967 if (Val->isZero())
2968 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002969 }
2970 }
2971 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002972
Chris Lattner53e677a2004-04-02 20:23:17 +00002973 return UnknownValue;
2974}
2975
2976/// HowFarToNonZero - Return the number of times a backedge checking the
2977/// specified value for nonzero will execute. If not computable, return
2978/// UnknownValue
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002979SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002980 // Loops that look like: while (X == 0) are very strange indeed. We don't
2981 // handle them yet except for the trivial case. This could be expanded in the
2982 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002983
Chris Lattner53e677a2004-04-02 20:23:17 +00002984 // If the value is a constant, check to see if it is known to be non-zero
2985 // already. If so, the backedge will execute zero times.
2986 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002987 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002988 return getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002989 return UnknownValue; // Otherwise it will loop infinitely.
2990 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002991
Chris Lattner53e677a2004-04-02 20:23:17 +00002992 // We could implement others, but I really doubt anyone writes loops like
2993 // this, and if they did, they would already be constant folded.
2994 return UnknownValue;
2995}
2996
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002997/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2998/// (which may not be an immediate predecessor) which has exactly one
2999/// successor from which BB is reachable, or null if no such block is
3000/// found.
3001///
3002BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003003ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003004 // If the block has a unique predecessor, then there is no path from the
3005 // predecessor to the block that does not go through the direct edge
3006 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003007 if (BasicBlock *Pred = BB->getSinglePredecessor())
3008 return Pred;
3009
3010 // A loop's header is defined to be a block that dominates the loop.
3011 // If the loop has a preheader, it must be a block that has exactly
3012 // one successor that can reach BB. This is slightly more strict
3013 // than necessary, but works if critical edges are split.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003014 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003015 return L->getLoopPreheader();
3016
3017 return 0;
3018}
3019
Dan Gohmanc2390b12009-02-12 22:19:27 +00003020/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003021/// a conditional between LHS and RHS. This is used to help avoid max
3022/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003023bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003024 ICmpInst::Predicate Pred,
3025 SCEV *LHS, SCEV *RHS) {
Nick Lewycky59cff122008-07-12 07:41:32 +00003026 BasicBlock *Preheader = L->getLoopPreheader();
3027 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003028
Dan Gohman38372182008-08-12 20:17:31 +00003029 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003030 // there are predecessors that can be found that have unique successors
3031 // leading to the original header.
3032 for (; Preheader;
3033 PreheaderDest = Preheader,
3034 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00003035
3036 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00003037 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003038 if (!LoopEntryPredicate ||
3039 LoopEntryPredicate->isUnconditional())
3040 continue;
3041
3042 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3043 if (!ICI) continue;
3044
3045 // Now that we found a conditional branch that dominates the loop, check to
3046 // see if it is the comparison we are looking for.
3047 Value *PreCondLHS = ICI->getOperand(0);
3048 Value *PreCondRHS = ICI->getOperand(1);
3049 ICmpInst::Predicate Cond;
3050 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3051 Cond = ICI->getPredicate();
3052 else
3053 Cond = ICI->getInversePredicate();
3054
Dan Gohmanc2390b12009-02-12 22:19:27 +00003055 if (Cond == Pred)
3056 ; // An exact match.
3057 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3058 ; // The actual condition is beyond sufficient.
3059 else
3060 // Check a few special cases.
3061 switch (Cond) {
3062 case ICmpInst::ICMP_UGT:
3063 if (Pred == ICmpInst::ICMP_ULT) {
3064 std::swap(PreCondLHS, PreCondRHS);
3065 Cond = ICmpInst::ICMP_ULT;
3066 break;
3067 }
3068 continue;
3069 case ICmpInst::ICMP_SGT:
3070 if (Pred == ICmpInst::ICMP_SLT) {
3071 std::swap(PreCondLHS, PreCondRHS);
3072 Cond = ICmpInst::ICMP_SLT;
3073 break;
3074 }
3075 continue;
3076 case ICmpInst::ICMP_NE:
3077 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3078 // so check for this case by checking if the NE is comparing against
3079 // a minimum or maximum constant.
3080 if (!ICmpInst::isTrueWhenEqual(Pred))
3081 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3082 const APInt &A = CI->getValue();
3083 switch (Pred) {
3084 case ICmpInst::ICMP_SLT:
3085 if (A.isMaxSignedValue()) break;
3086 continue;
3087 case ICmpInst::ICMP_SGT:
3088 if (A.isMinSignedValue()) break;
3089 continue;
3090 case ICmpInst::ICMP_ULT:
3091 if (A.isMaxValue()) break;
3092 continue;
3093 case ICmpInst::ICMP_UGT:
3094 if (A.isMinValue()) break;
3095 continue;
3096 default:
3097 continue;
3098 }
3099 Cond = ICmpInst::ICMP_NE;
3100 // NE is symmetric but the original comparison may not be. Swap
3101 // the operands if necessary so that they match below.
3102 if (isa<SCEVConstant>(LHS))
3103 std::swap(PreCondLHS, PreCondRHS);
3104 break;
3105 }
3106 continue;
3107 default:
3108 // We weren't able to reconcile the condition.
3109 continue;
3110 }
Dan Gohman38372182008-08-12 20:17:31 +00003111
3112 if (!PreCondLHS->getType()->isInteger()) continue;
3113
3114 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3115 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3116 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003117 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3118 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohman38372182008-08-12 20:17:31 +00003119 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003120 }
3121
Dan Gohman38372182008-08-12 20:17:31 +00003122 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003123}
3124
Chris Lattnerdb25de42005-08-15 23:33:51 +00003125/// HowManyLessThans - Return the number of times a backedge containing the
3126/// specified less-than comparison will execute. If not computable, return
3127/// UnknownValue.
Dan Gohmana1af7572009-04-30 20:47:05 +00003128ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Nick Lewycky789558d2009-01-13 09:18:58 +00003129HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003130 // Only handle: "ADDREC < LoopInvariant".
3131 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3132
3133 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3134 if (!AddRec || AddRec->getLoop() != L)
3135 return UnknownValue;
3136
3137 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003138 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00003139 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3140 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3141 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3142
3143 // TODO: handle non-constant strides.
3144 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3145 if (!CStep || CStep->isZero())
3146 return UnknownValue;
3147 if (CStep->getValue()->getValue() == 1) {
3148 // With unit stride, the iteration never steps past the limit value.
3149 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3150 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3151 // Test whether a positive iteration iteration can step past the limit
3152 // value and past the maximum value for its type in a single step.
3153 if (isSigned) {
3154 APInt Max = APInt::getSignedMaxValue(BitWidth);
3155 if ((Max - CStep->getValue()->getValue())
3156 .slt(CLimit->getValue()->getValue()))
3157 return UnknownValue;
3158 } else {
3159 APInt Max = APInt::getMaxValue(BitWidth);
3160 if ((Max - CStep->getValue()->getValue())
3161 .ult(CLimit->getValue()->getValue()))
3162 return UnknownValue;
3163 }
3164 } else
3165 // TODO: handle non-constant limit values below.
3166 return UnknownValue;
3167 } else
3168 // TODO: handle negative strides below.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003169 return UnknownValue;
3170
Dan Gohmana1af7572009-04-30 20:47:05 +00003171 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3172 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3173 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00003174 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003175
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003176 // First, we get the value of the LHS in the first iteration: n
3177 SCEVHandle Start = AddRec->getOperand(0);
3178
Dan Gohmana1af7572009-04-30 20:47:05 +00003179 // Determine the minimum constant start value.
3180 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3181 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3182 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003183
Dan Gohmana1af7572009-04-30 20:47:05 +00003184 // If we know that the condition is true in order to enter the loop,
3185 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3186 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3187 // division must round up.
3188 SCEVHandle End = RHS;
3189 if (!isLoopGuardedByCond(L,
3190 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3191 getMinusSCEV(Start, Step), RHS))
3192 End = isSigned ? getSMaxExpr(RHS, Start)
3193 : getUMaxExpr(RHS, Start);
3194
3195 // Determine the maximum constant end value.
3196 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3197 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3198 APInt::getMaxValue(BitWidth));
3199
3200 // Finally, we subtract these two values and divide, rounding up, to get
3201 // the number of times the backedge is executed.
3202 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3203 getAddExpr(Step, NegOne)),
3204 Step);
3205
3206 // The maximum backedge count is similar, except using the minimum start
3207 // value and the maximum end value.
3208 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3209 MinStart),
3210 getAddExpr(Step, NegOne)),
3211 Step);
3212
3213 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003214 }
3215
3216 return UnknownValue;
3217}
3218
Chris Lattner53e677a2004-04-02 20:23:17 +00003219/// getNumIterationsInRange - Return the number of iterations of this loop that
3220/// produce values in the specified constant range. Another way of looking at
3221/// this is that it returns the first iteration number where the value is not in
3222/// the condition, thus computing the exit count. If the iteration count can't
3223/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003224SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3225 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003226 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003227 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003228
3229 // If the start is a non-zero constant, shift the range to simplify things.
3230 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003231 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003232 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003233 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3234 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003235 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3236 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003237 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003238 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003239 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003240 }
3241
3242 // The only time we can solve this is when we have all constant indices.
3243 // Otherwise, we cannot determine the overflow conditions.
3244 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3245 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003246 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003247
3248
3249 // Okay at this point we know that all elements of the chrec are constants and
3250 // that the start element is zero.
3251
3252 // First check to see if the range contains zero. If not, the first
3253 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003254 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00003255 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman246b2562007-10-22 18:31:58 +00003256 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003257
Chris Lattner53e677a2004-04-02 20:23:17 +00003258 if (isAffine()) {
3259 // If this is an affine expression then we have this situation:
3260 // Solve {0,+,A} in Range === Ax in Range
3261
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003262 // We know that zero is in the range. If A is positive then we know that
3263 // the upper value of the range must be the first possible exit value.
3264 // If A is negative then the lower of the range is the last possible loop
3265 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00003266 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003267 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3268 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003269
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003270 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003271 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003272 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003273
3274 // Evaluate at the exit value. If we really did fall out of the valid
3275 // range, then we computed our trip count, otherwise wrap around or other
3276 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003277 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003278 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003279 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003280
3281 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003282 assert(Range.contains(
3283 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003284 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003285 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003286 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003287 } else if (isQuadratic()) {
3288 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3289 // quadratic equation to solve it. To do this, we must frame our problem in
3290 // terms of figuring out when zero is crossed, instead of when
3291 // Range.getUpper() is crossed.
3292 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003293 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3294 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003295
3296 // Next, solve the constructed addrec
3297 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003298 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003299 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3300 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3301 if (R1) {
3302 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003303 if (ConstantInt *CB =
3304 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003305 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003306 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003307 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003308
Chris Lattner53e677a2004-04-02 20:23:17 +00003309 // Make sure the root is not off by one. The returned iteration should
3310 // not be in the range, but the previous one should be. When solving
3311 // for "X*X < 5", for example, we should not return a root of 2.
3312 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003313 R1->getValue(),
3314 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003315 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003316 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003317 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003318
Dan Gohman246b2562007-10-22 18:31:58 +00003319 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003320 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003321 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003322 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003323 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003324
Chris Lattner53e677a2004-04-02 20:23:17 +00003325 // If R1 was not in the range, then it is a good return value. Make
3326 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003327 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003328 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003329 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003330 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003331 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003332 }
3333 }
3334 }
3335
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003336 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003337}
3338
3339
3340
3341//===----------------------------------------------------------------------===//
3342// ScalarEvolution Class Implementation
3343//===----------------------------------------------------------------------===//
3344
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003345ScalarEvolution::ScalarEvolution()
3346 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3347}
3348
Chris Lattner53e677a2004-04-02 20:23:17 +00003349bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003350 this->F = &F;
3351 LI = &getAnalysis<LoopInfo>();
3352 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00003353 return false;
3354}
3355
3356void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003357 Scalars.clear();
3358 BackedgeTakenCounts.clear();
3359 ConstantEvolutionLoopExitValue.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00003360}
3361
3362void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3363 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003364 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00003365}
3366
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003367bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003368 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00003369}
3370
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003371static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003372 const Loop *L) {
3373 // Print all inner loops first
3374 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3375 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003376
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003377 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003378
Devang Patelb7211a22007-08-21 00:31:24 +00003379 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003380 L->getExitBlocks(ExitBlocks);
3381 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003382 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003383
Dan Gohman46bdfb02009-02-24 18:55:53 +00003384 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3385 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003386 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003387 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003388 }
3389
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003390 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003391}
3392
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003393void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003394 // ScalarEvolution's implementaiton of the print method is to print
3395 // out SCEV values of all instructions that are interesting. Doing
3396 // this potentially causes it to create new SCEV objects though,
3397 // which technically conflicts with the const qualifier. This isn't
3398 // observable from outside the class though (the hasSCEV function
3399 // notwithstanding), so casting away the const isn't dangerous.
3400 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003401
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003402 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003403 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00003404 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003405 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003406 OS << " --> ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003407 SCEVHandle SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003408 SV->print(OS);
3409 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003410
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003411 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003412 OS << "Exits: ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003413 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003414 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3415 OS << "<<Unknown>>";
3416 } else {
3417 OS << *ExitValue;
3418 }
3419 }
3420
3421
3422 OS << "\n";
3423 }
3424
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003425 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3426 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3427 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003428}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003429
3430void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3431 raw_os_ostream OS(o);
3432 print(OS, M);
3433}