blob: ba1cbb156d1589c55dffaa0899e03dc9056eaaa3 [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 Gohman99243b32009-05-01 16:44:56 +0000649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
650 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000651 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000652 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000653 assert(isSCEVable(Ty) &&
654 "This is not a conversion to a SCEVable type!");
655 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000656
Chris Lattner53e677a2004-04-02 20:23:17 +0000657 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000658 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000659 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000660
Dan Gohman20900ca2009-04-22 16:20:48 +0000661 // trunc(trunc(x)) --> trunc(x)
662 if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
663 return getTruncateExpr(ST->getOperand(), Ty);
664
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000665 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
666 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
667 return getTruncateOrSignExtend(SS->getOperand(), Ty);
668
669 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
670 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
671 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
672
Chris Lattner53e677a2004-04-02 20:23:17 +0000673 // If the input value is a chrec scev made out of constants, truncate
674 // all of the constants.
675 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
676 std::vector<SCEVHandle> Operands;
677 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
678 // FIXME: This should allow truncation of other expression types!
679 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000680 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000681 else
682 break;
683 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000684 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000685 }
686
Chris Lattnerb3364092006-10-04 21:49:37 +0000687 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000688 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
689 return Result;
690}
691
Dan Gohman8170a682009-04-16 19:25:55 +0000692SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
693 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000694 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000695 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000696 assert(isSCEVable(Ty) &&
697 "This is not a conversion to a SCEVable type!");
698 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000699
Dan Gohman2d1be872009-04-16 03:18:22 +0000700 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000701 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000702 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
703 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
704 return getUnknown(C);
705 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000706
Dan Gohman20900ca2009-04-22 16:20:48 +0000707 // zext(zext(x)) --> zext(x)
708 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
709 return getZeroExtendExpr(SZ->getOperand(), Ty);
710
Dan Gohman01ecca22009-04-27 20:16:15 +0000711 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000712 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000713 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000714 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman01ecca22009-04-27 20:16:15 +0000715 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
716 if (AR->isAffine()) {
717 // Check whether the backedge-taken count is SCEVCouldNotCompute.
718 // Note that this serves two purposes: It filters out loops that are
719 // simply not analyzable, and it covers the case where this code is
720 // being called from within backedge-taken count analysis, such that
721 // attempting to ask for the backedge-taken count would likely result
722 // in infinite recursion. In the later case, the analysis code will
723 // cope with a conservative value, and it will take care to purge
724 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000725 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
726 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000727 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000728 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000729 SCEVHandle Start = AR->getStart();
730 SCEVHandle Step = AR->getStepRecurrence(*this);
731
732 // Check whether the backedge-taken count can be losslessly casted to
733 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000734 SCEVHandle CastedMaxBECount =
735 getTruncateOrZeroExtend(MaxBECount, Start->getType());
736 if (MaxBECount ==
737 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000738 const Type *WideTy =
739 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000740 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000741 SCEVHandle ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000742 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000743 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000744 SCEVHandle Add = getAddExpr(Start, ZMul);
745 if (getZeroExtendExpr(Add, WideTy) ==
746 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000747 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000748 getZeroExtendExpr(Step, WideTy))))
749 // Return the expression with the addrec on the outside.
750 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
751 getZeroExtendExpr(Step, Ty),
752 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000753
754 // Similar to above, only this time treat the step value as signed.
755 // This covers loops that count down.
756 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000757 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000758 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000759 Add = getAddExpr(Start, SMul);
760 if (getZeroExtendExpr(Add, WideTy) ==
761 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000762 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000763 getSignExtendExpr(Step, WideTy))))
764 // Return the expression with the addrec on the outside.
765 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
766 getSignExtendExpr(Step, Ty),
767 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000768 }
769 }
770 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000771
Chris Lattnerb3364092006-10-04 21:49:37 +0000772 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000773 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
774 return Result;
775}
776
Dan Gohman01ecca22009-04-27 20:16:15 +0000777SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
778 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000779 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000780 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000781 assert(isSCEVable(Ty) &&
782 "This is not a conversion to a SCEVable type!");
783 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000784
Dan Gohman2d1be872009-04-16 03:18:22 +0000785 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000786 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000787 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
788 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
789 return getUnknown(C);
790 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000791
Dan Gohman20900ca2009-04-22 16:20:48 +0000792 // sext(sext(x)) --> sext(x)
793 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
794 return getSignExtendExpr(SS->getOperand(), Ty);
795
Dan Gohman01ecca22009-04-27 20:16:15 +0000796 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000797 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000798 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000799 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman01ecca22009-04-27 20:16:15 +0000800 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
801 if (AR->isAffine()) {
802 // Check whether the backedge-taken count is SCEVCouldNotCompute.
803 // Note that this serves two purposes: It filters out loops that are
804 // simply not analyzable, and it covers the case where this code is
805 // being called from within backedge-taken count analysis, such that
806 // attempting to ask for the backedge-taken count would likely result
807 // in infinite recursion. In the later case, the analysis code will
808 // cope with a conservative value, and it will take care to purge
809 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000810 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
811 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000812 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000813 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000814 SCEVHandle Start = AR->getStart();
815 SCEVHandle Step = AR->getStepRecurrence(*this);
816
817 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000818 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000819 SCEVHandle CastedMaxBECount =
820 getTruncateOrZeroExtend(MaxBECount, Start->getType());
821 if (MaxBECount ==
822 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000823 const Type *WideTy =
824 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000825 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000826 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000827 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000828 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000829 SCEVHandle Add = getAddExpr(Start, SMul);
830 if (getSignExtendExpr(Add, WideTy) ==
831 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000832 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000833 getSignExtendExpr(Step, WideTy))))
834 // Return the expression with the addrec on the outside.
835 return getAddRecExpr(getSignExtendExpr(Start, Ty),
836 getSignExtendExpr(Step, Ty),
837 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000838 }
839 }
840 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000841
842 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
843 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
844 return Result;
845}
846
Chris Lattner53e677a2004-04-02 20:23:17 +0000847// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000848SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000849 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000850 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000851
852 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000853 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000854
855 // If there are any constants, fold them together.
856 unsigned Idx = 0;
857 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
858 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000859 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000860 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
861 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000862 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
863 RHSC->getValue()->getValue());
864 Ops[0] = getConstant(Fold);
865 Ops.erase(Ops.begin()+1); // Erase the folded element
866 if (Ops.size() == 1) return Ops[0];
867 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000868 }
869
870 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000871 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000872 Ops.erase(Ops.begin());
873 --Idx;
874 }
875 }
876
Chris Lattner627018b2004-04-07 16:16:11 +0000877 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000878
Chris Lattner53e677a2004-04-02 20:23:17 +0000879 // Okay, check to see if the same value occurs in the operand list twice. If
880 // so, merge them together into an multiply expression. Since we sorted the
881 // list, these values are required to be adjacent.
882 const Type *Ty = Ops[0]->getType();
883 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
884 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
885 // Found a match, merge the two values into a multiply, and add any
886 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000887 SCEVHandle Two = getIntegerSCEV(2, Ty);
888 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000889 if (Ops.size() == 2)
890 return Mul;
891 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
892 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000893 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000894 }
895
Dan Gohmanf50cd742007-06-18 19:30:09 +0000896 // Now we know the first non-constant operand. Skip past any cast SCEVs.
897 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
898 ++Idx;
899
900 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000901 if (Idx < Ops.size()) {
902 bool DeletedAdd = false;
903 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
904 // If we have an add, expand the add operands onto the end of the operands
905 // list.
906 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
907 Ops.erase(Ops.begin()+Idx);
908 DeletedAdd = true;
909 }
910
911 // If we deleted at least one add, we added operands to the end of the list,
912 // and they are not necessarily sorted. Recurse to resort and resimplify
913 // any operands we just aquired.
914 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000915 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000916 }
917
918 // Skip over the add expression until we get to a multiply.
919 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
920 ++Idx;
921
922 // If we are adding something to a multiply expression, make sure the
923 // something is not already an operand of the multiply. If so, merge it into
924 // the multiply.
925 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
926 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
927 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
928 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
929 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000930 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000931 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
932 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
933 if (Mul->getNumOperands() != 2) {
934 // If the multiply has more than two operands, we must get the
935 // Y*Z term.
936 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
937 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000938 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000939 }
Dan Gohman246b2562007-10-22 18:31:58 +0000940 SCEVHandle One = getIntegerSCEV(1, Ty);
941 SCEVHandle AddOne = getAddExpr(InnerMul, One);
942 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000943 if (Ops.size() == 2) return OuterMul;
944 if (AddOp < Idx) {
945 Ops.erase(Ops.begin()+AddOp);
946 Ops.erase(Ops.begin()+Idx-1);
947 } else {
948 Ops.erase(Ops.begin()+Idx);
949 Ops.erase(Ops.begin()+AddOp-1);
950 }
951 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000952 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000953 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000954
Chris Lattner53e677a2004-04-02 20:23:17 +0000955 // Check this multiply against other multiplies being added together.
956 for (unsigned OtherMulIdx = Idx+1;
957 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
958 ++OtherMulIdx) {
959 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
960 // If MulOp occurs in OtherMul, we can fold the two multiplies
961 // together.
962 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
963 OMulOp != e; ++OMulOp)
964 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
965 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
966 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
967 if (Mul->getNumOperands() != 2) {
968 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
969 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000970 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000971 }
972 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
973 if (OtherMul->getNumOperands() != 2) {
974 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
975 OtherMul->op_end());
976 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000977 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000978 }
Dan Gohman246b2562007-10-22 18:31:58 +0000979 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
980 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000981 if (Ops.size() == 2) return OuterMul;
982 Ops.erase(Ops.begin()+Idx);
983 Ops.erase(Ops.begin()+OtherMulIdx-1);
984 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000985 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000986 }
987 }
988 }
989 }
990
991 // If there are any add recurrences in the operands list, see if any other
992 // added values are loop invariant. If so, we can fold them into the
993 // recurrence.
994 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
995 ++Idx;
996
997 // Scan over all recurrences, trying to fold loop invariants into them.
998 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
999 // Scan all of the other operands to this add and add them to the vector if
1000 // they are loop invariant w.r.t. the recurrence.
1001 std::vector<SCEVHandle> LIOps;
1002 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1003 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1004 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1005 LIOps.push_back(Ops[i]);
1006 Ops.erase(Ops.begin()+i);
1007 --i; --e;
1008 }
1009
1010 // If we found some loop invariants, fold them into the recurrence.
1011 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001012 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001013 LIOps.push_back(AddRec->getStart());
1014
1015 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001016 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001017
Dan Gohman246b2562007-10-22 18:31:58 +00001018 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001019 // If all of the other operands were loop invariant, we are done.
1020 if (Ops.size() == 1) return NewRec;
1021
1022 // Otherwise, add the folded AddRec by the non-liv parts.
1023 for (unsigned i = 0;; ++i)
1024 if (Ops[i] == AddRec) {
1025 Ops[i] = NewRec;
1026 break;
1027 }
Dan Gohman246b2562007-10-22 18:31:58 +00001028 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001029 }
1030
1031 // Okay, if there weren't any loop invariants to be folded, check to see if
1032 // there are multiple AddRec's with the same loop induction variable being
1033 // added together. If so, we can fold them.
1034 for (unsigned OtherIdx = Idx+1;
1035 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1036 if (OtherIdx != Idx) {
1037 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1038 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1039 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1040 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1041 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1042 if (i >= NewOps.size()) {
1043 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1044 OtherAddRec->op_end());
1045 break;
1046 }
Dan Gohman246b2562007-10-22 18:31:58 +00001047 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001048 }
Dan Gohman246b2562007-10-22 18:31:58 +00001049 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001050
1051 if (Ops.size() == 2) return NewAddRec;
1052
1053 Ops.erase(Ops.begin()+Idx);
1054 Ops.erase(Ops.begin()+OtherIdx-1);
1055 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001056 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001057 }
1058 }
1059
1060 // Otherwise couldn't fold anything into this recurrence. Move onto the
1061 // next one.
1062 }
1063
1064 // Okay, it looks like we really DO need an add expr. Check to see if we
1065 // already have one, otherwise create a new one.
1066 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001067 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1068 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +00001069 if (Result == 0) Result = new SCEVAddExpr(Ops);
1070 return Result;
1071}
1072
1073
Dan Gohman246b2562007-10-22 18:31:58 +00001074SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001075 assert(!Ops.empty() && "Cannot get empty mul!");
1076
1077 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +00001078 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001079
1080 // If there are any constants, fold them together.
1081 unsigned Idx = 0;
1082 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1083
1084 // C1*(C2+V) -> C1*C2 + C1*V
1085 if (Ops.size() == 2)
1086 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1087 if (Add->getNumOperands() == 2 &&
1088 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001089 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1090 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001091
1092
1093 ++Idx;
1094 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1095 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001096 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1097 RHSC->getValue()->getValue());
1098 Ops[0] = getConstant(Fold);
1099 Ops.erase(Ops.begin()+1); // Erase the folded element
1100 if (Ops.size() == 1) return Ops[0];
1101 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001102 }
1103
1104 // If we are left with a constant one being multiplied, strip it off.
1105 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1106 Ops.erase(Ops.begin());
1107 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001108 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001109 // If we have a multiply of zero, it will always be zero.
1110 return Ops[0];
1111 }
1112 }
1113
1114 // Skip over the add expression until we get to a multiply.
1115 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1116 ++Idx;
1117
1118 if (Ops.size() == 1)
1119 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001120
Chris Lattner53e677a2004-04-02 20:23:17 +00001121 // If there are mul operands inline them all into this expression.
1122 if (Idx < Ops.size()) {
1123 bool DeletedMul = false;
1124 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1125 // If we have an mul, expand the mul operands onto the end of the operands
1126 // list.
1127 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1128 Ops.erase(Ops.begin()+Idx);
1129 DeletedMul = true;
1130 }
1131
1132 // If we deleted at least one mul, we added operands to the end of the list,
1133 // and they are not necessarily sorted. Recurse to resort and resimplify
1134 // any operands we just aquired.
1135 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001136 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001137 }
1138
1139 // If there are any add recurrences in the operands list, see if any other
1140 // added values are loop invariant. If so, we can fold them into the
1141 // recurrence.
1142 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1143 ++Idx;
1144
1145 // Scan over all recurrences, trying to fold loop invariants into them.
1146 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1147 // Scan all of the other operands to this mul and add them to the vector if
1148 // they are loop invariant w.r.t. the recurrence.
1149 std::vector<SCEVHandle> LIOps;
1150 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1151 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1152 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1153 LIOps.push_back(Ops[i]);
1154 Ops.erase(Ops.begin()+i);
1155 --i; --e;
1156 }
1157
1158 // If we found some loop invariants, fold them into the recurrence.
1159 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001160 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001161 std::vector<SCEVHandle> NewOps;
1162 NewOps.reserve(AddRec->getNumOperands());
1163 if (LIOps.size() == 1) {
1164 SCEV *Scale = LIOps[0];
1165 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001166 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001167 } else {
1168 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1169 std::vector<SCEVHandle> MulOps(LIOps);
1170 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001171 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001172 }
1173 }
1174
Dan Gohman246b2562007-10-22 18:31:58 +00001175 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001176
1177 // If all of the other operands were loop invariant, we are done.
1178 if (Ops.size() == 1) return NewRec;
1179
1180 // Otherwise, multiply the folded AddRec by the non-liv parts.
1181 for (unsigned i = 0;; ++i)
1182 if (Ops[i] == AddRec) {
1183 Ops[i] = NewRec;
1184 break;
1185 }
Dan Gohman246b2562007-10-22 18:31:58 +00001186 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001187 }
1188
1189 // Okay, if there weren't any loop invariants to be folded, check to see if
1190 // there are multiple AddRec's with the same loop induction variable being
1191 // multiplied together. If so, we can fold them.
1192 for (unsigned OtherIdx = Idx+1;
1193 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1194 if (OtherIdx != Idx) {
1195 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1196 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1197 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1198 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001199 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001200 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001201 SCEVHandle B = F->getStepRecurrence(*this);
1202 SCEVHandle D = G->getStepRecurrence(*this);
1203 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1204 getMulExpr(G, B),
1205 getMulExpr(B, D));
1206 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1207 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001208 if (Ops.size() == 2) return NewAddRec;
1209
1210 Ops.erase(Ops.begin()+Idx);
1211 Ops.erase(Ops.begin()+OtherIdx-1);
1212 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001213 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001214 }
1215 }
1216
1217 // Otherwise couldn't fold anything into this recurrence. Move onto the
1218 // next one.
1219 }
1220
1221 // Okay, it looks like we really DO need an mul expr. Check to see if we
1222 // already have one, otherwise create a new one.
1223 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001224 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1225 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001226 if (Result == 0)
1227 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001228 return Result;
1229}
1230
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001231SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001232 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1233 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001234 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001235
1236 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1237 Constant *LHSCV = LHSC->getValue();
1238 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001239 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001240 }
1241 }
1242
Nick Lewycky789558d2009-01-13 09:18:58 +00001243 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1244
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001245 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1246 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001247 return Result;
1248}
1249
1250
1251/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1252/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001253SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001254 const SCEVHandle &Step, const Loop *L) {
1255 std::vector<SCEVHandle> Operands;
1256 Operands.push_back(Start);
1257 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1258 if (StepChrec->getLoop() == L) {
1259 Operands.insert(Operands.end(), StepChrec->op_begin(),
1260 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001261 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001262 }
1263
1264 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001265 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001266}
1267
1268/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1269/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001270SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001271 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001272 if (Operands.size() == 1) return Operands[0];
1273
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001274 if (Operands.back()->isZero()) {
1275 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001276 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001277 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001278
Dan Gohmand9cc7492008-08-08 18:33:12 +00001279 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1280 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1281 const Loop* NestedLoop = NestedAR->getLoop();
1282 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1283 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1284 NestedAR->op_end());
1285 SCEVHandle NestedARHandle(NestedAR);
1286 Operands[0] = NestedAR->getStart();
1287 NestedOperands[0] = getAddRecExpr(Operands, L);
1288 return getAddRecExpr(NestedOperands, NestedLoop);
1289 }
1290 }
1291
Chris Lattner53e677a2004-04-02 20:23:17 +00001292 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001293 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1294 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001295 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1296 return Result;
1297}
1298
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001299SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1300 const SCEVHandle &RHS) {
1301 std::vector<SCEVHandle> Ops;
1302 Ops.push_back(LHS);
1303 Ops.push_back(RHS);
1304 return getSMaxExpr(Ops);
1305}
1306
1307SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1308 assert(!Ops.empty() && "Cannot get empty smax!");
1309 if (Ops.size() == 1) return Ops[0];
1310
1311 // Sort by complexity, this groups all similar expression types together.
1312 GroupByComplexity(Ops);
1313
1314 // If there are any constants, fold them together.
1315 unsigned Idx = 0;
1316 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1317 ++Idx;
1318 assert(Idx < Ops.size());
1319 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1320 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001321 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001322 APIntOps::smax(LHSC->getValue()->getValue(),
1323 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001324 Ops[0] = getConstant(Fold);
1325 Ops.erase(Ops.begin()+1); // Erase the folded element
1326 if (Ops.size() == 1) return Ops[0];
1327 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001328 }
1329
1330 // If we are left with a constant -inf, strip it off.
1331 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1332 Ops.erase(Ops.begin());
1333 --Idx;
1334 }
1335 }
1336
1337 if (Ops.size() == 1) return Ops[0];
1338
1339 // Find the first SMax
1340 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1341 ++Idx;
1342
1343 // Check to see if one of the operands is an SMax. If so, expand its operands
1344 // onto our operand list, and recurse to simplify.
1345 if (Idx < Ops.size()) {
1346 bool DeletedSMax = false;
1347 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1348 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1349 Ops.erase(Ops.begin()+Idx);
1350 DeletedSMax = true;
1351 }
1352
1353 if (DeletedSMax)
1354 return getSMaxExpr(Ops);
1355 }
1356
1357 // Okay, check to see if the same value occurs in the operand list twice. If
1358 // so, delete one. Since we sorted the list, these values are required to
1359 // be adjacent.
1360 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1361 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1362 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1363 --i; --e;
1364 }
1365
1366 if (Ops.size() == 1) return Ops[0];
1367
1368 assert(!Ops.empty() && "Reduced smax down to nothing!");
1369
Nick Lewycky3e630762008-02-20 06:48:22 +00001370 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001371 // already have one, otherwise create a new one.
1372 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1373 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1374 SCEVOps)];
1375 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1376 return Result;
1377}
1378
Nick Lewycky3e630762008-02-20 06:48:22 +00001379SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1380 const SCEVHandle &RHS) {
1381 std::vector<SCEVHandle> Ops;
1382 Ops.push_back(LHS);
1383 Ops.push_back(RHS);
1384 return getUMaxExpr(Ops);
1385}
1386
1387SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1388 assert(!Ops.empty() && "Cannot get empty umax!");
1389 if (Ops.size() == 1) return Ops[0];
1390
1391 // Sort by complexity, this groups all similar expression types together.
1392 GroupByComplexity(Ops);
1393
1394 // If there are any constants, fold them together.
1395 unsigned Idx = 0;
1396 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1397 ++Idx;
1398 assert(Idx < Ops.size());
1399 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1400 // We found two constants, fold them together!
1401 ConstantInt *Fold = ConstantInt::get(
1402 APIntOps::umax(LHSC->getValue()->getValue(),
1403 RHSC->getValue()->getValue()));
1404 Ops[0] = getConstant(Fold);
1405 Ops.erase(Ops.begin()+1); // Erase the folded element
1406 if (Ops.size() == 1) return Ops[0];
1407 LHSC = cast<SCEVConstant>(Ops[0]);
1408 }
1409
1410 // If we are left with a constant zero, strip it off.
1411 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1412 Ops.erase(Ops.begin());
1413 --Idx;
1414 }
1415 }
1416
1417 if (Ops.size() == 1) return Ops[0];
1418
1419 // Find the first UMax
1420 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1421 ++Idx;
1422
1423 // Check to see if one of the operands is a UMax. If so, expand its operands
1424 // onto our operand list, and recurse to simplify.
1425 if (Idx < Ops.size()) {
1426 bool DeletedUMax = false;
1427 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1428 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1429 Ops.erase(Ops.begin()+Idx);
1430 DeletedUMax = true;
1431 }
1432
1433 if (DeletedUMax)
1434 return getUMaxExpr(Ops);
1435 }
1436
1437 // Okay, check to see if the same value occurs in the operand list twice. If
1438 // so, delete one. Since we sorted the list, these values are required to
1439 // be adjacent.
1440 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1441 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1442 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1443 --i; --e;
1444 }
1445
1446 if (Ops.size() == 1) return Ops[0];
1447
1448 assert(!Ops.empty() && "Reduced umax down to nothing!");
1449
1450 // Okay, it looks like we really DO need a umax expr. Check to see if we
1451 // already have one, otherwise create a new one.
1452 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1453 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1454 SCEVOps)];
1455 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1456 return Result;
1457}
1458
Dan Gohman246b2562007-10-22 18:31:58 +00001459SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001460 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001461 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001462 if (isa<ConstantPointerNull>(V))
1463 return getIntegerSCEV(0, V->getType());
Chris Lattnerb3364092006-10-04 21:49:37 +00001464 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001465 if (Result == 0) Result = new SCEVUnknown(V);
1466 return Result;
1467}
1468
Chris Lattner53e677a2004-04-02 20:23:17 +00001469//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001470// Basic SCEV Analysis and PHI Idiom Recognition Code
1471//
1472
Dan Gohman5cec4db2007-06-19 14:28:31 +00001473/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001474/// client before it removes an instruction from the program, to make sure
1475/// that no dangling references are left around.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001476void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001477 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001478
Dan Gohman5cec4db2007-06-19 14:28:31 +00001479 if (Scalars.erase(V)) {
1480 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001481 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001482 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001483 }
1484
1485 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001486 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001487 Worklist.pop_back();
1488
Dan Gohman5cec4db2007-06-19 14:28:31 +00001489 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001490 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001491 Instruction *Inst = cast<Instruction>(*UI);
1492 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001493 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001494 ConstantEvolutionLoopExitValue.erase(PN);
1495 Worklist.push_back(Inst);
1496 }
1497 }
1498 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001499}
1500
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001501/// isSCEVable - Test if values of the given type are analyzable within
1502/// the SCEV framework. This primarily includes integer types, and it
1503/// can optionally include pointer types if the ScalarEvolution class
1504/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001505bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001506 // Integers are always SCEVable.
1507 if (Ty->isInteger())
1508 return true;
1509
1510 // Pointers are SCEVable if TargetData information is available
1511 // to provide pointer size information.
1512 if (isa<PointerType>(Ty))
1513 return TD != NULL;
1514
1515 // Otherwise it's not SCEVable.
1516 return false;
1517}
1518
1519/// getTypeSizeInBits - Return the size in bits of the specified type,
1520/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001521uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001522 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1523
1524 // If we have a TargetData, use it!
1525 if (TD)
1526 return TD->getTypeSizeInBits(Ty);
1527
1528 // Otherwise, we support only integer types.
1529 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1530 return Ty->getPrimitiveSizeInBits();
1531}
1532
1533/// getEffectiveSCEVType - Return a type with the same bitwidth as
1534/// the given type and which represents how SCEV will treat the given
1535/// type, for which isSCEVable must return true. For pointer types,
1536/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001537const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001538 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1539
1540 if (Ty->isInteger())
1541 return Ty;
1542
1543 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1544 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001545}
Chris Lattner53e677a2004-04-02 20:23:17 +00001546
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001547SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001548 return UnknownValue;
1549}
1550
Torok Edwine3d12852009-05-01 08:33:47 +00001551// hasSCEV - Return true if the SCEV for this value has already been
1552/// computed.
1553bool ScalarEvolution::hasSCEV(Value *V) const {
1554 return Scalars.count(V);
1555}
1556
Chris Lattner53e677a2004-04-02 20:23:17 +00001557/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1558/// expression and create a new one.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001559SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001560 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001561
1562 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1563 if (I != Scalars.end()) return I->second;
1564 SCEVHandle S = createSCEV(V);
1565 Scalars.insert(std::make_pair(V, S));
1566 return S;
1567}
1568
Dan Gohman2d1be872009-04-16 03:18:22 +00001569/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1570/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001571SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1572 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001573 Constant *C;
1574 if (Val == 0)
1575 C = Constant::getNullValue(Ty);
1576 else if (Ty->isFloatingPoint())
1577 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1578 APFloat::IEEEdouble, Val));
1579 else
1580 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001581 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001582}
1583
1584/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1585///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001586SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001587 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001588 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001589
1590 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001591 Ty = getEffectiveSCEVType(Ty);
1592 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001593}
1594
1595/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001596SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001597 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001598 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001599
1600 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001601 Ty = getEffectiveSCEVType(Ty);
1602 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001603 return getMinusSCEV(AllOnes, V);
1604}
1605
1606/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1607///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001608SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001609 const SCEVHandle &RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001610 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001611 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001612}
1613
1614/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1615/// input value to the specified type. If the type must be extended, it is zero
1616/// extended.
1617SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001618ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001619 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001620 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001621 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1622 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001623 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001624 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001625 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001626 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001627 return getTruncateExpr(V, Ty);
1628 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001629}
1630
1631/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1632/// input value to the specified type. If the type must be extended, it is sign
1633/// extended.
1634SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001635ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001636 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001637 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001638 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1639 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001640 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001641 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001642 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001643 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001644 return getTruncateExpr(V, Ty);
1645 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001646}
1647
Chris Lattner4dc534c2005-02-13 04:37:18 +00001648/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1649/// the specified instruction and replaces any references to the symbolic value
1650/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001651void ScalarEvolution::
Chris Lattner4dc534c2005-02-13 04:37:18 +00001652ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1653 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001654 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001655 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001656
Chris Lattner4dc534c2005-02-13 04:37:18 +00001657 SCEVHandle NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001658 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001659 if (NV == SI->second) return; // No change.
1660
1661 SI->second = NV; // Update the scalars map!
1662
1663 // Any instruction values that use this instruction might also need to be
1664 // updated!
1665 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1666 UI != E; ++UI)
1667 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1668}
Chris Lattner53e677a2004-04-02 20:23:17 +00001669
1670/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1671/// a loop header, making it a potential recurrence, or it doesn't.
1672///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001673SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001674 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001675 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00001676 if (L->getHeader() == PN->getParent()) {
1677 // If it lives in the loop header, it has two incoming values, one
1678 // from outside the loop, and one from inside.
1679 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1680 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001681
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001683 SCEVHandle SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001684 assert(Scalars.find(PN) == Scalars.end() &&
1685 "PHI node already processed?");
1686 Scalars.insert(std::make_pair(PN, SymbolicName));
1687
1688 // Using this symbolic name for the PHI, analyze the value coming around
1689 // the back-edge.
1690 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1691
1692 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1693 // has a special value for the first iteration of the loop.
1694
1695 // If the value coming around the backedge is an add with the symbolic
1696 // value we just inserted, then we found a simple induction variable!
1697 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1698 // If there is a single occurrence of the symbolic value, replace it
1699 // with a recurrence.
1700 unsigned FoundIndex = Add->getNumOperands();
1701 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1702 if (Add->getOperand(i) == SymbolicName)
1703 if (FoundIndex == e) {
1704 FoundIndex = i;
1705 break;
1706 }
1707
1708 if (FoundIndex != Add->getNumOperands()) {
1709 // Create an add with everything but the specified operand.
1710 std::vector<SCEVHandle> Ops;
1711 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1712 if (i != FoundIndex)
1713 Ops.push_back(Add->getOperand(i));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001714 SCEVHandle Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001715
1716 // This is not a valid addrec if the step amount is varying each
1717 // loop iteration, but is not itself an addrec in this loop.
1718 if (Accum->isLoopInvariant(L) ||
1719 (isa<SCEVAddRecExpr>(Accum) &&
1720 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1721 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001722 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001723
1724 // Okay, for the entire analysis of this edge we assumed the PHI
1725 // to be symbolic. We now need to go back and update all of the
1726 // entries for the scalars that use the PHI (except for the PHI
1727 // itself) to use the new analyzed value instead of the "symbolic"
1728 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001729 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001730 return PHISCEV;
1731 }
1732 }
Chris Lattner97156e72006-04-26 18:34:07 +00001733 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1734 // Otherwise, this could be a loop like this:
1735 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1736 // In this case, j = {1,+,1} and BEValue is j.
1737 // Because the other in-value of i (0) fits the evolution of BEValue
1738 // i really is an addrec evolution.
1739 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1740 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1741
1742 // If StartVal = j.start - j.stride, we can use StartVal as the
1743 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001744 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00001745 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001746 SCEVHandle PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001747 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001748
1749 // Okay, for the entire analysis of this edge we assumed the PHI
1750 // to be symbolic. We now need to go back and update all of the
1751 // entries for the scalars that use the PHI (except for the PHI
1752 // itself) to use the new analyzed value instead of the "symbolic"
1753 // value.
1754 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1755 return PHISCEV;
1756 }
1757 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001758 }
1759
1760 return SymbolicName;
1761 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001762
Chris Lattner53e677a2004-04-02 20:23:17 +00001763 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001764 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001765}
1766
Nick Lewycky83bb0052007-11-22 07:59:40 +00001767/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1768/// guaranteed to end in (at every loop iteration). It is, at the same time,
1769/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1770/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001771static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001772 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001773 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001774
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001775 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001776 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1777 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001778
1779 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001780 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1781 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1782 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001783 }
1784
1785 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001786 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1787 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1788 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001789 }
1790
Chris Lattnera17f0392006-12-12 02:26:09 +00001791 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001792 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001793 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001794 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001795 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001796 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001797 }
1798
1799 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001800 // The result is the sum of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001801 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1802 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00001803 for (unsigned i = 1, e = M->getNumOperands();
1804 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001805 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky83bb0052007-11-22 07:59:40 +00001806 BitWidth);
1807 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001808 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001809
Chris Lattnera17f0392006-12-12 02:26:09 +00001810 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001811 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001812 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001813 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001814 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001815 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001816 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001817
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001818 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1819 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001820 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001821 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001822 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001823 return MinOpRes;
1824 }
1825
Nick Lewycky3e630762008-02-20 06:48:22 +00001826 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1827 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001828 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky3e630762008-02-20 06:48:22 +00001829 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001830 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky3e630762008-02-20 06:48:22 +00001831 return MinOpRes;
1832 }
1833
Nick Lewycky789558d2009-01-13 09:18:58 +00001834 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001835 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001836}
Chris Lattner53e677a2004-04-02 20:23:17 +00001837
1838/// createSCEV - We know that there is no SCEV for the specified value.
1839/// Analyze the expression.
1840///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001841SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001842 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001843 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00001844
Dan Gohman6c459a22008-06-22 19:56:46 +00001845 unsigned Opcode = Instruction::UserOp1;
1846 if (Instruction *I = dyn_cast<Instruction>(V))
1847 Opcode = I->getOpcode();
1848 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1849 Opcode = CE->getOpcode();
1850 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001851 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001852
Dan Gohman6c459a22008-06-22 19:56:46 +00001853 User *U = cast<User>(V);
1854 switch (Opcode) {
1855 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001856 return getAddExpr(getSCEV(U->getOperand(0)),
1857 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001858 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001859 return getMulExpr(getSCEV(U->getOperand(0)),
1860 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001861 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001862 return getUDivExpr(getSCEV(U->getOperand(0)),
1863 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001864 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001865 return getMinusSCEV(getSCEV(U->getOperand(0)),
1866 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00001867 case Instruction::And:
1868 // For an expression like x&255 that merely masks off the high bits,
1869 // use zext(trunc(x)) as the SCEV expression.
1870 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001871 if (CI->isNullValue())
1872 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00001873 if (CI->isAllOnesValue())
1874 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00001875 const APInt &A = CI->getValue();
1876 unsigned Ones = A.countTrailingOnes();
1877 if (APIntOps::isMask(Ones, A))
1878 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001879 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1880 IntegerType::get(Ones)),
1881 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00001882 }
1883 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00001884 case Instruction::Or:
1885 // If the RHS of the Or is a constant, we may have something like:
1886 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1887 // optimizations will transparently handle this case.
1888 //
1889 // In order for this transformation to be safe, the LHS must be of the
1890 // form X*(2^n) and the Or constant must be less than 2^n.
1891 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1892 SCEVHandle LHS = getSCEV(U->getOperand(0));
1893 const APInt &CIVal = CI->getValue();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001894 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00001895 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001896 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001897 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001898 break;
1899 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001900 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001901 // If the RHS of the xor is a signbit, then this is just an add.
1902 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001903 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001904 return getAddExpr(getSCEV(U->getOperand(0)),
1905 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001906
1907 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001908 else if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001909 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001910 }
1911 break;
1912
1913 case Instruction::Shl:
1914 // Turn shift left of a constant amount into a multiply.
1915 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1916 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1917 Constant *X = ConstantInt::get(
1918 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001919 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00001920 }
1921 break;
1922
Nick Lewycky01eaf802008-07-07 06:15:49 +00001923 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00001924 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001925 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1926 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1927 Constant *X = ConstantInt::get(
1928 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001929 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001930 }
1931 break;
1932
Dan Gohman4ee29af2009-04-21 02:26:00 +00001933 case Instruction::AShr:
1934 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1935 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1936 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1937 if (L->getOpcode() == Instruction::Shl &&
1938 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001939 unsigned BitWidth = getTypeSizeInBits(U->getType());
1940 uint64_t Amt = BitWidth - CI->getZExtValue();
1941 if (Amt == BitWidth)
1942 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1943 if (Amt > BitWidth)
1944 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00001945 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001946 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001947 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00001948 U->getType());
1949 }
1950 break;
1951
Dan Gohman6c459a22008-06-22 19:56:46 +00001952 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001953 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001954
1955 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001956 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001957
1958 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001959 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001960
1961 case Instruction::BitCast:
1962 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001963 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00001964 return getSCEV(U->getOperand(0));
1965 break;
1966
Dan Gohman2d1be872009-04-16 03:18:22 +00001967 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001968 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00001969 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001970 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00001971
1972 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001973 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00001974 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1975 U->getType());
1976
1977 case Instruction::GetElementPtr: {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001978 if (!TD) break; // Without TD we can't analyze pointers.
1979 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001980 Value *Base = U->getOperand(0);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001981 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman2d1be872009-04-16 03:18:22 +00001982 gep_type_iterator GTI = gep_type_begin(U);
1983 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1984 E = U->op_end();
1985 I != E; ++I) {
1986 Value *Index = *I;
1987 // Compute the (potentially symbolic) offset in bytes for this index.
1988 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1989 // For a struct, add the member offset.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001990 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman2d1be872009-04-16 03:18:22 +00001991 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1992 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001993 TotalOffset = getAddExpr(TotalOffset,
1994 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman2d1be872009-04-16 03:18:22 +00001995 } else {
1996 // For an array, add the element offset, explicitly scaled.
1997 SCEVHandle LocalOffset = getSCEV(Index);
1998 if (!isa<PointerType>(LocalOffset->getType()))
1999 // Getelementptr indicies are signed.
2000 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2001 IntPtrTy);
2002 LocalOffset =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002003 getMulExpr(LocalOffset,
2004 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2005 IntPtrTy));
2006 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman2d1be872009-04-16 03:18:22 +00002007 }
2008 }
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002009 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman2d1be872009-04-16 03:18:22 +00002010 }
2011
Dan Gohman6c459a22008-06-22 19:56:46 +00002012 case Instruction::PHI:
2013 return createNodeForPHI(cast<PHINode>(U));
2014
2015 case Instruction::Select:
2016 // This could be a smax or umax that was lowered earlier.
2017 // Try to recover it.
2018 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2019 Value *LHS = ICI->getOperand(0);
2020 Value *RHS = ICI->getOperand(1);
2021 switch (ICI->getPredicate()) {
2022 case ICmpInst::ICMP_SLT:
2023 case ICmpInst::ICMP_SLE:
2024 std::swap(LHS, RHS);
2025 // fall through
2026 case ICmpInst::ICMP_SGT:
2027 case ICmpInst::ICMP_SGE:
2028 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002029 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002030 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00002031 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002032 return getNotSCEV(getSMaxExpr(
2033 getNotSCEV(getSCEV(LHS)),
2034 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002035 break;
2036 case ICmpInst::ICMP_ULT:
2037 case ICmpInst::ICMP_ULE:
2038 std::swap(LHS, RHS);
2039 // fall through
2040 case ICmpInst::ICMP_UGT:
2041 case ICmpInst::ICMP_UGE:
2042 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002043 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002044 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2045 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002046 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2047 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002048 break;
2049 default:
2050 break;
2051 }
2052 }
2053
2054 default: // We cannot analyze this expression.
2055 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002056 }
2057
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002058 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002059}
2060
2061
2062
2063//===----------------------------------------------------------------------===//
2064// Iteration Count Computation Code
2065//
2066
Dan Gohman46bdfb02009-02-24 18:55:53 +00002067/// getBackedgeTakenCount - If the specified loop has a predictable
2068/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2069/// object. The backedge-taken count is the number of times the loop header
2070/// will be branched to from within the loop. This is one less than the
2071/// trip count of the loop, since it doesn't count the first iteration,
2072/// when the header is branched to from outside the loop.
2073///
2074/// Note that it is not valid to call this method on a loop without a
2075/// loop-invariant backedge-taken count (see
2076/// hasLoopInvariantBackedgeTakenCount).
2077///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002078SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002079 return getBackedgeTakenInfo(L).Exact;
2080}
2081
2082/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2083/// return the least SCEV value that is known never to be less than the
2084/// actual backedge taken count.
2085SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2086 return getBackedgeTakenInfo(L).Max;
2087}
2088
2089const ScalarEvolution::BackedgeTakenInfo &
2090ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002091 // Initially insert a CouldNotCompute for this loop. If the insertion
2092 // succeeds, procede to actually compute a backedge-taken count and
2093 // update the value. The temporary CouldNotCompute value tells SCEV
2094 // code elsewhere that it shouldn't attempt to request a new
2095 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002096 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002097 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2098 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002099 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2100 if (ItCount.Exact != UnknownValue) {
2101 assert(ItCount.Exact->isLoopInvariant(L) &&
2102 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002103 "Computed trip count isn't loop invariant for loop!");
2104 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002105
Dan Gohman01ecca22009-04-27 20:16:15 +00002106 // Update the value in the map.
2107 Pair.first->second = ItCount;
Chris Lattner53e677a2004-04-02 20:23:17 +00002108 } else if (isa<PHINode>(L->getHeader()->begin())) {
2109 // Only count loops that have phi nodes as not being computable.
2110 ++NumTripCountsNotComputed;
2111 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002112
2113 // Now that we know more about the trip count for this loop, forget any
2114 // existing SCEV values for PHI nodes in this loop since they are only
2115 // conservative estimates made without the benefit
2116 // of trip count information.
2117 if (ItCount.hasAnyInfo())
2118 for (BasicBlock::iterator I = L->getHeader()->begin();
2119 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2120 deleteValueFromRecords(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002121 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002122 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002123}
2124
Dan Gohman46bdfb02009-02-24 18:55:53 +00002125/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002126/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002127/// ScalarEvolution's ability to compute a trip count, or if the loop
2128/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002129void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002130 BackedgeTakenCounts.erase(L);
Dan Gohman60f8a632009-02-17 20:49:49 +00002131}
2132
Dan Gohman46bdfb02009-02-24 18:55:53 +00002133/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2134/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002135ScalarEvolution::BackedgeTakenInfo
2136ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002137 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00002138 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002139 L->getExitBlocks(ExitBlocks);
2140 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002141
2142 // Okay, there is one exit block. Try to find the condition that causes the
2143 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002144 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00002145
2146 BasicBlock *ExitingBlock = 0;
2147 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2148 PI != E; ++PI)
2149 if (L->contains(*PI)) {
2150 if (ExitingBlock == 0)
2151 ExitingBlock = *PI;
2152 else
2153 return UnknownValue; // More than one block exiting!
2154 }
2155 assert(ExitingBlock && "No exits from loop, something is broken!");
2156
2157 // Okay, we've computed the exiting block. See what condition causes us to
2158 // exit.
2159 //
2160 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002161 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2162 if (ExitBr == 0) return UnknownValue;
2163 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002164
2165 // At this point, we know we have a conditional branch that determines whether
2166 // the loop is exited. However, we don't know if the branch is executed each
2167 // time through the loop. If not, then the execution count of the branch will
2168 // not be equal to the trip count of the loop.
2169 //
2170 // Currently we check for this by checking to see if the Exit branch goes to
2171 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002172 // times as the loop. We also handle the case where the exit block *is* the
2173 // loop header. This is common for un-rotated loops. More extensive analysis
2174 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002175 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002176 ExitBr->getSuccessor(1) != L->getHeader() &&
2177 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00002178 return UnknownValue;
2179
Reid Spencere4d87aa2006-12-23 06:05:41 +00002180 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2181
Nick Lewycky3b711652008-02-21 08:34:02 +00002182 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002183 // Note that ICmpInst deals with pointer comparisons too so we must check
2184 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002185 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman46bdfb02009-02-24 18:55:53 +00002186 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Chris Lattner7980fb92004-04-17 18:36:24 +00002187 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002188
Reid Spencere4d87aa2006-12-23 06:05:41 +00002189 // If the condition was exit on true, convert the condition to exit on false
2190 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002191 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002192 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002193 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002194 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002195
2196 // Handle common loops like: for (X = "string"; *X; ++X)
2197 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2198 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2199 SCEVHandle ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002200 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Chris Lattner673e02b2004-10-12 01:49:27 +00002201 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2202 }
2203
Chris Lattner53e677a2004-04-02 20:23:17 +00002204 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2205 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2206
2207 // Try to evaluate any dependencies out of the loop.
2208 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2209 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2210 Tmp = getSCEVAtScope(RHS, L);
2211 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2212
Reid Spencere4d87aa2006-12-23 06:05:41 +00002213 // At this point, we would like to compute how many iterations of the
2214 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002215 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2216 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002217 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002218 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002219 }
2220
Chris Lattner53e677a2004-04-02 20:23:17 +00002221 // If we have a comparison of a chrec against a constant, try to use value
2222 // ranges to answer this query.
2223 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2224 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2225 if (AddRec->getLoop() == L) {
2226 // Form the comparison range using the constant of the correct type so
2227 // that the ConstantRange class knows to do a signed or unsigned
2228 // comparison.
2229 ConstantInt *CompVal = RHSC->getValue();
2230 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002231 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002232 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002233 if (CompVal) {
2234 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002235 ConstantRange CompRange(
2236 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002237
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002238 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002239 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2240 }
2241 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002242
Chris Lattner53e677a2004-04-02 20:23:17 +00002243 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002244 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002245 // Convert to: while (X-Y != 0)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002246 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002247 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002248 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002249 }
2250 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002251 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002252 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002253 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002254 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002255 }
2256 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002257 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2258 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002259 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002260 }
2261 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002262 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2263 getNotSCEV(RHS), L, true);
2264 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002265 break;
2266 }
2267 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002268 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2269 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002270 break;
2271 }
2272 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002273 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2274 getNotSCEV(RHS), L, false);
2275 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002276 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002277 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002278 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002279#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002280 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002281 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002282 errs() << "[unsigned] ";
2283 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002284 << Instruction::getOpcodeName(Instruction::ICmp)
2285 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002286#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002287 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002288 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00002289 return
2290 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2291 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002292}
2293
Chris Lattner673e02b2004-10-12 01:49:27 +00002294static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002295EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2296 ScalarEvolution &SE) {
2297 SCEVHandle InVal = SE.getConstant(C);
2298 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002299 assert(isa<SCEVConstant>(Val) &&
2300 "Evaluation of SCEV at constant didn't fold correctly?");
2301 return cast<SCEVConstant>(Val)->getValue();
2302}
2303
2304/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2305/// and a GEP expression (missing the pointer index) indexing into it, return
2306/// the addressed element of the initializer or null if the index expression is
2307/// invalid.
2308static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002309GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002310 const std::vector<ConstantInt*> &Indices) {
2311 Constant *Init = GV->getInitializer();
2312 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002313 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002314 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2315 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2316 Init = cast<Constant>(CS->getOperand(Idx));
2317 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2318 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2319 Init = cast<Constant>(CA->getOperand(Idx));
2320 } else if (isa<ConstantAggregateZero>(Init)) {
2321 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2322 assert(Idx < STy->getNumElements() && "Bad struct index!");
2323 Init = Constant::getNullValue(STy->getElementType(Idx));
2324 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2325 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2326 Init = Constant::getNullValue(ATy->getElementType());
2327 } else {
2328 assert(0 && "Unknown constant aggregate type!");
2329 }
2330 return 0;
2331 } else {
2332 return 0; // Unknown initializer type
2333 }
2334 }
2335 return Init;
2336}
2337
Dan Gohman46bdfb02009-02-24 18:55:53 +00002338/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2339/// 'icmp op load X, cst', try to see if we can compute the backedge
2340/// execution count.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002341SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002342ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2343 const Loop *L,
2344 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002345 if (LI->isVolatile()) return UnknownValue;
2346
2347 // Check to see if the loaded pointer is a getelementptr of a global.
2348 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2349 if (!GEP) return UnknownValue;
2350
2351 // Make sure that it is really a constant global we are gepping, with an
2352 // initializer, and make sure the first IDX is really 0.
2353 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2354 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2355 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2356 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2357 return UnknownValue;
2358
2359 // Okay, we allow one non-constant index into the GEP instruction.
2360 Value *VarIdx = 0;
2361 std::vector<ConstantInt*> Indexes;
2362 unsigned VarIdxNum = 0;
2363 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2364 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2365 Indexes.push_back(CI);
2366 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2367 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2368 VarIdx = GEP->getOperand(i);
2369 VarIdxNum = i-2;
2370 Indexes.push_back(0);
2371 }
2372
2373 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2374 // Check to see if X is a loop variant variable value now.
2375 SCEVHandle Idx = getSCEV(VarIdx);
2376 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2377 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2378
2379 // We can only recognize very limited forms of loop index expressions, in
2380 // particular, only affine AddRec's like {C1,+,C2}.
2381 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2382 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2383 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2384 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2385 return UnknownValue;
2386
2387 unsigned MaxSteps = MaxBruteForceIterations;
2388 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002389 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002390 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002391 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00002392
2393 // Form the GEP offset.
2394 Indexes[VarIdxNum] = Val;
2395
2396 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2397 if (Result == 0) break; // Cannot compute!
2398
2399 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002400 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002401 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002402 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002403#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002404 errs() << "\n***\n*** Computed loop count " << *ItCst
2405 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2406 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002407#endif
2408 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002409 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002410 }
2411 }
2412 return UnknownValue;
2413}
2414
2415
Chris Lattner3221ad02004-04-17 22:58:41 +00002416/// CanConstantFold - Return true if we can constant fold an instruction of the
2417/// specified type, assuming that all operands were constants.
2418static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002419 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002420 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2421 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002422
Chris Lattner3221ad02004-04-17 22:58:41 +00002423 if (const CallInst *CI = dyn_cast<CallInst>(I))
2424 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002425 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002426 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002427}
2428
Chris Lattner3221ad02004-04-17 22:58:41 +00002429/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2430/// in the loop that V is derived from. We allow arbitrary operations along the
2431/// way, but the operands of an operation must either be constants or a value
2432/// derived from a constant PHI. If this expression does not fit with these
2433/// constraints, return null.
2434static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2435 // If this is not an instruction, or if this is an instruction outside of the
2436 // loop, it can't be derived from a loop PHI.
2437 Instruction *I = dyn_cast<Instruction>(V);
2438 if (I == 0 || !L->contains(I->getParent())) return 0;
2439
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002440 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002441 if (L->getHeader() == I->getParent())
2442 return PN;
2443 else
2444 // We don't currently keep track of the control flow needed to evaluate
2445 // PHIs, so we cannot handle PHIs inside of loops.
2446 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002447 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002448
2449 // If we won't be able to constant fold this expression even if the operands
2450 // are constants, return early.
2451 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002452
Chris Lattner3221ad02004-04-17 22:58:41 +00002453 // Otherwise, we can evaluate this instruction if all of its operands are
2454 // constant or derived from a PHI node themselves.
2455 PHINode *PHI = 0;
2456 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2457 if (!(isa<Constant>(I->getOperand(Op)) ||
2458 isa<GlobalValue>(I->getOperand(Op)))) {
2459 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2460 if (P == 0) return 0; // Not evolving from PHI
2461 if (PHI == 0)
2462 PHI = P;
2463 else if (PHI != P)
2464 return 0; // Evolving from multiple different PHIs.
2465 }
2466
2467 // This is a expression evolving from a constant PHI!
2468 return PHI;
2469}
2470
2471/// EvaluateExpression - Given an expression that passes the
2472/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2473/// in the loop has the value PHIVal. If we can't fold this expression for some
2474/// reason, return null.
2475static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2476 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002477 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00002478 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00002479 Instruction *I = cast<Instruction>(V);
2480
2481 std::vector<Constant*> Operands;
2482 Operands.resize(I->getNumOperands());
2483
2484 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2485 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2486 if (Operands[i] == 0) return 0;
2487 }
2488
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002489 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2490 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2491 &Operands[0], Operands.size());
2492 else
2493 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2494 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002495}
2496
2497/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2498/// in the header of its containing loop, we know the loop executes a
2499/// constant number of times, and the PHI node is just a recurrence
2500/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002501Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002502getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002503 std::map<PHINode*, Constant*>::iterator I =
2504 ConstantEvolutionLoopExitValue.find(PN);
2505 if (I != ConstantEvolutionLoopExitValue.end())
2506 return I->second;
2507
Dan Gohman46bdfb02009-02-24 18:55:53 +00002508 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002509 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2510
2511 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2512
2513 // Since the loop is canonicalized, the PHI node must have two entries. One
2514 // entry must be a constant (coming in from outside of the loop), and the
2515 // second must be derived from the same PHI.
2516 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2517 Constant *StartCST =
2518 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2519 if (StartCST == 0)
2520 return RetVal = 0; // Must be a constant.
2521
2522 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2523 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2524 if (PN2 != PN)
2525 return RetVal = 0; // Not derived from same PHI.
2526
2527 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002528 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00002529 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002530
Dan Gohman46bdfb02009-02-24 18:55:53 +00002531 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00002532 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002533 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2534 if (IterationNum == NumIterations)
2535 return RetVal = PHIVal; // Got exit value!
2536
2537 // Compute the value of the PHI node for the next iteration.
2538 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2539 if (NextPHI == PHIVal)
2540 return RetVal = NextPHI; // Stopped evolving!
2541 if (NextPHI == 0)
2542 return 0; // Couldn't evaluate!
2543 PHIVal = NextPHI;
2544 }
2545}
2546
Dan Gohman46bdfb02009-02-24 18:55:53 +00002547/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00002548/// constant number of times (the condition evolves only from constants),
2549/// try to evaluate a few iterations of the loop until we get the exit
2550/// condition gets a value of ExitWhen (true or false). If we cannot
2551/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002552SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002553ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00002554 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2555 if (PN == 0) return UnknownValue;
2556
2557 // Since the loop is canonicalized, the PHI node must have two entries. One
2558 // entry must be a constant (coming in from outside of the loop), and the
2559 // second must be derived from the same PHI.
2560 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2561 Constant *StartCST =
2562 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2563 if (StartCST == 0) return UnknownValue; // Must be a constant.
2564
2565 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2566 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2567 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2568
2569 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2570 // the loop symbolically to determine when the condition gets a value of
2571 // "ExitWhen".
2572 unsigned IterationNum = 0;
2573 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2574 for (Constant *PHIVal = StartCST;
2575 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002576 ConstantInt *CondVal =
2577 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002578
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002579 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002580 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002581
Reid Spencere8019bb2007-03-01 07:25:48 +00002582 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002583 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002584 ++NumBruteForceTripCountsComputed;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002585 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002586 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002587
Chris Lattner3221ad02004-04-17 22:58:41 +00002588 // Compute the value of the PHI node for the next iteration.
2589 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2590 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002591 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002592 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002593 }
2594
2595 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002596 return UnknownValue;
2597}
2598
2599/// getSCEVAtScope - Compute the value of the specified expression within the
2600/// indicated loop (which may be null to indicate in no loop). If the
2601/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002602SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002603 // FIXME: this should be turned into a virtual method on SCEV!
2604
Chris Lattner3221ad02004-04-17 22:58:41 +00002605 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002606
Nick Lewycky3e630762008-02-20 06:48:22 +00002607 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002608 // exit value from the loop without using SCEVs.
2609 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2610 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002611 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00002612 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2613 if (PHINode *PN = dyn_cast<PHINode>(I))
2614 if (PN->getParent() == LI->getHeader()) {
2615 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00002616 // to see if the loop that contains it has a known backedge-taken
2617 // count. If so, we may be able to force computation of the exit
2618 // value.
2619 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2620 if (SCEVConstant *BTCC =
2621 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002622 // Okay, we know how many times the containing loop executes. If
2623 // this is a constant evolving PHI node, get the final value at
2624 // the specified iteration number.
2625 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00002626 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002627 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002628 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002629 }
2630 }
2631
Reid Spencer09906f32006-12-04 21:33:23 +00002632 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002633 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002634 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002635 // result. This is particularly useful for computing loop exit values.
2636 if (CanConstantFold(I)) {
2637 std::vector<Constant*> Operands;
2638 Operands.reserve(I->getNumOperands());
2639 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2640 Value *Op = I->getOperand(i);
2641 if (Constant *C = dyn_cast<Constant>(Op)) {
2642 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002643 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002644 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00002645 // non-integer and non-pointer, don't even try to analyze them
2646 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00002647 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00002648 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00002649
Chris Lattner3221ad02004-04-17 22:58:41 +00002650 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman4acd12a2009-04-30 16:40:30 +00002651 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
2652 Constant *C = SC->getValue();
2653 if (C->getType() != Op->getType())
2654 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2655 Op->getType(),
2656 false),
2657 C, Op->getType());
2658 Operands.push_back(C);
2659 } else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2660 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2661 if (C->getType() != Op->getType())
2662 C =
2663 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2664 Op->getType(),
2665 false),
2666 C, Op->getType());
2667 Operands.push_back(C);
2668 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00002669 return V;
2670 } else {
2671 return V;
2672 }
2673 }
2674 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002675
2676 Constant *C;
2677 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2678 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2679 &Operands[0], Operands.size());
2680 else
2681 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2682 &Operands[0], Operands.size());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002683 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002684 }
2685 }
2686
2687 // This is some other type of SCEVUnknown, just return it.
2688 return V;
2689 }
2690
Chris Lattner53e677a2004-04-02 20:23:17 +00002691 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2692 // Avoid performing the look-up in the common case where the specified
2693 // expression has no loop-variant portions.
2694 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2695 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2696 if (OpAtScope != Comm->getOperand(i)) {
2697 if (OpAtScope == UnknownValue) return UnknownValue;
2698 // Okay, at least one of these operands is loop variant but might be
2699 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002700 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002701 NewOps.push_back(OpAtScope);
2702
2703 for (++i; i != e; ++i) {
2704 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2705 if (OpAtScope == UnknownValue) return UnknownValue;
2706 NewOps.push_back(OpAtScope);
2707 }
2708 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002709 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002710 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002711 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002712 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002713 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002714 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002715 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002716 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002717 }
2718 }
2719 // If we got here, all operands are loop invariant.
2720 return Comm;
2721 }
2722
Nick Lewycky789558d2009-01-13 09:18:58 +00002723 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2724 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002725 if (LHS == UnknownValue) return LHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002726 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002727 if (RHS == UnknownValue) return RHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002728 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2729 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002730 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002731 }
2732
2733 // If this is a loop recurrence for a loop that does not contain L, then we
2734 // are dealing with the final value computed by the loop.
2735 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2736 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2737 // To evaluate this recurrence, we need to know how many times the AddRec
2738 // loop iterates. Compute this now.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002739 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2740 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002741
Eli Friedmanb42a6262008-08-04 23:49:06 +00002742 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002743 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002744 }
2745 return UnknownValue;
2746 }
2747
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002748 if (SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
2749 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2750 if (Op == UnknownValue) return Op;
2751 if (Op == Cast->getOperand())
2752 return Cast; // must be loop invariant
2753 return getZeroExtendExpr(Op, Cast->getType());
2754 }
2755
2756 if (SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
2757 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2758 if (Op == UnknownValue) return Op;
2759 if (Op == Cast->getOperand())
2760 return Cast; // must be loop invariant
2761 return getSignExtendExpr(Op, Cast->getType());
2762 }
2763
2764 if (SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
2765 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2766 if (Op == UnknownValue) return Op;
2767 if (Op == Cast->getOperand())
2768 return Cast; // must be loop invariant
2769 return getTruncateExpr(Op, Cast->getType());
2770 }
2771
2772 assert(0 && "Unknown SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002773}
2774
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002775/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2776/// at the specified scope in the program. The L value specifies a loop
2777/// nest to evaluate the expression at, where null is the top-level or a
2778/// specified loop is immediately inside of the loop.
2779///
2780/// This method can be used to compute the exit value for a variable defined
2781/// in a loop by querying what the value will hold in the parent loop.
2782///
2783/// If this value is not computable at this scope, a SCEVCouldNotCompute
2784/// object is returned.
2785SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2786 return getSCEVAtScope(getSCEV(V), L);
2787}
2788
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002789/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2790/// following equation:
2791///
2792/// A * X = B (mod N)
2793///
2794/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2795/// A and B isn't important.
2796///
2797/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2798static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2799 ScalarEvolution &SE) {
2800 uint32_t BW = A.getBitWidth();
2801 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2802 assert(A != 0 && "A must be non-zero.");
2803
2804 // 1. D = gcd(A, N)
2805 //
2806 // The gcd of A and N may have only one prime factor: 2. The number of
2807 // trailing zeros in A is its multiplicity
2808 uint32_t Mult2 = A.countTrailingZeros();
2809 // D = 2^Mult2
2810
2811 // 2. Check if B is divisible by D.
2812 //
2813 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2814 // is not less than multiplicity of this prime factor for D.
2815 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002816 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002817
2818 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2819 // modulo (N / D).
2820 //
2821 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2822 // bit width during computations.
2823 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2824 APInt Mod(BW + 1, 0);
2825 Mod.set(BW - Mult2); // Mod = N / D
2826 APInt I = AD.multiplicativeInverse(Mod);
2827
2828 // 4. Compute the minimum unsigned root of the equation:
2829 // I * (B / D) mod (N / D)
2830 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2831
2832 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2833 // bits.
2834 return SE.getConstant(Result.trunc(BW));
2835}
Chris Lattner53e677a2004-04-02 20:23:17 +00002836
2837/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2838/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2839/// might be the same) or two SCEVCouldNotCompute objects.
2840///
2841static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002842SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002843 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002844 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2845 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2846 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002847
Chris Lattner53e677a2004-04-02 20:23:17 +00002848 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002849 if (!LC || !MC || !NC) {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002850 SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00002851 return std::make_pair(CNC, CNC);
2852 }
2853
Reid Spencere8019bb2007-03-01 07:25:48 +00002854 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002855 const APInt &L = LC->getValue()->getValue();
2856 const APInt &M = MC->getValue()->getValue();
2857 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002858 APInt Two(BitWidth, 2);
2859 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002860
Reid Spencere8019bb2007-03-01 07:25:48 +00002861 {
2862 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002863 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002864 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2865 // The B coefficient is M-N/2
2866 APInt B(M);
2867 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002868
Reid Spencere8019bb2007-03-01 07:25:48 +00002869 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002870 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002871
Reid Spencere8019bb2007-03-01 07:25:48 +00002872 // Compute the B^2-4ac term.
2873 APInt SqrtTerm(B);
2874 SqrtTerm *= B;
2875 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002876
Reid Spencere8019bb2007-03-01 07:25:48 +00002877 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2878 // integer value or else APInt::sqrt() will assert.
2879 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002880
Reid Spencere8019bb2007-03-01 07:25:48 +00002881 // Compute the two solutions for the quadratic formula.
2882 // The divisions must be performed as signed divisions.
2883 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002884 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002885 if (TwoA.isMinValue()) {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002886 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002887 return std::make_pair(CNC, CNC);
2888 }
2889
Reid Spencere8019bb2007-03-01 07:25:48 +00002890 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2891 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002892
Dan Gohman246b2562007-10-22 18:31:58 +00002893 return std::make_pair(SE.getConstant(Solution1),
2894 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002895 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002896}
2897
2898/// HowFarToZero - Return the number of times a backedge comparing the specified
2899/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002900SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002901 // If the value is a constant
2902 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2903 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002904 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002905 return UnknownValue; // Otherwise it will loop infinitely.
2906 }
2907
2908 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2909 if (!AddRec || AddRec->getLoop() != L)
2910 return UnknownValue;
2911
2912 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002913 // If this is an affine expression, the execution count of this branch is
2914 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002915 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002916 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002917 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002918 // equivalent to:
2919 //
2920 // Step*N = -Start (mod 2^BW)
2921 //
2922 // where BW is the common bit width of Start and Step.
2923
Chris Lattner53e677a2004-04-02 20:23:17 +00002924 // Get the initial value for the loop.
2925 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002926 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002927
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002928 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002929
Chris Lattner53e677a2004-04-02 20:23:17 +00002930 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002931 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002932
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002933 // First, handle unitary steps.
2934 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002935 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002936 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2937 return Start; // N = Start (as unsigned)
2938
2939 // Then, try to solve the above equation provided that Start is constant.
2940 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2941 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002942 -StartC->getValue()->getValue(),
2943 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002944 }
Chris Lattner42a75512007-01-15 02:27:26 +00002945 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002946 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2947 // the quadratic equation to solve it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002948 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2949 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002950 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2951 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2952 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002953#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002954 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2955 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002956#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002957 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002958 if (ConstantInt *CB =
2959 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002960 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002961 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002962 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002963
Chris Lattner53e677a2004-04-02 20:23:17 +00002964 // We can only use this value if the chrec ends up with an exact zero
2965 // value at this index. When solving for "X*X != 5", for example, we
2966 // should not accept a root of 2.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002967 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002968 if (Val->isZero())
2969 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002970 }
2971 }
2972 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002973
Chris Lattner53e677a2004-04-02 20:23:17 +00002974 return UnknownValue;
2975}
2976
2977/// HowFarToNonZero - Return the number of times a backedge checking the
2978/// specified value for nonzero will execute. If not computable, return
2979/// UnknownValue
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002980SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002981 // Loops that look like: while (X == 0) are very strange indeed. We don't
2982 // handle them yet except for the trivial case. This could be expanded in the
2983 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002984
Chris Lattner53e677a2004-04-02 20:23:17 +00002985 // If the value is a constant, check to see if it is known to be non-zero
2986 // already. If so, the backedge will execute zero times.
2987 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002988 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002989 return getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002990 return UnknownValue; // Otherwise it will loop infinitely.
2991 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002992
Chris Lattner53e677a2004-04-02 20:23:17 +00002993 // We could implement others, but I really doubt anyone writes loops like
2994 // this, and if they did, they would already be constant folded.
2995 return UnknownValue;
2996}
2997
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002998/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2999/// (which may not be an immediate predecessor) which has exactly one
3000/// successor from which BB is reachable, or null if no such block is
3001/// found.
3002///
3003BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003004ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003005 // If the block has a unique predecessor, then there is no path from the
3006 // predecessor to the block that does not go through the direct edge
3007 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003008 if (BasicBlock *Pred = BB->getSinglePredecessor())
3009 return Pred;
3010
3011 // A loop's header is defined to be a block that dominates the loop.
3012 // If the loop has a preheader, it must be a block that has exactly
3013 // one successor that can reach BB. This is slightly more strict
3014 // than necessary, but works if critical edges are split.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003015 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003016 return L->getLoopPreheader();
3017
3018 return 0;
3019}
3020
Dan Gohmanc2390b12009-02-12 22:19:27 +00003021/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003022/// a conditional between LHS and RHS. This is used to help avoid max
3023/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003024bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003025 ICmpInst::Predicate Pred,
3026 SCEV *LHS, SCEV *RHS) {
Nick Lewycky59cff122008-07-12 07:41:32 +00003027 BasicBlock *Preheader = L->getLoopPreheader();
3028 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003029
Dan Gohman38372182008-08-12 20:17:31 +00003030 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003031 // there are predecessors that can be found that have unique successors
3032 // leading to the original header.
3033 for (; Preheader;
3034 PreheaderDest = Preheader,
3035 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00003036
3037 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00003038 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003039 if (!LoopEntryPredicate ||
3040 LoopEntryPredicate->isUnconditional())
3041 continue;
3042
3043 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3044 if (!ICI) continue;
3045
3046 // Now that we found a conditional branch that dominates the loop, check to
3047 // see if it is the comparison we are looking for.
3048 Value *PreCondLHS = ICI->getOperand(0);
3049 Value *PreCondRHS = ICI->getOperand(1);
3050 ICmpInst::Predicate Cond;
3051 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3052 Cond = ICI->getPredicate();
3053 else
3054 Cond = ICI->getInversePredicate();
3055
Dan Gohmanc2390b12009-02-12 22:19:27 +00003056 if (Cond == Pred)
3057 ; // An exact match.
3058 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3059 ; // The actual condition is beyond sufficient.
3060 else
3061 // Check a few special cases.
3062 switch (Cond) {
3063 case ICmpInst::ICMP_UGT:
3064 if (Pred == ICmpInst::ICMP_ULT) {
3065 std::swap(PreCondLHS, PreCondRHS);
3066 Cond = ICmpInst::ICMP_ULT;
3067 break;
3068 }
3069 continue;
3070 case ICmpInst::ICMP_SGT:
3071 if (Pred == ICmpInst::ICMP_SLT) {
3072 std::swap(PreCondLHS, PreCondRHS);
3073 Cond = ICmpInst::ICMP_SLT;
3074 break;
3075 }
3076 continue;
3077 case ICmpInst::ICMP_NE:
3078 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3079 // so check for this case by checking if the NE is comparing against
3080 // a minimum or maximum constant.
3081 if (!ICmpInst::isTrueWhenEqual(Pred))
3082 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3083 const APInt &A = CI->getValue();
3084 switch (Pred) {
3085 case ICmpInst::ICMP_SLT:
3086 if (A.isMaxSignedValue()) break;
3087 continue;
3088 case ICmpInst::ICMP_SGT:
3089 if (A.isMinSignedValue()) break;
3090 continue;
3091 case ICmpInst::ICMP_ULT:
3092 if (A.isMaxValue()) break;
3093 continue;
3094 case ICmpInst::ICMP_UGT:
3095 if (A.isMinValue()) break;
3096 continue;
3097 default:
3098 continue;
3099 }
3100 Cond = ICmpInst::ICMP_NE;
3101 // NE is symmetric but the original comparison may not be. Swap
3102 // the operands if necessary so that they match below.
3103 if (isa<SCEVConstant>(LHS))
3104 std::swap(PreCondLHS, PreCondRHS);
3105 break;
3106 }
3107 continue;
3108 default:
3109 // We weren't able to reconcile the condition.
3110 continue;
3111 }
Dan Gohman38372182008-08-12 20:17:31 +00003112
3113 if (!PreCondLHS->getType()->isInteger()) continue;
3114
3115 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3116 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3117 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003118 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3119 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohman38372182008-08-12 20:17:31 +00003120 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003121 }
3122
Dan Gohman38372182008-08-12 20:17:31 +00003123 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003124}
3125
Chris Lattnerdb25de42005-08-15 23:33:51 +00003126/// HowManyLessThans - Return the number of times a backedge containing the
3127/// specified less-than comparison will execute. If not computable, return
3128/// UnknownValue.
Dan Gohmana1af7572009-04-30 20:47:05 +00003129ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Nick Lewycky789558d2009-01-13 09:18:58 +00003130HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003131 // Only handle: "ADDREC < LoopInvariant".
3132 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3133
3134 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3135 if (!AddRec || AddRec->getLoop() != L)
3136 return UnknownValue;
3137
3138 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003139 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00003140 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3141 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3142 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3143
3144 // TODO: handle non-constant strides.
3145 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3146 if (!CStep || CStep->isZero())
3147 return UnknownValue;
3148 if (CStep->getValue()->getValue() == 1) {
3149 // With unit stride, the iteration never steps past the limit value.
3150 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3151 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3152 // Test whether a positive iteration iteration can step past the limit
3153 // value and past the maximum value for its type in a single step.
3154 if (isSigned) {
3155 APInt Max = APInt::getSignedMaxValue(BitWidth);
3156 if ((Max - CStep->getValue()->getValue())
3157 .slt(CLimit->getValue()->getValue()))
3158 return UnknownValue;
3159 } else {
3160 APInt Max = APInt::getMaxValue(BitWidth);
3161 if ((Max - CStep->getValue()->getValue())
3162 .ult(CLimit->getValue()->getValue()))
3163 return UnknownValue;
3164 }
3165 } else
3166 // TODO: handle non-constant limit values below.
3167 return UnknownValue;
3168 } else
3169 // TODO: handle negative strides below.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003170 return UnknownValue;
3171
Dan Gohmana1af7572009-04-30 20:47:05 +00003172 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3173 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3174 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00003175 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003176
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003177 // First, we get the value of the LHS in the first iteration: n
3178 SCEVHandle Start = AddRec->getOperand(0);
3179
Dan Gohmana1af7572009-04-30 20:47:05 +00003180 // Determine the minimum constant start value.
3181 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3182 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3183 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003184
Dan Gohmana1af7572009-04-30 20:47:05 +00003185 // If we know that the condition is true in order to enter the loop,
3186 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3187 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3188 // division must round up.
3189 SCEVHandle End = RHS;
3190 if (!isLoopGuardedByCond(L,
3191 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3192 getMinusSCEV(Start, Step), RHS))
3193 End = isSigned ? getSMaxExpr(RHS, Start)
3194 : getUMaxExpr(RHS, Start);
3195
3196 // Determine the maximum constant end value.
3197 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3198 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3199 APInt::getMaxValue(BitWidth));
3200
3201 // Finally, we subtract these two values and divide, rounding up, to get
3202 // the number of times the backedge is executed.
3203 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3204 getAddExpr(Step, NegOne)),
3205 Step);
3206
3207 // The maximum backedge count is similar, except using the minimum start
3208 // value and the maximum end value.
3209 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3210 MinStart),
3211 getAddExpr(Step, NegOne)),
3212 Step);
3213
3214 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003215 }
3216
3217 return UnknownValue;
3218}
3219
Chris Lattner53e677a2004-04-02 20:23:17 +00003220/// getNumIterationsInRange - Return the number of iterations of this loop that
3221/// produce values in the specified constant range. Another way of looking at
3222/// this is that it returns the first iteration number where the value is not in
3223/// the condition, thus computing the exit count. If the iteration count can't
3224/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003225SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3226 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003227 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003228 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003229
3230 // If the start is a non-zero constant, shift the range to simplify things.
3231 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003232 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003233 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003234 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3235 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003236 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3237 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003238 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003239 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003240 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003241 }
3242
3243 // The only time we can solve this is when we have all constant indices.
3244 // Otherwise, we cannot determine the overflow conditions.
3245 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3246 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003247 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003248
3249
3250 // Okay at this point we know that all elements of the chrec are constants and
3251 // that the start element is zero.
3252
3253 // First check to see if the range contains zero. If not, the first
3254 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003255 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00003256 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman246b2562007-10-22 18:31:58 +00003257 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003258
Chris Lattner53e677a2004-04-02 20:23:17 +00003259 if (isAffine()) {
3260 // If this is an affine expression then we have this situation:
3261 // Solve {0,+,A} in Range === Ax in Range
3262
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003263 // We know that zero is in the range. If A is positive then we know that
3264 // the upper value of the range must be the first possible exit value.
3265 // If A is negative then the lower of the range is the last possible loop
3266 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00003267 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003268 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3269 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003270
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003271 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003272 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003273 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003274
3275 // Evaluate at the exit value. If we really did fall out of the valid
3276 // range, then we computed our trip count, otherwise wrap around or other
3277 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003278 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003279 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003280 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003281
3282 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003283 assert(Range.contains(
3284 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003285 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003286 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003287 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003288 } else if (isQuadratic()) {
3289 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3290 // quadratic equation to solve it. To do this, we must frame our problem in
3291 // terms of figuring out when zero is crossed, instead of when
3292 // Range.getUpper() is crossed.
3293 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003294 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3295 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003296
3297 // Next, solve the constructed addrec
3298 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003299 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003300 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3301 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3302 if (R1) {
3303 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003304 if (ConstantInt *CB =
3305 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003306 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003307 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003308 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003309
Chris Lattner53e677a2004-04-02 20:23:17 +00003310 // Make sure the root is not off by one. The returned iteration should
3311 // not be in the range, but the previous one should be. When solving
3312 // for "X*X < 5", for example, we should not return a root of 2.
3313 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003314 R1->getValue(),
3315 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003316 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003317 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003318 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003319
Dan Gohman246b2562007-10-22 18:31:58 +00003320 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003321 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003322 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003323 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003324 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003325
Chris Lattner53e677a2004-04-02 20:23:17 +00003326 // If R1 was not in the range, then it is a good return value. Make
3327 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003328 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003329 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003330 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003331 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003332 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003333 }
3334 }
3335 }
3336
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003337 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003338}
3339
3340
3341
3342//===----------------------------------------------------------------------===//
3343// ScalarEvolution Class Implementation
3344//===----------------------------------------------------------------------===//
3345
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003346ScalarEvolution::ScalarEvolution()
3347 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3348}
3349
Chris Lattner53e677a2004-04-02 20:23:17 +00003350bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003351 this->F = &F;
3352 LI = &getAnalysis<LoopInfo>();
3353 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00003354 return false;
3355}
3356
3357void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003358 Scalars.clear();
3359 BackedgeTakenCounts.clear();
3360 ConstantEvolutionLoopExitValue.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00003361}
3362
3363void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3364 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003365 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00003366}
3367
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003368bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003369 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00003370}
3371
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003372static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003373 const Loop *L) {
3374 // Print all inner loops first
3375 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3376 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003377
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003378 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003379
Devang Patelb7211a22007-08-21 00:31:24 +00003380 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003381 L->getExitBlocks(ExitBlocks);
3382 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003383 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003384
Dan Gohman46bdfb02009-02-24 18:55:53 +00003385 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3386 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003387 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003388 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003389 }
3390
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003391 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003392}
3393
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003394void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003395 // ScalarEvolution's implementaiton of the print method is to print
3396 // out SCEV values of all instructions that are interesting. Doing
3397 // this potentially causes it to create new SCEV objects though,
3398 // which technically conflicts with the const qualifier. This isn't
3399 // observable from outside the class though (the hasSCEV function
3400 // notwithstanding), so casting away the const isn't dangerous.
3401 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003402
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003403 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003404 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00003405 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003406 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003407 OS << " --> ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003408 SCEVHandle SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003409 SV->print(OS);
3410 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003411
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003412 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003413 OS << "Exits: ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003414 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003415 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3416 OS << "<<Unknown>>";
3417 } else {
3418 OS << *ExitValue;
3419 }
3420 }
3421
3422
3423 OS << "\n";
3424 }
3425
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003426 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3427 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3428 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003429}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003430
3431void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3432 raw_os_ostream OS(o);
3433 print(OS, M);
3434}