blob: 3e2b7354a807fbd4b800cc227a291957381b1232 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000073#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000075#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000079#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000080#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000081#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000085#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000086#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000087#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
103 cl::init(100));
104
Dan Gohman844731a2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000107char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Chris Lattner53e677a2004-04-02 20:23:17 +0000116SCEV::~SCEV() {}
117void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000125}
126
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Chris Lattner53e677a2004-04-02 20:23:17 +0000133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanf8a8be82009-04-21 23:15:49 +0000135SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000144 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
Chris Lattner4dc534c2005-02-13 04:37:18 +0000152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000154 const SCEVHandle &Conc,
155 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000156 return this;
157}
158
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000159void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000160 OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
165}
166
167
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value. Don't use a SCEVHandle here, or else the object will
170// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000172
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000174SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000175 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176}
Chris Lattner53e677a2004-04-02 20:23:17 +0000177
Dan Gohman246b2562007-10-22 18:31:58 +0000178SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000179 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000180 if (R == 0) R = new SCEVConstant(V);
181 return R;
182}
Chris Lattner53e677a2004-04-02 20:23:17 +0000183
Dan Gohman246b2562007-10-22 18:31:58 +0000184SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000186}
187
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000190void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191 WriteAsOperand(OS, V, false);
192}
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Dan Gohman84923602009-04-21 01:25:57 +0000194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195 const SCEVHandle &op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
197
198SCEVCastExpr::~SCEVCastExpr() {}
199
200bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201 return Op->dominates(BB, DT);
202}
203
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000204// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205// particular input. Don't use a SCEVHandle here, or else the object will
206// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000207static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
208 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000209
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000211 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215}
Chris Lattner53e677a2004-04-02 20:23:17 +0000216
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000218 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000232 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000240}
241
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000242void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000243 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000244}
245
Dan Gohmand19534a2007-06-15 14:38:12 +0000246// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247// particular input. Don't use a SCEVHandle here, or else the object will never
248// be deleted!
249static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
250 SCEVSignExtendExpr*> > SCEVSignExtends;
251
252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000253 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000256 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000257}
258
259SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
261}
262
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000263void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000264 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000265}
266
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000267// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268// particular input. Don't use a SCEVHandle here, or else the object will never
269// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000270static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
271 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000272
273SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000274 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
275 std::vector<SCEV*>(Operands.begin(),
276 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000277}
278
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
286}
287
Chris Lattner4dc534c2005-02-13 04:37:18 +0000288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000295 if (H != getOperand(i)) {
296 std::vector<SCEVHandle> NewOps;
297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000304
305 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000306 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000307 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000308 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000313 else
314 assert(0 && "Unknown commutative expr!");
315 }
316 }
317 return this;
318}
319
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000320bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
324 }
325 return true;
326}
327
Chris Lattner4dc534c2005-02-13 04:37:18 +0000328
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000333 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000335SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
338
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000343void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000344 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345}
346
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000348 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000349}
350
351// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352// particular input. Don't use a SCEVHandle here, or else the object will never
353// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000354static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000358 SCEVAddRecExprs->erase(std::make_pair(L,
359 std::vector<SCEV*>(Operands.begin(),
360 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361}
362
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000363bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365 if (!getOperand(i)->dominates(BB, DT))
366 return false;
367 }
368 return true;
369}
370
371
Chris Lattner4dc534c2005-02-13 04:37:18 +0000372SCEVHandle SCEVAddRecExpr::
373replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000374 const SCEVHandle &Conc,
375 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000377 SCEVHandle H =
378 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000379 if (H != getOperand(i)) {
380 std::vector<SCEVHandle> NewOps;
381 NewOps.reserve(getNumOperands());
382 for (unsigned j = 0; j != i; ++j)
383 NewOps.push_back(getOperand(j));
384 NewOps.push_back(H);
385 for (++i; i != e; ++i)
386 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000387 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000388
Dan Gohman246b2562007-10-22 18:31:58 +0000389 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000390 }
391 }
392 return this;
393}
394
395
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000396bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
397 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000398 // contain L and if the start is invariant.
399 return !QueryLoop->contains(L->getHeader()) &&
400 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000401}
402
403
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000404void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000405 OS << "{" << *Operands[0];
406 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
407 OS << ",+," << *Operands[i];
408 OS << "}<" << L->getHeader()->getName() + ">";
409}
Chris Lattner53e677a2004-04-02 20:23:17 +0000410
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000411// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
412// value. Don't use a SCEVHandle here, or else the object will never be
413// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000414static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000415
Chris Lattnerb3364092006-10-04 21:49:37 +0000416SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000417
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000418bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
419 // All non-instruction values are loop invariant. All instructions are loop
420 // invariant if they are not contained in the specified loop.
421 if (Instruction *I = dyn_cast<Instruction>(V))
422 return !L->contains(I->getParent());
423 return true;
424}
Chris Lattner53e677a2004-04-02 20:23:17 +0000425
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
430}
431
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000432const Type *SCEVUnknown::getType() const {
433 return V->getType();
434}
Chris Lattner53e677a2004-04-02 20:23:17 +0000435
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000436void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman2d1be872009-04-16 03:18:22 +0000437 if (isa<PointerType>(V->getType()))
438 OS << "(ptrtoint " << *V->getType() << " ";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000439 WriteAsOperand(OS, V, false);
Dan Gohman2d1be872009-04-16 03:18:22 +0000440 if (isa<PointerType>(V->getType()))
441 OS << " to iPTR)";
Chris Lattner53e677a2004-04-02 20:23:17 +0000442}
443
Chris Lattner8d741b82004-06-20 06:23:15 +0000444//===----------------------------------------------------------------------===//
445// SCEV Utilities
446//===----------------------------------------------------------------------===//
447
448namespace {
449 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450 /// than the complexity of the RHS. This comparator is used to canonicalize
451 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000452 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000453 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000454 return LHS->getSCEVType() < RHS->getSCEVType();
455 }
456 };
457}
458
459/// GroupByComplexity - Given a list of SCEV objects, order them by their
460/// complexity, and group objects of the same complexity together by value.
461/// When this routine is finished, we know that any duplicates in the vector are
462/// consecutive and that complexity is monotonically increasing.
463///
464/// Note that we go take special precautions to ensure that we get determinstic
465/// results from this routine. In other words, we don't want the results of
466/// this to depend on where the addresses of various SCEV objects happened to
467/// land in memory.
468///
469static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
470 if (Ops.size() < 2) return; // Noop
471 if (Ops.size() == 2) {
472 // This is the common case, which also happens to be trivially simple.
473 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000474 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000475 std::swap(Ops[0], Ops[1]);
476 return;
477 }
478
479 // Do the rough sort by complexity.
480 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
481
482 // Now that we are sorted by complexity, group elements of the same
483 // complexity. Note that this is, at worst, N^2, but the vector is likely to
484 // be extremely short in practice. Note that we take this approach because we
485 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000486 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000487 SCEV *S = Ops[i];
488 unsigned Complexity = S->getSCEVType();
489
490 // If there are any objects of the same complexity and same value as this
491 // one, group them.
492 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
493 if (Ops[j] == S) { // Found a duplicate.
494 // Move it to immediately after i'th element.
495 std::swap(Ops[i+1], Ops[j]);
496 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000497 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000498 }
499 }
500 }
501}
502
Chris Lattner53e677a2004-04-02 20:23:17 +0000503
Chris Lattner53e677a2004-04-02 20:23:17 +0000504
505//===----------------------------------------------------------------------===//
506// Simple SCEV method implementations
507//===----------------------------------------------------------------------===//
508
Eli Friedmanb42a6262008-08-04 23:49:06 +0000509/// BinomialCoefficient - Compute BC(It, K). The result has width W.
510// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000511static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000512 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000513 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000514 // Handle the simplest case efficiently.
515 if (K == 1)
516 return SE.getTruncateOrZeroExtend(It, ResultTy);
517
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000518 // We are using the following formula for BC(It, K):
519 //
520 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
521 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000522 // Suppose, W is the bitwidth of the return value. We must be prepared for
523 // overflow. Hence, we must assure that the result of our computation is
524 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
525 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000526 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000527 // However, this code doesn't use exactly that formula; the formula it uses
528 // is something like the following, where T is the number of factors of 2 in
529 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
530 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000531 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000532 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000533 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000534 // This formula is trivially equivalent to the previous formula. However,
535 // this formula can be implemented much more efficiently. The trick is that
536 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
537 // arithmetic. To do exact division in modular arithmetic, all we have
538 // to do is multiply by the inverse. Therefore, this step can be done at
539 // width W.
540 //
541 // The next issue is how to safely do the division by 2^T. The way this
542 // is done is by doing the multiplication step at a width of at least W + T
543 // bits. This way, the bottom W+T bits of the product are accurate. Then,
544 // when we perform the division by 2^T (which is equivalent to a right shift
545 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
546 // truncated out after the division by 2^T.
547 //
548 // In comparison to just directly using the first formula, this technique
549 // is much more efficient; using the first formula requires W * K bits,
550 // but this formula less than W + K bits. Also, the first formula requires
551 // a division step, whereas this formula only requires multiplies and shifts.
552 //
553 // It doesn't matter whether the subtraction step is done in the calculation
554 // width or the input iteration count's width; if the subtraction overflows,
555 // the result must be zero anyway. We prefer here to do it in the width of
556 // the induction variable because it helps a lot for certain cases; CodeGen
557 // isn't smart enough to ignore the overflow, which leads to much less
558 // efficient code if the width of the subtraction is wider than the native
559 // register width.
560 //
561 // (It's possible to not widen at all by pulling out factors of 2 before
562 // the multiplication; for example, K=2 can be calculated as
563 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
564 // extra arithmetic, so it's not an obvious win, and it gets
565 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000566
Eli Friedmanb42a6262008-08-04 23:49:06 +0000567 // Protection from insane SCEVs; this bound is conservative,
568 // but it probably doesn't matter.
569 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000570 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000571
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000572 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000573
Eli Friedmanb42a6262008-08-04 23:49:06 +0000574 // Calculate K! / 2^T and T; we divide out the factors of two before
575 // multiplying for calculating K! / 2^T to avoid overflow.
576 // Other overflow doesn't matter because we only care about the bottom
577 // W bits of the result.
578 APInt OddFactorial(W, 1);
579 unsigned T = 1;
580 for (unsigned i = 3; i <= K; ++i) {
581 APInt Mult(W, i);
582 unsigned TwoFactors = Mult.countTrailingZeros();
583 T += TwoFactors;
584 Mult = Mult.lshr(TwoFactors);
585 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000586 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000587
Eli Friedmanb42a6262008-08-04 23:49:06 +0000588 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000589 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000590
591 // Calcuate 2^T, at width T+W.
592 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
593
594 // Calculate the multiplicative inverse of K! / 2^T;
595 // this multiplication factor will perform the exact division by
596 // K! / 2^T.
597 APInt Mod = APInt::getSignedMinValue(W+1);
598 APInt MultiplyFactor = OddFactorial.zext(W+1);
599 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
600 MultiplyFactor = MultiplyFactor.trunc(W);
601
602 // Calculate the product, at width T+W
603 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
604 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
605 for (unsigned i = 1; i != K; ++i) {
606 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
607 Dividend = SE.getMulExpr(Dividend,
608 SE.getTruncateOrZeroExtend(S, CalculationTy));
609 }
610
611 // Divide by 2^T
612 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
613
614 // Truncate the result, and divide by K! / 2^T.
615
616 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
617 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000618}
619
Chris Lattner53e677a2004-04-02 20:23:17 +0000620/// evaluateAtIteration - Return the value of this chain of recurrences at
621/// the specified iteration number. We can evaluate this recurrence by
622/// multiplying each element in the chain by the binomial coefficient
623/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
624///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000625/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000626///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000627/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000628///
Dan Gohman246b2562007-10-22 18:31:58 +0000629SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
630 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000631 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000632 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000633 // The computation is correct in the face of overflow provided that the
634 // multiplication is performed _after_ the evaluation of the binomial
635 // coefficient.
Dan Gohman2d1be872009-04-16 03:18:22 +0000636 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000637 if (isa<SCEVCouldNotCompute>(Coeff))
638 return Coeff;
639
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000641 }
642 return Result;
643}
644
Chris Lattner53e677a2004-04-02 20:23:17 +0000645//===----------------------------------------------------------------------===//
646// SCEV Expression folder implementations
647//===----------------------------------------------------------------------===//
648
Dan Gohman246b2562007-10-22 18:31:58 +0000649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000650 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000651 "This is not a truncating conversion!");
652
Chris Lattner53e677a2004-04-02 20:23:17 +0000653 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000654 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000655 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000656
Dan Gohman20900ca2009-04-22 16:20:48 +0000657 // trunc(trunc(x)) --> trunc(x)
658 if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
659 return getTruncateExpr(ST->getOperand(), Ty);
660
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000661 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
662 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
663 return getTruncateOrSignExtend(SS->getOperand(), Ty);
664
665 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
666 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
667 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
668
Chris Lattner53e677a2004-04-02 20:23:17 +0000669 // If the input value is a chrec scev made out of constants, truncate
670 // all of the constants.
671 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
672 std::vector<SCEVHandle> Operands;
673 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
674 // FIXME: This should allow truncation of other expression types!
675 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000676 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000677 else
678 break;
679 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000680 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000681 }
682
Chris Lattnerb3364092006-10-04 21:49:37 +0000683 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000684 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
685 return Result;
686}
687
Dan Gohman8170a682009-04-16 19:25:55 +0000688SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
689 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000690 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000691 "This is not an extending conversion!");
692
Dan Gohman2d1be872009-04-16 03:18:22 +0000693 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000694 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000695 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
696 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
697 return getUnknown(C);
698 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000699
Dan Gohman20900ca2009-04-22 16:20:48 +0000700 // zext(zext(x)) --> zext(x)
701 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
702 return getZeroExtendExpr(SZ->getOperand(), Ty);
703
Dan Gohman01ecca22009-04-27 20:16:15 +0000704 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000705 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000706 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000707 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman01ecca22009-04-27 20:16:15 +0000708 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
709 if (AR->isAffine()) {
710 // Check whether the backedge-taken count is SCEVCouldNotCompute.
711 // Note that this serves two purposes: It filters out loops that are
712 // simply not analyzable, and it covers the case where this code is
713 // being called from within backedge-taken count analysis, such that
714 // attempting to ask for the backedge-taken count would likely result
715 // in infinite recursion. In the later case, the analysis code will
716 // cope with a conservative value, and it will take care to purge
717 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000718 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
719 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000720 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000721 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000722 SCEVHandle Start = AR->getStart();
723 SCEVHandle Step = AR->getStepRecurrence(*this);
724
725 // Check whether the backedge-taken count can be losslessly casted to
726 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000727 SCEVHandle CastedMaxBECount =
728 getTruncateOrZeroExtend(MaxBECount, Start->getType());
729 if (MaxBECount ==
730 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000731 const Type *WideTy =
732 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000733 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000734 SCEVHandle ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000735 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000736 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000737 SCEVHandle Add = getAddExpr(Start, ZMul);
738 if (getZeroExtendExpr(Add, WideTy) ==
739 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000740 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000741 getZeroExtendExpr(Step, WideTy))))
742 // Return the expression with the addrec on the outside.
743 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
744 getZeroExtendExpr(Step, Ty),
745 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000746
747 // Similar to above, only this time treat the step value as signed.
748 // This covers loops that count down.
749 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000750 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000751 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000752 Add = getAddExpr(Start, SMul);
753 if (getZeroExtendExpr(Add, WideTy) ==
754 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000755 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000756 getSignExtendExpr(Step, WideTy))))
757 // Return the expression with the addrec on the outside.
758 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
759 getSignExtendExpr(Step, Ty),
760 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000761 }
762 }
763 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000764
Chris Lattnerb3364092006-10-04 21:49:37 +0000765 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000766 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
767 return Result;
768}
769
Dan Gohman01ecca22009-04-27 20:16:15 +0000770SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
771 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000772 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000773 "This is not an extending conversion!");
774
Dan Gohman2d1be872009-04-16 03:18:22 +0000775 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000776 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000777 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
778 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
779 return getUnknown(C);
780 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000781
Dan Gohman20900ca2009-04-22 16:20:48 +0000782 // sext(sext(x)) --> sext(x)
783 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
784 return getSignExtendExpr(SS->getOperand(), Ty);
785
Dan Gohman01ecca22009-04-27 20:16:15 +0000786 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000787 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000788 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000789 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman01ecca22009-04-27 20:16:15 +0000790 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
791 if (AR->isAffine()) {
792 // Check whether the backedge-taken count is SCEVCouldNotCompute.
793 // Note that this serves two purposes: It filters out loops that are
794 // simply not analyzable, and it covers the case where this code is
795 // being called from within backedge-taken count analysis, such that
796 // attempting to ask for the backedge-taken count would likely result
797 // in infinite recursion. In the later case, the analysis code will
798 // cope with a conservative value, and it will take care to purge
799 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000800 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
801 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000802 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000803 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000804 SCEVHandle Start = AR->getStart();
805 SCEVHandle Step = AR->getStepRecurrence(*this);
806
807 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000808 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000809 SCEVHandle CastedMaxBECount =
810 getTruncateOrZeroExtend(MaxBECount, Start->getType());
811 if (MaxBECount ==
812 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000813 const Type *WideTy =
814 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000815 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000816 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000817 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000818 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000819 SCEVHandle Add = getAddExpr(Start, SMul);
820 if (getSignExtendExpr(Add, WideTy) ==
821 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000822 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000823 getSignExtendExpr(Step, WideTy))))
824 // Return the expression with the addrec on the outside.
825 return getAddRecExpr(getSignExtendExpr(Start, Ty),
826 getSignExtendExpr(Step, Ty),
827 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000828 }
829 }
830 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000831
832 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
833 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
834 return Result;
835}
836
Chris Lattner53e677a2004-04-02 20:23:17 +0000837// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000838SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000839 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000840 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000841
842 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000843 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000844
845 // If there are any constants, fold them together.
846 unsigned Idx = 0;
847 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
848 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000849 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000850 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
851 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000852 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
853 RHSC->getValue()->getValue());
854 Ops[0] = getConstant(Fold);
855 Ops.erase(Ops.begin()+1); // Erase the folded element
856 if (Ops.size() == 1) return Ops[0];
857 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000858 }
859
860 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000861 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000862 Ops.erase(Ops.begin());
863 --Idx;
864 }
865 }
866
Chris Lattner627018b2004-04-07 16:16:11 +0000867 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000868
Chris Lattner53e677a2004-04-02 20:23:17 +0000869 // Okay, check to see if the same value occurs in the operand list twice. If
870 // so, merge them together into an multiply expression. Since we sorted the
871 // list, these values are required to be adjacent.
872 const Type *Ty = Ops[0]->getType();
873 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
874 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
875 // Found a match, merge the two values into a multiply, and add any
876 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000877 SCEVHandle Two = getIntegerSCEV(2, Ty);
878 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000879 if (Ops.size() == 2)
880 return Mul;
881 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
882 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000883 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000884 }
885
Dan Gohmanf50cd742007-06-18 19:30:09 +0000886 // Now we know the first non-constant operand. Skip past any cast SCEVs.
887 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
888 ++Idx;
889
890 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000891 if (Idx < Ops.size()) {
892 bool DeletedAdd = false;
893 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
894 // If we have an add, expand the add operands onto the end of the operands
895 // list.
896 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
897 Ops.erase(Ops.begin()+Idx);
898 DeletedAdd = true;
899 }
900
901 // If we deleted at least one add, we added operands to the end of the list,
902 // and they are not necessarily sorted. Recurse to resort and resimplify
903 // any operands we just aquired.
904 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000905 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000906 }
907
908 // Skip over the add expression until we get to a multiply.
909 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
910 ++Idx;
911
912 // If we are adding something to a multiply expression, make sure the
913 // something is not already an operand of the multiply. If so, merge it into
914 // the multiply.
915 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
916 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
917 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
918 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
919 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000920 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000921 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
922 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
923 if (Mul->getNumOperands() != 2) {
924 // If the multiply has more than two operands, we must get the
925 // Y*Z term.
926 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
927 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000928 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000929 }
Dan Gohman246b2562007-10-22 18:31:58 +0000930 SCEVHandle One = getIntegerSCEV(1, Ty);
931 SCEVHandle AddOne = getAddExpr(InnerMul, One);
932 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000933 if (Ops.size() == 2) return OuterMul;
934 if (AddOp < Idx) {
935 Ops.erase(Ops.begin()+AddOp);
936 Ops.erase(Ops.begin()+Idx-1);
937 } else {
938 Ops.erase(Ops.begin()+Idx);
939 Ops.erase(Ops.begin()+AddOp-1);
940 }
941 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000942 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000943 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000944
Chris Lattner53e677a2004-04-02 20:23:17 +0000945 // Check this multiply against other multiplies being added together.
946 for (unsigned OtherMulIdx = Idx+1;
947 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
948 ++OtherMulIdx) {
949 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
950 // If MulOp occurs in OtherMul, we can fold the two multiplies
951 // together.
952 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
953 OMulOp != e; ++OMulOp)
954 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
955 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
956 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
957 if (Mul->getNumOperands() != 2) {
958 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
959 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000960 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000961 }
962 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
963 if (OtherMul->getNumOperands() != 2) {
964 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
965 OtherMul->op_end());
966 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000967 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000968 }
Dan Gohman246b2562007-10-22 18:31:58 +0000969 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
970 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000971 if (Ops.size() == 2) return OuterMul;
972 Ops.erase(Ops.begin()+Idx);
973 Ops.erase(Ops.begin()+OtherMulIdx-1);
974 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000975 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000976 }
977 }
978 }
979 }
980
981 // If there are any add recurrences in the operands list, see if any other
982 // added values are loop invariant. If so, we can fold them into the
983 // recurrence.
984 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
985 ++Idx;
986
987 // Scan over all recurrences, trying to fold loop invariants into them.
988 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
989 // Scan all of the other operands to this add and add them to the vector if
990 // they are loop invariant w.r.t. the recurrence.
991 std::vector<SCEVHandle> LIOps;
992 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
993 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
994 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
995 LIOps.push_back(Ops[i]);
996 Ops.erase(Ops.begin()+i);
997 --i; --e;
998 }
999
1000 // If we found some loop invariants, fold them into the recurrence.
1001 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001002 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001003 LIOps.push_back(AddRec->getStart());
1004
1005 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001006 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001007
Dan Gohman246b2562007-10-22 18:31:58 +00001008 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001009 // If all of the other operands were loop invariant, we are done.
1010 if (Ops.size() == 1) return NewRec;
1011
1012 // Otherwise, add the folded AddRec by the non-liv parts.
1013 for (unsigned i = 0;; ++i)
1014 if (Ops[i] == AddRec) {
1015 Ops[i] = NewRec;
1016 break;
1017 }
Dan Gohman246b2562007-10-22 18:31:58 +00001018 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001019 }
1020
1021 // Okay, if there weren't any loop invariants to be folded, check to see if
1022 // there are multiple AddRec's with the same loop induction variable being
1023 // added together. If so, we can fold them.
1024 for (unsigned OtherIdx = Idx+1;
1025 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1026 if (OtherIdx != Idx) {
1027 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1028 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1029 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1030 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1031 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1032 if (i >= NewOps.size()) {
1033 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1034 OtherAddRec->op_end());
1035 break;
1036 }
Dan Gohman246b2562007-10-22 18:31:58 +00001037 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001038 }
Dan Gohman246b2562007-10-22 18:31:58 +00001039 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001040
1041 if (Ops.size() == 2) return NewAddRec;
1042
1043 Ops.erase(Ops.begin()+Idx);
1044 Ops.erase(Ops.begin()+OtherIdx-1);
1045 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001046 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001047 }
1048 }
1049
1050 // Otherwise couldn't fold anything into this recurrence. Move onto the
1051 // next one.
1052 }
1053
1054 // Okay, it looks like we really DO need an add expr. Check to see if we
1055 // already have one, otherwise create a new one.
1056 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001057 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1058 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +00001059 if (Result == 0) Result = new SCEVAddExpr(Ops);
1060 return Result;
1061}
1062
1063
Dan Gohman246b2562007-10-22 18:31:58 +00001064SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001065 assert(!Ops.empty() && "Cannot get empty mul!");
1066
1067 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +00001068 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001069
1070 // If there are any constants, fold them together.
1071 unsigned Idx = 0;
1072 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1073
1074 // C1*(C2+V) -> C1*C2 + C1*V
1075 if (Ops.size() == 2)
1076 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1077 if (Add->getNumOperands() == 2 &&
1078 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001079 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1080 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001081
1082
1083 ++Idx;
1084 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1085 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001086 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1087 RHSC->getValue()->getValue());
1088 Ops[0] = getConstant(Fold);
1089 Ops.erase(Ops.begin()+1); // Erase the folded element
1090 if (Ops.size() == 1) return Ops[0];
1091 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001092 }
1093
1094 // If we are left with a constant one being multiplied, strip it off.
1095 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1096 Ops.erase(Ops.begin());
1097 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001098 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001099 // If we have a multiply of zero, it will always be zero.
1100 return Ops[0];
1101 }
1102 }
1103
1104 // Skip over the add expression until we get to a multiply.
1105 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1106 ++Idx;
1107
1108 if (Ops.size() == 1)
1109 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001110
Chris Lattner53e677a2004-04-02 20:23:17 +00001111 // If there are mul operands inline them all into this expression.
1112 if (Idx < Ops.size()) {
1113 bool DeletedMul = false;
1114 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1115 // If we have an mul, expand the mul operands onto the end of the operands
1116 // list.
1117 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1118 Ops.erase(Ops.begin()+Idx);
1119 DeletedMul = true;
1120 }
1121
1122 // If we deleted at least one mul, we added operands to the end of the list,
1123 // and they are not necessarily sorted. Recurse to resort and resimplify
1124 // any operands we just aquired.
1125 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001126 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001127 }
1128
1129 // If there are any add recurrences in the operands list, see if any other
1130 // added values are loop invariant. If so, we can fold them into the
1131 // recurrence.
1132 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1133 ++Idx;
1134
1135 // Scan over all recurrences, trying to fold loop invariants into them.
1136 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1137 // Scan all of the other operands to this mul and add them to the vector if
1138 // they are loop invariant w.r.t. the recurrence.
1139 std::vector<SCEVHandle> LIOps;
1140 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1141 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1142 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1143 LIOps.push_back(Ops[i]);
1144 Ops.erase(Ops.begin()+i);
1145 --i; --e;
1146 }
1147
1148 // If we found some loop invariants, fold them into the recurrence.
1149 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001150 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001151 std::vector<SCEVHandle> NewOps;
1152 NewOps.reserve(AddRec->getNumOperands());
1153 if (LIOps.size() == 1) {
1154 SCEV *Scale = LIOps[0];
1155 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001156 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001157 } else {
1158 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1159 std::vector<SCEVHandle> MulOps(LIOps);
1160 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001161 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001162 }
1163 }
1164
Dan Gohman246b2562007-10-22 18:31:58 +00001165 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001166
1167 // If all of the other operands were loop invariant, we are done.
1168 if (Ops.size() == 1) return NewRec;
1169
1170 // Otherwise, multiply the folded AddRec by the non-liv parts.
1171 for (unsigned i = 0;; ++i)
1172 if (Ops[i] == AddRec) {
1173 Ops[i] = NewRec;
1174 break;
1175 }
Dan Gohman246b2562007-10-22 18:31:58 +00001176 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001177 }
1178
1179 // Okay, if there weren't any loop invariants to be folded, check to see if
1180 // there are multiple AddRec's with the same loop induction variable being
1181 // multiplied together. If so, we can fold them.
1182 for (unsigned OtherIdx = Idx+1;
1183 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1184 if (OtherIdx != Idx) {
1185 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1186 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1187 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1188 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001189 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001190 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001191 SCEVHandle B = F->getStepRecurrence(*this);
1192 SCEVHandle D = G->getStepRecurrence(*this);
1193 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1194 getMulExpr(G, B),
1195 getMulExpr(B, D));
1196 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1197 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001198 if (Ops.size() == 2) return NewAddRec;
1199
1200 Ops.erase(Ops.begin()+Idx);
1201 Ops.erase(Ops.begin()+OtherIdx-1);
1202 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001203 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001204 }
1205 }
1206
1207 // Otherwise couldn't fold anything into this recurrence. Move onto the
1208 // next one.
1209 }
1210
1211 // Okay, it looks like we really DO need an mul expr. Check to see if we
1212 // already have one, otherwise create a new one.
1213 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001214 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1215 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001216 if (Result == 0)
1217 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001218 return Result;
1219}
1220
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001221SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001222 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1223 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001224 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001225
1226 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1227 Constant *LHSCV = LHSC->getValue();
1228 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001229 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001230 }
1231 }
1232
Nick Lewycky789558d2009-01-13 09:18:58 +00001233 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1234
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001235 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1236 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001237 return Result;
1238}
1239
1240
1241/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1242/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001243SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001244 const SCEVHandle &Step, const Loop *L) {
1245 std::vector<SCEVHandle> Operands;
1246 Operands.push_back(Start);
1247 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1248 if (StepChrec->getLoop() == L) {
1249 Operands.insert(Operands.end(), StepChrec->op_begin(),
1250 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001251 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001252 }
1253
1254 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001255 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001256}
1257
1258/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1259/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001260SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001261 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001262 if (Operands.size() == 1) return Operands[0];
1263
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001264 if (Operands.back()->isZero()) {
1265 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001266 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001267 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001268
Dan Gohmand9cc7492008-08-08 18:33:12 +00001269 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1270 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1271 const Loop* NestedLoop = NestedAR->getLoop();
1272 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1273 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1274 NestedAR->op_end());
1275 SCEVHandle NestedARHandle(NestedAR);
1276 Operands[0] = NestedAR->getStart();
1277 NestedOperands[0] = getAddRecExpr(Operands, L);
1278 return getAddRecExpr(NestedOperands, NestedLoop);
1279 }
1280 }
1281
Chris Lattner53e677a2004-04-02 20:23:17 +00001282 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001283 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1284 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001285 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1286 return Result;
1287}
1288
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001289SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1290 const SCEVHandle &RHS) {
1291 std::vector<SCEVHandle> Ops;
1292 Ops.push_back(LHS);
1293 Ops.push_back(RHS);
1294 return getSMaxExpr(Ops);
1295}
1296
1297SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1298 assert(!Ops.empty() && "Cannot get empty smax!");
1299 if (Ops.size() == 1) return Ops[0];
1300
1301 // Sort by complexity, this groups all similar expression types together.
1302 GroupByComplexity(Ops);
1303
1304 // If there are any constants, fold them together.
1305 unsigned Idx = 0;
1306 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1307 ++Idx;
1308 assert(Idx < Ops.size());
1309 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1310 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001311 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001312 APIntOps::smax(LHSC->getValue()->getValue(),
1313 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001314 Ops[0] = getConstant(Fold);
1315 Ops.erase(Ops.begin()+1); // Erase the folded element
1316 if (Ops.size() == 1) return Ops[0];
1317 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001318 }
1319
1320 // If we are left with a constant -inf, strip it off.
1321 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1322 Ops.erase(Ops.begin());
1323 --Idx;
1324 }
1325 }
1326
1327 if (Ops.size() == 1) return Ops[0];
1328
1329 // Find the first SMax
1330 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1331 ++Idx;
1332
1333 // Check to see if one of the operands is an SMax. If so, expand its operands
1334 // onto our operand list, and recurse to simplify.
1335 if (Idx < Ops.size()) {
1336 bool DeletedSMax = false;
1337 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1338 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1339 Ops.erase(Ops.begin()+Idx);
1340 DeletedSMax = true;
1341 }
1342
1343 if (DeletedSMax)
1344 return getSMaxExpr(Ops);
1345 }
1346
1347 // Okay, check to see if the same value occurs in the operand list twice. If
1348 // so, delete one. Since we sorted the list, these values are required to
1349 // be adjacent.
1350 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1351 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1352 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1353 --i; --e;
1354 }
1355
1356 if (Ops.size() == 1) return Ops[0];
1357
1358 assert(!Ops.empty() && "Reduced smax down to nothing!");
1359
Nick Lewycky3e630762008-02-20 06:48:22 +00001360 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001361 // already have one, otherwise create a new one.
1362 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1363 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1364 SCEVOps)];
1365 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1366 return Result;
1367}
1368
Nick Lewycky3e630762008-02-20 06:48:22 +00001369SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1370 const SCEVHandle &RHS) {
1371 std::vector<SCEVHandle> Ops;
1372 Ops.push_back(LHS);
1373 Ops.push_back(RHS);
1374 return getUMaxExpr(Ops);
1375}
1376
1377SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1378 assert(!Ops.empty() && "Cannot get empty umax!");
1379 if (Ops.size() == 1) return Ops[0];
1380
1381 // Sort by complexity, this groups all similar expression types together.
1382 GroupByComplexity(Ops);
1383
1384 // If there are any constants, fold them together.
1385 unsigned Idx = 0;
1386 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1387 ++Idx;
1388 assert(Idx < Ops.size());
1389 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1390 // We found two constants, fold them together!
1391 ConstantInt *Fold = ConstantInt::get(
1392 APIntOps::umax(LHSC->getValue()->getValue(),
1393 RHSC->getValue()->getValue()));
1394 Ops[0] = getConstant(Fold);
1395 Ops.erase(Ops.begin()+1); // Erase the folded element
1396 if (Ops.size() == 1) return Ops[0];
1397 LHSC = cast<SCEVConstant>(Ops[0]);
1398 }
1399
1400 // If we are left with a constant zero, strip it off.
1401 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1402 Ops.erase(Ops.begin());
1403 --Idx;
1404 }
1405 }
1406
1407 if (Ops.size() == 1) return Ops[0];
1408
1409 // Find the first UMax
1410 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1411 ++Idx;
1412
1413 // Check to see if one of the operands is a UMax. If so, expand its operands
1414 // onto our operand list, and recurse to simplify.
1415 if (Idx < Ops.size()) {
1416 bool DeletedUMax = false;
1417 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1418 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1419 Ops.erase(Ops.begin()+Idx);
1420 DeletedUMax = true;
1421 }
1422
1423 if (DeletedUMax)
1424 return getUMaxExpr(Ops);
1425 }
1426
1427 // Okay, check to see if the same value occurs in the operand list twice. If
1428 // so, delete one. Since we sorted the list, these values are required to
1429 // be adjacent.
1430 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1431 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1432 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1433 --i; --e;
1434 }
1435
1436 if (Ops.size() == 1) return Ops[0];
1437
1438 assert(!Ops.empty() && "Reduced umax down to nothing!");
1439
1440 // Okay, it looks like we really DO need a umax expr. Check to see if we
1441 // already have one, otherwise create a new one.
1442 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1443 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1444 SCEVOps)];
1445 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1446 return Result;
1447}
1448
Dan Gohman246b2562007-10-22 18:31:58 +00001449SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001450 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001451 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001452 if (isa<ConstantPointerNull>(V))
1453 return getIntegerSCEV(0, V->getType());
Chris Lattnerb3364092006-10-04 21:49:37 +00001454 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001455 if (Result == 0) Result = new SCEVUnknown(V);
1456 return Result;
1457}
1458
Chris Lattner53e677a2004-04-02 20:23:17 +00001459//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001460// Basic SCEV Analysis and PHI Idiom Recognition Code
1461//
1462
Dan Gohman5cec4db2007-06-19 14:28:31 +00001463/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001464/// client before it removes an instruction from the program, to make sure
1465/// that no dangling references are left around.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001466void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001467 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001468
Dan Gohman5cec4db2007-06-19 14:28:31 +00001469 if (Scalars.erase(V)) {
1470 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001471 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001472 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001473 }
1474
1475 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001476 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001477 Worklist.pop_back();
1478
Dan Gohman5cec4db2007-06-19 14:28:31 +00001479 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001480 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001481 Instruction *Inst = cast<Instruction>(*UI);
1482 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001483 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001484 ConstantEvolutionLoopExitValue.erase(PN);
1485 Worklist.push_back(Inst);
1486 }
1487 }
1488 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001489}
1490
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001491/// isSCEVable - Test if values of the given type are analyzable within
1492/// the SCEV framework. This primarily includes integer types, and it
1493/// can optionally include pointer types if the ScalarEvolution class
1494/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001495bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001496 // Integers are always SCEVable.
1497 if (Ty->isInteger())
1498 return true;
1499
1500 // Pointers are SCEVable if TargetData information is available
1501 // to provide pointer size information.
1502 if (isa<PointerType>(Ty))
1503 return TD != NULL;
1504
1505 // Otherwise it's not SCEVable.
1506 return false;
1507}
1508
1509/// getTypeSizeInBits - Return the size in bits of the specified type,
1510/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001511uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001512 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1513
1514 // If we have a TargetData, use it!
1515 if (TD)
1516 return TD->getTypeSizeInBits(Ty);
1517
1518 // Otherwise, we support only integer types.
1519 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1520 return Ty->getPrimitiveSizeInBits();
1521}
1522
1523/// getEffectiveSCEVType - Return a type with the same bitwidth as
1524/// the given type and which represents how SCEV will treat the given
1525/// type, for which isSCEVable must return true. For pointer types,
1526/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001527const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001528 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1529
1530 if (Ty->isInteger())
1531 return Ty;
1532
1533 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1534 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001535}
Chris Lattner53e677a2004-04-02 20:23:17 +00001536
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001537SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001538 return UnknownValue;
1539}
1540
Torok Edwine3d12852009-05-01 08:33:47 +00001541// hasSCEV - Return true if the SCEV for this value has already been
1542/// computed.
1543bool ScalarEvolution::hasSCEV(Value *V) const {
1544 return Scalars.count(V);
1545}
1546
Chris Lattner53e677a2004-04-02 20:23:17 +00001547/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1548/// expression and create a new one.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001549SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001550 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001551
1552 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1553 if (I != Scalars.end()) return I->second;
1554 SCEVHandle S = createSCEV(V);
1555 Scalars.insert(std::make_pair(V, S));
1556 return S;
1557}
1558
Dan Gohman2d1be872009-04-16 03:18:22 +00001559/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1560/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001561SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1562 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001563 Constant *C;
1564 if (Val == 0)
1565 C = Constant::getNullValue(Ty);
1566 else if (Ty->isFloatingPoint())
1567 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1568 APFloat::IEEEdouble, Val));
1569 else
1570 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001571 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001572}
1573
1574/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1575///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001576SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001577 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001578 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001579
1580 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001581 Ty = getEffectiveSCEVType(Ty);
1582 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001583}
1584
1585/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001586SCEVHandle ScalarEvolution::getNotSCEV(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::getNot(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 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001593 return getMinusSCEV(AllOnes, V);
1594}
1595
1596/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1597///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001598SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001599 const SCEVHandle &RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001600 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001601 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001602}
1603
1604/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1605/// input value to the specified type. If the type must be extended, it is zero
1606/// extended.
1607SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001608ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001609 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001610 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001611 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1612 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001613 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001614 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001615 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001616 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001617 return getTruncateExpr(V, Ty);
1618 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001619}
1620
1621/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1622/// input value to the specified type. If the type must be extended, it is sign
1623/// extended.
1624SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001625ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001626 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001627 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001628 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1629 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001630 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001631 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001632 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001633 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001634 return getTruncateExpr(V, Ty);
1635 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001636}
1637
Chris Lattner4dc534c2005-02-13 04:37:18 +00001638/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1639/// the specified instruction and replaces any references to the symbolic value
1640/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001641void ScalarEvolution::
Chris Lattner4dc534c2005-02-13 04:37:18 +00001642ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1643 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001644 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001645 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001646
Chris Lattner4dc534c2005-02-13 04:37:18 +00001647 SCEVHandle NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001648 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001649 if (NV == SI->second) return; // No change.
1650
1651 SI->second = NV; // Update the scalars map!
1652
1653 // Any instruction values that use this instruction might also need to be
1654 // updated!
1655 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1656 UI != E; ++UI)
1657 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1658}
Chris Lattner53e677a2004-04-02 20:23:17 +00001659
1660/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1661/// a loop header, making it a potential recurrence, or it doesn't.
1662///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001663SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001664 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001665 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00001666 if (L->getHeader() == PN->getParent()) {
1667 // If it lives in the loop header, it has two incoming values, one
1668 // from outside the loop, and one from inside.
1669 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1670 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001671
Chris Lattner53e677a2004-04-02 20:23:17 +00001672 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001673 SCEVHandle SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001674 assert(Scalars.find(PN) == Scalars.end() &&
1675 "PHI node already processed?");
1676 Scalars.insert(std::make_pair(PN, SymbolicName));
1677
1678 // Using this symbolic name for the PHI, analyze the value coming around
1679 // the back-edge.
1680 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1681
1682 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1683 // has a special value for the first iteration of the loop.
1684
1685 // If the value coming around the backedge is an add with the symbolic
1686 // value we just inserted, then we found a simple induction variable!
1687 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1688 // If there is a single occurrence of the symbolic value, replace it
1689 // with a recurrence.
1690 unsigned FoundIndex = Add->getNumOperands();
1691 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1692 if (Add->getOperand(i) == SymbolicName)
1693 if (FoundIndex == e) {
1694 FoundIndex = i;
1695 break;
1696 }
1697
1698 if (FoundIndex != Add->getNumOperands()) {
1699 // Create an add with everything but the specified operand.
1700 std::vector<SCEVHandle> Ops;
1701 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1702 if (i != FoundIndex)
1703 Ops.push_back(Add->getOperand(i));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001704 SCEVHandle Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001705
1706 // This is not a valid addrec if the step amount is varying each
1707 // loop iteration, but is not itself an addrec in this loop.
1708 if (Accum->isLoopInvariant(L) ||
1709 (isa<SCEVAddRecExpr>(Accum) &&
1710 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1711 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001712 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001713
1714 // Okay, for the entire analysis of this edge we assumed the PHI
1715 // to be symbolic. We now need to go back and update all of the
1716 // entries for the scalars that use the PHI (except for the PHI
1717 // itself) to use the new analyzed value instead of the "symbolic"
1718 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001719 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001720 return PHISCEV;
1721 }
1722 }
Chris Lattner97156e72006-04-26 18:34:07 +00001723 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1724 // Otherwise, this could be a loop like this:
1725 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1726 // In this case, j = {1,+,1} and BEValue is j.
1727 // Because the other in-value of i (0) fits the evolution of BEValue
1728 // i really is an addrec evolution.
1729 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1730 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1731
1732 // If StartVal = j.start - j.stride, we can use StartVal as the
1733 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001734 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00001735 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001736 SCEVHandle PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001737 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001738
1739 // Okay, for the entire analysis of this edge we assumed the PHI
1740 // to be symbolic. We now need to go back and update all of the
1741 // entries for the scalars that use the PHI (except for the PHI
1742 // itself) to use the new analyzed value instead of the "symbolic"
1743 // value.
1744 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1745 return PHISCEV;
1746 }
1747 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001748 }
1749
1750 return SymbolicName;
1751 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001752
Chris Lattner53e677a2004-04-02 20:23:17 +00001753 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001754 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001755}
1756
Nick Lewycky83bb0052007-11-22 07:59:40 +00001757/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1758/// guaranteed to end in (at every loop iteration). It is, at the same time,
1759/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1760/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001761static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001762 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001763 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001764
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001765 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001766 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1767 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001768
1769 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001770 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1771 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1772 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001773 }
1774
1775 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001776 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1777 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1778 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001779 }
1780
Chris Lattnera17f0392006-12-12 02:26:09 +00001781 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001782 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001783 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001784 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001785 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001786 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001787 }
1788
1789 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001790 // The result is the sum of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001791 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1792 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00001793 for (unsigned i = 1, e = M->getNumOperands();
1794 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001795 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky83bb0052007-11-22 07:59:40 +00001796 BitWidth);
1797 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001798 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001799
Chris Lattnera17f0392006-12-12 02:26:09 +00001800 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001801 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001802 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001803 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001804 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001805 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001806 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001807
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001808 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1809 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001810 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001811 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001812 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001813 return MinOpRes;
1814 }
1815
Nick Lewycky3e630762008-02-20 06:48:22 +00001816 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1817 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001818 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky3e630762008-02-20 06:48:22 +00001819 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001820 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky3e630762008-02-20 06:48:22 +00001821 return MinOpRes;
1822 }
1823
Nick Lewycky789558d2009-01-13 09:18:58 +00001824 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001825 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001826}
Chris Lattner53e677a2004-04-02 20:23:17 +00001827
1828/// createSCEV - We know that there is no SCEV for the specified value.
1829/// Analyze the expression.
1830///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001831SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001832 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001833 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00001834
Dan Gohman6c459a22008-06-22 19:56:46 +00001835 unsigned Opcode = Instruction::UserOp1;
1836 if (Instruction *I = dyn_cast<Instruction>(V))
1837 Opcode = I->getOpcode();
1838 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1839 Opcode = CE->getOpcode();
1840 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001841 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001842
Dan Gohman6c459a22008-06-22 19:56:46 +00001843 User *U = cast<User>(V);
1844 switch (Opcode) {
1845 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001846 return getAddExpr(getSCEV(U->getOperand(0)),
1847 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001848 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001849 return getMulExpr(getSCEV(U->getOperand(0)),
1850 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001851 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001852 return getUDivExpr(getSCEV(U->getOperand(0)),
1853 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001854 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001855 return getMinusSCEV(getSCEV(U->getOperand(0)),
1856 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00001857 case Instruction::And:
1858 // For an expression like x&255 that merely masks off the high bits,
1859 // use zext(trunc(x)) as the SCEV expression.
1860 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001861 if (CI->isNullValue())
1862 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00001863 if (CI->isAllOnesValue())
1864 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00001865 const APInt &A = CI->getValue();
1866 unsigned Ones = A.countTrailingOnes();
1867 if (APIntOps::isMask(Ones, A))
1868 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001869 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1870 IntegerType::get(Ones)),
1871 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00001872 }
1873 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00001874 case Instruction::Or:
1875 // If the RHS of the Or is a constant, we may have something like:
1876 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1877 // optimizations will transparently handle this case.
1878 //
1879 // In order for this transformation to be safe, the LHS must be of the
1880 // form X*(2^n) and the Or constant must be less than 2^n.
1881 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1882 SCEVHandle LHS = getSCEV(U->getOperand(0));
1883 const APInt &CIVal = CI->getValue();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001884 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00001885 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001886 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001887 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001888 break;
1889 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001890 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001891 // If the RHS of the xor is a signbit, then this is just an add.
1892 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001893 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001894 return getAddExpr(getSCEV(U->getOperand(0)),
1895 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001896
1897 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001898 else if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001899 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001900 }
1901 break;
1902
1903 case Instruction::Shl:
1904 // Turn shift left of a constant amount into a multiply.
1905 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1906 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1907 Constant *X = ConstantInt::get(
1908 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001909 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00001910 }
1911 break;
1912
Nick Lewycky01eaf802008-07-07 06:15:49 +00001913 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00001914 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001915 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 getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001920 }
1921 break;
1922
Dan Gohman4ee29af2009-04-21 02:26:00 +00001923 case Instruction::AShr:
1924 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1925 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1926 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1927 if (L->getOpcode() == Instruction::Shl &&
1928 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001929 unsigned BitWidth = getTypeSizeInBits(U->getType());
1930 uint64_t Amt = BitWidth - CI->getZExtValue();
1931 if (Amt == BitWidth)
1932 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1933 if (Amt > BitWidth)
1934 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00001935 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001936 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001937 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00001938 U->getType());
1939 }
1940 break;
1941
Dan Gohman6c459a22008-06-22 19:56:46 +00001942 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001943 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001944
1945 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001946 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001947
1948 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001949 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001950
1951 case Instruction::BitCast:
1952 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001953 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00001954 return getSCEV(U->getOperand(0));
1955 break;
1956
Dan Gohman2d1be872009-04-16 03:18:22 +00001957 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001958 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00001959 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001960 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00001961
1962 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001963 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00001964 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1965 U->getType());
1966
1967 case Instruction::GetElementPtr: {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001968 if (!TD) break; // Without TD we can't analyze pointers.
1969 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001970 Value *Base = U->getOperand(0);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001971 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman2d1be872009-04-16 03:18:22 +00001972 gep_type_iterator GTI = gep_type_begin(U);
1973 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1974 E = U->op_end();
1975 I != E; ++I) {
1976 Value *Index = *I;
1977 // Compute the (potentially symbolic) offset in bytes for this index.
1978 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1979 // For a struct, add the member offset.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001980 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman2d1be872009-04-16 03:18:22 +00001981 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1982 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001983 TotalOffset = getAddExpr(TotalOffset,
1984 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman2d1be872009-04-16 03:18:22 +00001985 } else {
1986 // For an array, add the element offset, explicitly scaled.
1987 SCEVHandle LocalOffset = getSCEV(Index);
1988 if (!isa<PointerType>(LocalOffset->getType()))
1989 // Getelementptr indicies are signed.
1990 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1991 IntPtrTy);
1992 LocalOffset =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001993 getMulExpr(LocalOffset,
1994 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1995 IntPtrTy));
1996 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman2d1be872009-04-16 03:18:22 +00001997 }
1998 }
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001999 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman2d1be872009-04-16 03:18:22 +00002000 }
2001
Dan Gohman6c459a22008-06-22 19:56:46 +00002002 case Instruction::PHI:
2003 return createNodeForPHI(cast<PHINode>(U));
2004
2005 case Instruction::Select:
2006 // This could be a smax or umax that was lowered earlier.
2007 // Try to recover it.
2008 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2009 Value *LHS = ICI->getOperand(0);
2010 Value *RHS = ICI->getOperand(1);
2011 switch (ICI->getPredicate()) {
2012 case ICmpInst::ICMP_SLT:
2013 case ICmpInst::ICMP_SLE:
2014 std::swap(LHS, RHS);
2015 // fall through
2016 case ICmpInst::ICMP_SGT:
2017 case ICmpInst::ICMP_SGE:
2018 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002019 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002020 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00002021 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002022 return getNotSCEV(getSMaxExpr(
2023 getNotSCEV(getSCEV(LHS)),
2024 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002025 break;
2026 case ICmpInst::ICMP_ULT:
2027 case ICmpInst::ICMP_ULE:
2028 std::swap(LHS, RHS);
2029 // fall through
2030 case ICmpInst::ICMP_UGT:
2031 case ICmpInst::ICMP_UGE:
2032 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002033 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002034 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2035 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002036 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2037 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002038 break;
2039 default:
2040 break;
2041 }
2042 }
2043
2044 default: // We cannot analyze this expression.
2045 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002046 }
2047
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002048 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002049}
2050
2051
2052
2053//===----------------------------------------------------------------------===//
2054// Iteration Count Computation Code
2055//
2056
Dan Gohman46bdfb02009-02-24 18:55:53 +00002057/// getBackedgeTakenCount - If the specified loop has a predictable
2058/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2059/// object. The backedge-taken count is the number of times the loop header
2060/// will be branched to from within the loop. This is one less than the
2061/// trip count of the loop, since it doesn't count the first iteration,
2062/// when the header is branched to from outside the loop.
2063///
2064/// Note that it is not valid to call this method on a loop without a
2065/// loop-invariant backedge-taken count (see
2066/// hasLoopInvariantBackedgeTakenCount).
2067///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002068SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002069 return getBackedgeTakenInfo(L).Exact;
2070}
2071
2072/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2073/// return the least SCEV value that is known never to be less than the
2074/// actual backedge taken count.
2075SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2076 return getBackedgeTakenInfo(L).Max;
2077}
2078
2079const ScalarEvolution::BackedgeTakenInfo &
2080ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002081 // Initially insert a CouldNotCompute for this loop. If the insertion
2082 // succeeds, procede to actually compute a backedge-taken count and
2083 // update the value. The temporary CouldNotCompute value tells SCEV
2084 // code elsewhere that it shouldn't attempt to request a new
2085 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002086 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002087 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2088 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002089 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2090 if (ItCount.Exact != UnknownValue) {
2091 assert(ItCount.Exact->isLoopInvariant(L) &&
2092 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002093 "Computed trip count isn't loop invariant for loop!");
2094 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002095
Dan Gohman01ecca22009-04-27 20:16:15 +00002096 // Update the value in the map.
2097 Pair.first->second = ItCount;
Chris Lattner53e677a2004-04-02 20:23:17 +00002098 } else if (isa<PHINode>(L->getHeader()->begin())) {
2099 // Only count loops that have phi nodes as not being computable.
2100 ++NumTripCountsNotComputed;
2101 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002102
2103 // Now that we know more about the trip count for this loop, forget any
2104 // existing SCEV values for PHI nodes in this loop since they are only
2105 // conservative estimates made without the benefit
2106 // of trip count information.
2107 if (ItCount.hasAnyInfo())
2108 for (BasicBlock::iterator I = L->getHeader()->begin();
2109 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2110 deleteValueFromRecords(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002111 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002112 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002113}
2114
Dan Gohman46bdfb02009-02-24 18:55:53 +00002115/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002116/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002117/// ScalarEvolution's ability to compute a trip count, or if the loop
2118/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002119void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002120 BackedgeTakenCounts.erase(L);
Dan Gohman60f8a632009-02-17 20:49:49 +00002121}
2122
Dan Gohman46bdfb02009-02-24 18:55:53 +00002123/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2124/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002125ScalarEvolution::BackedgeTakenInfo
2126ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002127 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00002128 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002129 L->getExitBlocks(ExitBlocks);
2130 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002131
2132 // Okay, there is one exit block. Try to find the condition that causes the
2133 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002134 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00002135
2136 BasicBlock *ExitingBlock = 0;
2137 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2138 PI != E; ++PI)
2139 if (L->contains(*PI)) {
2140 if (ExitingBlock == 0)
2141 ExitingBlock = *PI;
2142 else
2143 return UnknownValue; // More than one block exiting!
2144 }
2145 assert(ExitingBlock && "No exits from loop, something is broken!");
2146
2147 // Okay, we've computed the exiting block. See what condition causes us to
2148 // exit.
2149 //
2150 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002151 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2152 if (ExitBr == 0) return UnknownValue;
2153 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002154
2155 // At this point, we know we have a conditional branch that determines whether
2156 // the loop is exited. However, we don't know if the branch is executed each
2157 // time through the loop. If not, then the execution count of the branch will
2158 // not be equal to the trip count of the loop.
2159 //
2160 // Currently we check for this by checking to see if the Exit branch goes to
2161 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002162 // times as the loop. We also handle the case where the exit block *is* the
2163 // loop header. This is common for un-rotated loops. More extensive analysis
2164 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002165 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002166 ExitBr->getSuccessor(1) != L->getHeader() &&
2167 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00002168 return UnknownValue;
2169
Reid Spencere4d87aa2006-12-23 06:05:41 +00002170 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2171
Nick Lewycky3b711652008-02-21 08:34:02 +00002172 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002173 // Note that ICmpInst deals with pointer comparisons too so we must check
2174 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002175 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman46bdfb02009-02-24 18:55:53 +00002176 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Chris Lattner7980fb92004-04-17 18:36:24 +00002177 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002178
Reid Spencere4d87aa2006-12-23 06:05:41 +00002179 // If the condition was exit on true, convert the condition to exit on false
2180 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002181 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002182 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002183 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002184 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002185
2186 // Handle common loops like: for (X = "string"; *X; ++X)
2187 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2188 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2189 SCEVHandle ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002190 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Chris Lattner673e02b2004-10-12 01:49:27 +00002191 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2192 }
2193
Chris Lattner53e677a2004-04-02 20:23:17 +00002194 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2195 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2196
2197 // Try to evaluate any dependencies out of the loop.
2198 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2199 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2200 Tmp = getSCEVAtScope(RHS, L);
2201 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2202
Reid Spencere4d87aa2006-12-23 06:05:41 +00002203 // At this point, we would like to compute how many iterations of the
2204 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002205 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2206 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002207 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002208 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002209 }
2210
Chris Lattner53e677a2004-04-02 20:23:17 +00002211 // If we have a comparison of a chrec against a constant, try to use value
2212 // ranges to answer this query.
2213 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2214 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2215 if (AddRec->getLoop() == L) {
2216 // Form the comparison range using the constant of the correct type so
2217 // that the ConstantRange class knows to do a signed or unsigned
2218 // comparison.
2219 ConstantInt *CompVal = RHSC->getValue();
2220 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002221 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002222 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002223 if (CompVal) {
2224 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002225 ConstantRange CompRange(
2226 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002227
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002228 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002229 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2230 }
2231 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002232
Chris Lattner53e677a2004-04-02 20:23:17 +00002233 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002234 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002235 // Convert to: while (X-Y != 0)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002236 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002237 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002238 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002239 }
2240 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002241 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002242 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002243 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002244 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002245 }
2246 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002247 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2248 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002249 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002250 }
2251 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002252 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2253 getNotSCEV(RHS), L, true);
2254 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002255 break;
2256 }
2257 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002258 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2259 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002260 break;
2261 }
2262 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002263 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2264 getNotSCEV(RHS), L, false);
2265 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002266 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002267 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002268 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002269#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002270 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002271 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002272 errs() << "[unsigned] ";
2273 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002274 << Instruction::getOpcodeName(Instruction::ICmp)
2275 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002276#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002277 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002278 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00002279 return
2280 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2281 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002282}
2283
Chris Lattner673e02b2004-10-12 01:49:27 +00002284static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002285EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2286 ScalarEvolution &SE) {
2287 SCEVHandle InVal = SE.getConstant(C);
2288 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002289 assert(isa<SCEVConstant>(Val) &&
2290 "Evaluation of SCEV at constant didn't fold correctly?");
2291 return cast<SCEVConstant>(Val)->getValue();
2292}
2293
2294/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2295/// and a GEP expression (missing the pointer index) indexing into it, return
2296/// the addressed element of the initializer or null if the index expression is
2297/// invalid.
2298static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002299GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002300 const std::vector<ConstantInt*> &Indices) {
2301 Constant *Init = GV->getInitializer();
2302 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002303 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002304 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2305 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2306 Init = cast<Constant>(CS->getOperand(Idx));
2307 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2308 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2309 Init = cast<Constant>(CA->getOperand(Idx));
2310 } else if (isa<ConstantAggregateZero>(Init)) {
2311 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2312 assert(Idx < STy->getNumElements() && "Bad struct index!");
2313 Init = Constant::getNullValue(STy->getElementType(Idx));
2314 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2315 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2316 Init = Constant::getNullValue(ATy->getElementType());
2317 } else {
2318 assert(0 && "Unknown constant aggregate type!");
2319 }
2320 return 0;
2321 } else {
2322 return 0; // Unknown initializer type
2323 }
2324 }
2325 return Init;
2326}
2327
Dan Gohman46bdfb02009-02-24 18:55:53 +00002328/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2329/// 'icmp op load X, cst', try to see if we can compute the backedge
2330/// execution count.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002331SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002332ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2333 const Loop *L,
2334 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002335 if (LI->isVolatile()) return UnknownValue;
2336
2337 // Check to see if the loaded pointer is a getelementptr of a global.
2338 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2339 if (!GEP) return UnknownValue;
2340
2341 // Make sure that it is really a constant global we are gepping, with an
2342 // initializer, and make sure the first IDX is really 0.
2343 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2344 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2345 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2346 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2347 return UnknownValue;
2348
2349 // Okay, we allow one non-constant index into the GEP instruction.
2350 Value *VarIdx = 0;
2351 std::vector<ConstantInt*> Indexes;
2352 unsigned VarIdxNum = 0;
2353 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2354 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2355 Indexes.push_back(CI);
2356 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2357 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2358 VarIdx = GEP->getOperand(i);
2359 VarIdxNum = i-2;
2360 Indexes.push_back(0);
2361 }
2362
2363 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2364 // Check to see if X is a loop variant variable value now.
2365 SCEVHandle Idx = getSCEV(VarIdx);
2366 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2367 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2368
2369 // We can only recognize very limited forms of loop index expressions, in
2370 // particular, only affine AddRec's like {C1,+,C2}.
2371 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2372 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2373 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2374 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2375 return UnknownValue;
2376
2377 unsigned MaxSteps = MaxBruteForceIterations;
2378 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002379 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002380 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002381 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00002382
2383 // Form the GEP offset.
2384 Indexes[VarIdxNum] = Val;
2385
2386 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2387 if (Result == 0) break; // Cannot compute!
2388
2389 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002390 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002391 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002392 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002393#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002394 errs() << "\n***\n*** Computed loop count " << *ItCst
2395 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2396 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002397#endif
2398 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002399 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002400 }
2401 }
2402 return UnknownValue;
2403}
2404
2405
Chris Lattner3221ad02004-04-17 22:58:41 +00002406/// CanConstantFold - Return true if we can constant fold an instruction of the
2407/// specified type, assuming that all operands were constants.
2408static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002409 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002410 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2411 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002412
Chris Lattner3221ad02004-04-17 22:58:41 +00002413 if (const CallInst *CI = dyn_cast<CallInst>(I))
2414 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002415 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002416 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002417}
2418
Chris Lattner3221ad02004-04-17 22:58:41 +00002419/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2420/// in the loop that V is derived from. We allow arbitrary operations along the
2421/// way, but the operands of an operation must either be constants or a value
2422/// derived from a constant PHI. If this expression does not fit with these
2423/// constraints, return null.
2424static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2425 // If this is not an instruction, or if this is an instruction outside of the
2426 // loop, it can't be derived from a loop PHI.
2427 Instruction *I = dyn_cast<Instruction>(V);
2428 if (I == 0 || !L->contains(I->getParent())) return 0;
2429
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002430 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002431 if (L->getHeader() == I->getParent())
2432 return PN;
2433 else
2434 // We don't currently keep track of the control flow needed to evaluate
2435 // PHIs, so we cannot handle PHIs inside of loops.
2436 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002437 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002438
2439 // If we won't be able to constant fold this expression even if the operands
2440 // are constants, return early.
2441 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002442
Chris Lattner3221ad02004-04-17 22:58:41 +00002443 // Otherwise, we can evaluate this instruction if all of its operands are
2444 // constant or derived from a PHI node themselves.
2445 PHINode *PHI = 0;
2446 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2447 if (!(isa<Constant>(I->getOperand(Op)) ||
2448 isa<GlobalValue>(I->getOperand(Op)))) {
2449 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2450 if (P == 0) return 0; // Not evolving from PHI
2451 if (PHI == 0)
2452 PHI = P;
2453 else if (PHI != P)
2454 return 0; // Evolving from multiple different PHIs.
2455 }
2456
2457 // This is a expression evolving from a constant PHI!
2458 return PHI;
2459}
2460
2461/// EvaluateExpression - Given an expression that passes the
2462/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2463/// in the loop has the value PHIVal. If we can't fold this expression for some
2464/// reason, return null.
2465static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2466 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002467 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00002468 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00002469 Instruction *I = cast<Instruction>(V);
2470
2471 std::vector<Constant*> Operands;
2472 Operands.resize(I->getNumOperands());
2473
2474 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2475 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2476 if (Operands[i] == 0) return 0;
2477 }
2478
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002479 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2480 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2481 &Operands[0], Operands.size());
2482 else
2483 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2484 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002485}
2486
2487/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2488/// in the header of its containing loop, we know the loop executes a
2489/// constant number of times, and the PHI node is just a recurrence
2490/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002491Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002492getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002493 std::map<PHINode*, Constant*>::iterator I =
2494 ConstantEvolutionLoopExitValue.find(PN);
2495 if (I != ConstantEvolutionLoopExitValue.end())
2496 return I->second;
2497
Dan Gohman46bdfb02009-02-24 18:55:53 +00002498 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002499 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2500
2501 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2502
2503 // Since the loop is canonicalized, the PHI node must have two entries. One
2504 // entry must be a constant (coming in from outside of the loop), and the
2505 // second must be derived from the same PHI.
2506 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2507 Constant *StartCST =
2508 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2509 if (StartCST == 0)
2510 return RetVal = 0; // Must be a constant.
2511
2512 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2513 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2514 if (PN2 != PN)
2515 return RetVal = 0; // Not derived from same PHI.
2516
2517 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002518 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00002519 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002520
Dan Gohman46bdfb02009-02-24 18:55:53 +00002521 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00002522 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002523 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2524 if (IterationNum == NumIterations)
2525 return RetVal = PHIVal; // Got exit value!
2526
2527 // Compute the value of the PHI node for the next iteration.
2528 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2529 if (NextPHI == PHIVal)
2530 return RetVal = NextPHI; // Stopped evolving!
2531 if (NextPHI == 0)
2532 return 0; // Couldn't evaluate!
2533 PHIVal = NextPHI;
2534 }
2535}
2536
Dan Gohman46bdfb02009-02-24 18:55:53 +00002537/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00002538/// constant number of times (the condition evolves only from constants),
2539/// try to evaluate a few iterations of the loop until we get the exit
2540/// condition gets a value of ExitWhen (true or false). If we cannot
2541/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002542SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002543ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00002544 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2545 if (PN == 0) return UnknownValue;
2546
2547 // Since the loop is canonicalized, the PHI node must have two entries. One
2548 // entry must be a constant (coming in from outside of the loop), and the
2549 // second must be derived from the same PHI.
2550 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2551 Constant *StartCST =
2552 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2553 if (StartCST == 0) return UnknownValue; // Must be a constant.
2554
2555 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2556 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2557 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2558
2559 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2560 // the loop symbolically to determine when the condition gets a value of
2561 // "ExitWhen".
2562 unsigned IterationNum = 0;
2563 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2564 for (Constant *PHIVal = StartCST;
2565 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002566 ConstantInt *CondVal =
2567 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002568
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002569 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002570 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002571
Reid Spencere8019bb2007-03-01 07:25:48 +00002572 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002573 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002574 ++NumBruteForceTripCountsComputed;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002575 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002576 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002577
Chris Lattner3221ad02004-04-17 22:58:41 +00002578 // Compute the value of the PHI node for the next iteration.
2579 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2580 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002581 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002582 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002583 }
2584
2585 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002586 return UnknownValue;
2587}
2588
2589/// getSCEVAtScope - Compute the value of the specified expression within the
2590/// indicated loop (which may be null to indicate in no loop). If the
2591/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002592SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002593 // FIXME: this should be turned into a virtual method on SCEV!
2594
Chris Lattner3221ad02004-04-17 22:58:41 +00002595 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002596
Nick Lewycky3e630762008-02-20 06:48:22 +00002597 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002598 // exit value from the loop without using SCEVs.
2599 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2600 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002601 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00002602 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2603 if (PHINode *PN = dyn_cast<PHINode>(I))
2604 if (PN->getParent() == LI->getHeader()) {
2605 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00002606 // to see if the loop that contains it has a known backedge-taken
2607 // count. If so, we may be able to force computation of the exit
2608 // value.
2609 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2610 if (SCEVConstant *BTCC =
2611 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002612 // Okay, we know how many times the containing loop executes. If
2613 // this is a constant evolving PHI node, get the final value at
2614 // the specified iteration number.
2615 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00002616 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002617 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002618 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002619 }
2620 }
2621
Reid Spencer09906f32006-12-04 21:33:23 +00002622 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002623 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002624 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002625 // result. This is particularly useful for computing loop exit values.
2626 if (CanConstantFold(I)) {
2627 std::vector<Constant*> Operands;
2628 Operands.reserve(I->getNumOperands());
2629 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2630 Value *Op = I->getOperand(i);
2631 if (Constant *C = dyn_cast<Constant>(Op)) {
2632 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002633 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002634 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00002635 // non-integer and non-pointer, don't even try to analyze them
2636 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00002637 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00002638 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00002639
Chris Lattner3221ad02004-04-17 22:58:41 +00002640 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman4acd12a2009-04-30 16:40:30 +00002641 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
2642 Constant *C = SC->getValue();
2643 if (C->getType() != Op->getType())
2644 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2645 Op->getType(),
2646 false),
2647 C, Op->getType());
2648 Operands.push_back(C);
2649 } else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2650 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2651 if (C->getType() != Op->getType())
2652 C =
2653 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2654 Op->getType(),
2655 false),
2656 C, Op->getType());
2657 Operands.push_back(C);
2658 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00002659 return V;
2660 } else {
2661 return V;
2662 }
2663 }
2664 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002665
2666 Constant *C;
2667 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2668 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2669 &Operands[0], Operands.size());
2670 else
2671 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2672 &Operands[0], Operands.size());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002673 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002674 }
2675 }
2676
2677 // This is some other type of SCEVUnknown, just return it.
2678 return V;
2679 }
2680
Chris Lattner53e677a2004-04-02 20:23:17 +00002681 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2682 // Avoid performing the look-up in the common case where the specified
2683 // expression has no loop-variant portions.
2684 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2685 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2686 if (OpAtScope != Comm->getOperand(i)) {
2687 if (OpAtScope == UnknownValue) return UnknownValue;
2688 // Okay, at least one of these operands is loop variant but might be
2689 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002690 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002691 NewOps.push_back(OpAtScope);
2692
2693 for (++i; i != e; ++i) {
2694 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2695 if (OpAtScope == UnknownValue) return UnknownValue;
2696 NewOps.push_back(OpAtScope);
2697 }
2698 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002699 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002700 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002701 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002702 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002703 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002704 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002705 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002706 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002707 }
2708 }
2709 // If we got here, all operands are loop invariant.
2710 return Comm;
2711 }
2712
Nick Lewycky789558d2009-01-13 09:18:58 +00002713 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2714 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002715 if (LHS == UnknownValue) return LHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002716 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002717 if (RHS == UnknownValue) return RHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002718 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2719 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002720 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002721 }
2722
2723 // If this is a loop recurrence for a loop that does not contain L, then we
2724 // are dealing with the final value computed by the loop.
2725 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2726 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2727 // To evaluate this recurrence, we need to know how many times the AddRec
2728 // loop iterates. Compute this now.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002729 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2730 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002731
Eli Friedmanb42a6262008-08-04 23:49:06 +00002732 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002733 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002734 }
2735 return UnknownValue;
2736 }
2737
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002738 if (SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
2739 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2740 if (Op == UnknownValue) return Op;
2741 if (Op == Cast->getOperand())
2742 return Cast; // must be loop invariant
2743 return getZeroExtendExpr(Op, Cast->getType());
2744 }
2745
2746 if (SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
2747 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2748 if (Op == UnknownValue) return Op;
2749 if (Op == Cast->getOperand())
2750 return Cast; // must be loop invariant
2751 return getSignExtendExpr(Op, Cast->getType());
2752 }
2753
2754 if (SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
2755 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2756 if (Op == UnknownValue) return Op;
2757 if (Op == Cast->getOperand())
2758 return Cast; // must be loop invariant
2759 return getTruncateExpr(Op, Cast->getType());
2760 }
2761
2762 assert(0 && "Unknown SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002763}
2764
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002765/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2766/// at the specified scope in the program. The L value specifies a loop
2767/// nest to evaluate the expression at, where null is the top-level or a
2768/// specified loop is immediately inside of the loop.
2769///
2770/// This method can be used to compute the exit value for a variable defined
2771/// in a loop by querying what the value will hold in the parent loop.
2772///
2773/// If this value is not computable at this scope, a SCEVCouldNotCompute
2774/// object is returned.
2775SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2776 return getSCEVAtScope(getSCEV(V), L);
2777}
2778
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002779/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2780/// following equation:
2781///
2782/// A * X = B (mod N)
2783///
2784/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2785/// A and B isn't important.
2786///
2787/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2788static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2789 ScalarEvolution &SE) {
2790 uint32_t BW = A.getBitWidth();
2791 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2792 assert(A != 0 && "A must be non-zero.");
2793
2794 // 1. D = gcd(A, N)
2795 //
2796 // The gcd of A and N may have only one prime factor: 2. The number of
2797 // trailing zeros in A is its multiplicity
2798 uint32_t Mult2 = A.countTrailingZeros();
2799 // D = 2^Mult2
2800
2801 // 2. Check if B is divisible by D.
2802 //
2803 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2804 // is not less than multiplicity of this prime factor for D.
2805 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002806 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002807
2808 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2809 // modulo (N / D).
2810 //
2811 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2812 // bit width during computations.
2813 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2814 APInt Mod(BW + 1, 0);
2815 Mod.set(BW - Mult2); // Mod = N / D
2816 APInt I = AD.multiplicativeInverse(Mod);
2817
2818 // 4. Compute the minimum unsigned root of the equation:
2819 // I * (B / D) mod (N / D)
2820 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2821
2822 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2823 // bits.
2824 return SE.getConstant(Result.trunc(BW));
2825}
Chris Lattner53e677a2004-04-02 20:23:17 +00002826
2827/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2828/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2829/// might be the same) or two SCEVCouldNotCompute objects.
2830///
2831static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002832SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002833 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002834 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2835 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2836 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002837
Chris Lattner53e677a2004-04-02 20:23:17 +00002838 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002839 if (!LC || !MC || !NC) {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002840 SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00002841 return std::make_pair(CNC, CNC);
2842 }
2843
Reid Spencere8019bb2007-03-01 07:25:48 +00002844 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002845 const APInt &L = LC->getValue()->getValue();
2846 const APInt &M = MC->getValue()->getValue();
2847 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002848 APInt Two(BitWidth, 2);
2849 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002850
Reid Spencere8019bb2007-03-01 07:25:48 +00002851 {
2852 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002853 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002854 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2855 // The B coefficient is M-N/2
2856 APInt B(M);
2857 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002858
Reid Spencere8019bb2007-03-01 07:25:48 +00002859 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002860 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002861
Reid Spencere8019bb2007-03-01 07:25:48 +00002862 // Compute the B^2-4ac term.
2863 APInt SqrtTerm(B);
2864 SqrtTerm *= B;
2865 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002866
Reid Spencere8019bb2007-03-01 07:25:48 +00002867 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2868 // integer value or else APInt::sqrt() will assert.
2869 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002870
Reid Spencere8019bb2007-03-01 07:25:48 +00002871 // Compute the two solutions for the quadratic formula.
2872 // The divisions must be performed as signed divisions.
2873 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002874 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002875 if (TwoA.isMinValue()) {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002876 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002877 return std::make_pair(CNC, CNC);
2878 }
2879
Reid Spencere8019bb2007-03-01 07:25:48 +00002880 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2881 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002882
Dan Gohman246b2562007-10-22 18:31:58 +00002883 return std::make_pair(SE.getConstant(Solution1),
2884 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002885 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002886}
2887
2888/// HowFarToZero - Return the number of times a backedge comparing the specified
2889/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002890SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002891 // If the value is a constant
2892 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2893 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002894 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002895 return UnknownValue; // Otherwise it will loop infinitely.
2896 }
2897
2898 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2899 if (!AddRec || AddRec->getLoop() != L)
2900 return UnknownValue;
2901
2902 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002903 // If this is an affine expression, the execution count of this branch is
2904 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002905 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002906 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002907 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002908 // equivalent to:
2909 //
2910 // Step*N = -Start (mod 2^BW)
2911 //
2912 // where BW is the common bit width of Start and Step.
2913
Chris Lattner53e677a2004-04-02 20:23:17 +00002914 // Get the initial value for the loop.
2915 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002916 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002917
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002918 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002919
Chris Lattner53e677a2004-04-02 20:23:17 +00002920 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002921 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002922
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002923 // First, handle unitary steps.
2924 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002925 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002926 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2927 return Start; // N = Start (as unsigned)
2928
2929 // Then, try to solve the above equation provided that Start is constant.
2930 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2931 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002932 -StartC->getValue()->getValue(),
2933 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002934 }
Chris Lattner42a75512007-01-15 02:27:26 +00002935 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002936 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2937 // the quadratic equation to solve it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002938 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2939 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002940 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2941 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2942 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002943#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002944 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2945 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002946#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002947 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002948 if (ConstantInt *CB =
2949 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002950 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002951 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002952 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002953
Chris Lattner53e677a2004-04-02 20:23:17 +00002954 // We can only use this value if the chrec ends up with an exact zero
2955 // value at this index. When solving for "X*X != 5", for example, we
2956 // should not accept a root of 2.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002957 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002958 if (Val->isZero())
2959 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002960 }
2961 }
2962 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002963
Chris Lattner53e677a2004-04-02 20:23:17 +00002964 return UnknownValue;
2965}
2966
2967/// HowFarToNonZero - Return the number of times a backedge checking the
2968/// specified value for nonzero will execute. If not computable, return
2969/// UnknownValue
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002970SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002971 // Loops that look like: while (X == 0) are very strange indeed. We don't
2972 // handle them yet except for the trivial case. This could be expanded in the
2973 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002974
Chris Lattner53e677a2004-04-02 20:23:17 +00002975 // If the value is a constant, check to see if it is known to be non-zero
2976 // already. If so, the backedge will execute zero times.
2977 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002978 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002979 return getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002980 return UnknownValue; // Otherwise it will loop infinitely.
2981 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002982
Chris Lattner53e677a2004-04-02 20:23:17 +00002983 // We could implement others, but I really doubt anyone writes loops like
2984 // this, and if they did, they would already be constant folded.
2985 return UnknownValue;
2986}
2987
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002988/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2989/// (which may not be an immediate predecessor) which has exactly one
2990/// successor from which BB is reachable, or null if no such block is
2991/// found.
2992///
2993BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002994ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00002995 // If the block has a unique predecessor, then there is no path from the
2996 // predecessor to the block that does not go through the direct edge
2997 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002998 if (BasicBlock *Pred = BB->getSinglePredecessor())
2999 return Pred;
3000
3001 // A loop's header is defined to be a block that dominates the loop.
3002 // If the loop has a preheader, it must be a block that has exactly
3003 // one successor that can reach BB. This is slightly more strict
3004 // than necessary, but works if critical edges are split.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003005 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003006 return L->getLoopPreheader();
3007
3008 return 0;
3009}
3010
Dan Gohmanc2390b12009-02-12 22:19:27 +00003011/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003012/// a conditional between LHS and RHS. This is used to help avoid max
3013/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003014bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003015 ICmpInst::Predicate Pred,
3016 SCEV *LHS, SCEV *RHS) {
Nick Lewycky59cff122008-07-12 07:41:32 +00003017 BasicBlock *Preheader = L->getLoopPreheader();
3018 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003019
Dan Gohman38372182008-08-12 20:17:31 +00003020 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003021 // there are predecessors that can be found that have unique successors
3022 // leading to the original header.
3023 for (; Preheader;
3024 PreheaderDest = Preheader,
3025 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00003026
3027 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00003028 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003029 if (!LoopEntryPredicate ||
3030 LoopEntryPredicate->isUnconditional())
3031 continue;
3032
3033 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3034 if (!ICI) continue;
3035
3036 // Now that we found a conditional branch that dominates the loop, check to
3037 // see if it is the comparison we are looking for.
3038 Value *PreCondLHS = ICI->getOperand(0);
3039 Value *PreCondRHS = ICI->getOperand(1);
3040 ICmpInst::Predicate Cond;
3041 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3042 Cond = ICI->getPredicate();
3043 else
3044 Cond = ICI->getInversePredicate();
3045
Dan Gohmanc2390b12009-02-12 22:19:27 +00003046 if (Cond == Pred)
3047 ; // An exact match.
3048 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3049 ; // The actual condition is beyond sufficient.
3050 else
3051 // Check a few special cases.
3052 switch (Cond) {
3053 case ICmpInst::ICMP_UGT:
3054 if (Pred == ICmpInst::ICMP_ULT) {
3055 std::swap(PreCondLHS, PreCondRHS);
3056 Cond = ICmpInst::ICMP_ULT;
3057 break;
3058 }
3059 continue;
3060 case ICmpInst::ICMP_SGT:
3061 if (Pred == ICmpInst::ICMP_SLT) {
3062 std::swap(PreCondLHS, PreCondRHS);
3063 Cond = ICmpInst::ICMP_SLT;
3064 break;
3065 }
3066 continue;
3067 case ICmpInst::ICMP_NE:
3068 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3069 // so check for this case by checking if the NE is comparing against
3070 // a minimum or maximum constant.
3071 if (!ICmpInst::isTrueWhenEqual(Pred))
3072 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3073 const APInt &A = CI->getValue();
3074 switch (Pred) {
3075 case ICmpInst::ICMP_SLT:
3076 if (A.isMaxSignedValue()) break;
3077 continue;
3078 case ICmpInst::ICMP_SGT:
3079 if (A.isMinSignedValue()) break;
3080 continue;
3081 case ICmpInst::ICMP_ULT:
3082 if (A.isMaxValue()) break;
3083 continue;
3084 case ICmpInst::ICMP_UGT:
3085 if (A.isMinValue()) break;
3086 continue;
3087 default:
3088 continue;
3089 }
3090 Cond = ICmpInst::ICMP_NE;
3091 // NE is symmetric but the original comparison may not be. Swap
3092 // the operands if necessary so that they match below.
3093 if (isa<SCEVConstant>(LHS))
3094 std::swap(PreCondLHS, PreCondRHS);
3095 break;
3096 }
3097 continue;
3098 default:
3099 // We weren't able to reconcile the condition.
3100 continue;
3101 }
Dan Gohman38372182008-08-12 20:17:31 +00003102
3103 if (!PreCondLHS->getType()->isInteger()) continue;
3104
3105 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3106 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3107 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003108 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3109 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohman38372182008-08-12 20:17:31 +00003110 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003111 }
3112
Dan Gohman38372182008-08-12 20:17:31 +00003113 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003114}
3115
Chris Lattnerdb25de42005-08-15 23:33:51 +00003116/// HowManyLessThans - Return the number of times a backedge containing the
3117/// specified less-than comparison will execute. If not computable, return
3118/// UnknownValue.
Dan Gohmana1af7572009-04-30 20:47:05 +00003119ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Nick Lewycky789558d2009-01-13 09:18:58 +00003120HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003121 // Only handle: "ADDREC < LoopInvariant".
3122 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3123
3124 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3125 if (!AddRec || AddRec->getLoop() != L)
3126 return UnknownValue;
3127
3128 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003129 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00003130 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3131 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3132 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3133
3134 // TODO: handle non-constant strides.
3135 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3136 if (!CStep || CStep->isZero())
3137 return UnknownValue;
3138 if (CStep->getValue()->getValue() == 1) {
3139 // With unit stride, the iteration never steps past the limit value.
3140 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3141 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3142 // Test whether a positive iteration iteration can step past the limit
3143 // value and past the maximum value for its type in a single step.
3144 if (isSigned) {
3145 APInt Max = APInt::getSignedMaxValue(BitWidth);
3146 if ((Max - CStep->getValue()->getValue())
3147 .slt(CLimit->getValue()->getValue()))
3148 return UnknownValue;
3149 } else {
3150 APInt Max = APInt::getMaxValue(BitWidth);
3151 if ((Max - CStep->getValue()->getValue())
3152 .ult(CLimit->getValue()->getValue()))
3153 return UnknownValue;
3154 }
3155 } else
3156 // TODO: handle non-constant limit values below.
3157 return UnknownValue;
3158 } else
3159 // TODO: handle negative strides below.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003160 return UnknownValue;
3161
Dan Gohmana1af7572009-04-30 20:47:05 +00003162 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3163 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3164 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00003165 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003166
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003167 // First, we get the value of the LHS in the first iteration: n
3168 SCEVHandle Start = AddRec->getOperand(0);
3169
Dan Gohmana1af7572009-04-30 20:47:05 +00003170 // Determine the minimum constant start value.
3171 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3172 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3173 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003174
Dan Gohmana1af7572009-04-30 20:47:05 +00003175 // If we know that the condition is true in order to enter the loop,
3176 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3177 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3178 // division must round up.
3179 SCEVHandle End = RHS;
3180 if (!isLoopGuardedByCond(L,
3181 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3182 getMinusSCEV(Start, Step), RHS))
3183 End = isSigned ? getSMaxExpr(RHS, Start)
3184 : getUMaxExpr(RHS, Start);
3185
3186 // Determine the maximum constant end value.
3187 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3188 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3189 APInt::getMaxValue(BitWidth));
3190
3191 // Finally, we subtract these two values and divide, rounding up, to get
3192 // the number of times the backedge is executed.
3193 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3194 getAddExpr(Step, NegOne)),
3195 Step);
3196
3197 // The maximum backedge count is similar, except using the minimum start
3198 // value and the maximum end value.
3199 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3200 MinStart),
3201 getAddExpr(Step, NegOne)),
3202 Step);
3203
3204 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003205 }
3206
3207 return UnknownValue;
3208}
3209
Chris Lattner53e677a2004-04-02 20:23:17 +00003210/// getNumIterationsInRange - Return the number of iterations of this loop that
3211/// produce values in the specified constant range. Another way of looking at
3212/// this is that it returns the first iteration number where the value is not in
3213/// the condition, thus computing the exit count. If the iteration count can't
3214/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003215SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3216 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003217 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003218 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003219
3220 // If the start is a non-zero constant, shift the range to simplify things.
3221 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003222 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003223 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003224 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3225 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003226 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3227 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003228 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003229 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003230 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003231 }
3232
3233 // The only time we can solve this is when we have all constant indices.
3234 // Otherwise, we cannot determine the overflow conditions.
3235 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3236 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003237 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003238
3239
3240 // Okay at this point we know that all elements of the chrec are constants and
3241 // that the start element is zero.
3242
3243 // First check to see if the range contains zero. If not, the first
3244 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003245 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00003246 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman246b2562007-10-22 18:31:58 +00003247 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003248
Chris Lattner53e677a2004-04-02 20:23:17 +00003249 if (isAffine()) {
3250 // If this is an affine expression then we have this situation:
3251 // Solve {0,+,A} in Range === Ax in Range
3252
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003253 // We know that zero is in the range. If A is positive then we know that
3254 // the upper value of the range must be the first possible exit value.
3255 // If A is negative then the lower of the range is the last possible loop
3256 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00003257 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003258 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3259 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003260
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003261 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003262 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003263 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003264
3265 // Evaluate at the exit value. If we really did fall out of the valid
3266 // range, then we computed our trip count, otherwise wrap around or other
3267 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003268 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003269 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003270 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003271
3272 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003273 assert(Range.contains(
3274 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003275 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003276 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003277 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003278 } else if (isQuadratic()) {
3279 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3280 // quadratic equation to solve it. To do this, we must frame our problem in
3281 // terms of figuring out when zero is crossed, instead of when
3282 // Range.getUpper() is crossed.
3283 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003284 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3285 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003286
3287 // Next, solve the constructed addrec
3288 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003289 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003290 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3291 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3292 if (R1) {
3293 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003294 if (ConstantInt *CB =
3295 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003296 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003297 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003298 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003299
Chris Lattner53e677a2004-04-02 20:23:17 +00003300 // Make sure the root is not off by one. The returned iteration should
3301 // not be in the range, but the previous one should be. When solving
3302 // for "X*X < 5", for example, we should not return a root of 2.
3303 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003304 R1->getValue(),
3305 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003306 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003307 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003308 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003309
Dan Gohman246b2562007-10-22 18:31:58 +00003310 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003311 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003312 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003313 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003314 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003315
Chris Lattner53e677a2004-04-02 20:23:17 +00003316 // If R1 was not in the range, then it is a good return value. Make
3317 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003318 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003319 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003320 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003321 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003322 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003323 }
3324 }
3325 }
3326
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003327 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003328}
3329
3330
3331
3332//===----------------------------------------------------------------------===//
3333// ScalarEvolution Class Implementation
3334//===----------------------------------------------------------------------===//
3335
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003336ScalarEvolution::ScalarEvolution()
3337 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3338}
3339
Chris Lattner53e677a2004-04-02 20:23:17 +00003340bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003341 this->F = &F;
3342 LI = &getAnalysis<LoopInfo>();
3343 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00003344 return false;
3345}
3346
3347void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003348 Scalars.clear();
3349 BackedgeTakenCounts.clear();
3350 ConstantEvolutionLoopExitValue.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00003351}
3352
3353void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3354 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003355 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00003356}
3357
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003358bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003359 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00003360}
3361
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003362static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003363 const Loop *L) {
3364 // Print all inner loops first
3365 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3366 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003367
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003368 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003369
Devang Patelb7211a22007-08-21 00:31:24 +00003370 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003371 L->getExitBlocks(ExitBlocks);
3372 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003373 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003374
Dan Gohman46bdfb02009-02-24 18:55:53 +00003375 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3376 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003377 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003378 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003379 }
3380
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003381 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003382}
3383
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003384void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003385 // ScalarEvolution's implementaiton of the print method is to print
3386 // out SCEV values of all instructions that are interesting. Doing
3387 // this potentially causes it to create new SCEV objects though,
3388 // which technically conflicts with the const qualifier. This isn't
3389 // observable from outside the class though (the hasSCEV function
3390 // notwithstanding), so casting away the const isn't dangerous.
3391 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003392
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003393 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003394 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00003395 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003396 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003397 OS << " --> ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003398 SCEVHandle SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003399 SV->print(OS);
3400 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003401
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003402 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003403 OS << "Exits: ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003404 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003405 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3406 OS << "<<Unknown>>";
3407 } else {
3408 OS << *ExitValue;
3409 }
3410 }
3411
3412
3413 OS << "\n";
3414 }
3415
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003416 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3417 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3418 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003419}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003420
3421void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3422 raw_os_ostream OS(o);
3423 print(OS, M);
3424}