blob: 9c6941f0d318b4e263c603f9e3bb2a0db5171223 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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.
31//
32// 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//
36// 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
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
Dan Gohmana7726c32009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000073#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074#include "llvm/Support/CommandLine.h"
75#include "llvm/Support/Compiler.h"
76#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000077#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078#include "llvm/Support/InstIterator.h"
79#include "llvm/Support/ManagedStatic.h"
80#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000081#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000083#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085using namespace llvm;
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman089efff2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman089efff2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104char ScalarEvolution::ID = 0;
105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122}
123
Dan Gohman7b560c42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohmanf8bc8e82009-05-18 15:22:39 +0000130bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
133 return false;
134}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135
136SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000137SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138
139bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
141 return false;
142}
143
144const Type *SCEVCouldNotCompute::getType() const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return 0;
147}
148
149bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
151 return false;
152}
153
154SCEVHandle SCEVCouldNotCompute::
155replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000156 const SCEVHandle &Conc,
157 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 return this;
159}
160
Dan Gohman13058cc2009-04-21 00:47:46 +0000161void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 OS << "***COULDNOTCOMPUTE***";
163}
164
165bool SCEVCouldNotCompute::classof(const SCEV *S) {
166 return S->getSCEVType() == scCouldNotCompute;
167}
168
169
170// SCEVConstants - Only allow the creation of one SCEVConstant for any
171// particular value. Don't use a SCEVHandle here, or else the object will
172// never be deleted!
173static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
174
175
176SCEVConstant::~SCEVConstant() {
177 SCEVConstants->erase(V);
178}
179
Dan Gohman89f85052007-10-22 18:31:58 +0000180SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 SCEVConstant *&R = (*SCEVConstants)[V];
182 if (R == 0) R = new SCEVConstant(V);
183 return R;
184}
185
Dan Gohman89f85052007-10-22 18:31:58 +0000186SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
187 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188}
189
Dan Gohman8fd520a2009-06-15 22:12:54 +0000190SCEVHandle
191ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
192 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
193}
194
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
196
Dan Gohman13058cc2009-04-21 00:47:46 +0000197void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 WriteAsOperand(OS, V, false);
199}
200
Dan Gohman2a381532009-04-21 01:25:57 +0000201SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
202 const SCEVHandle &op, const Type *ty)
203 : SCEV(SCEVTy), Op(op), Ty(ty) {}
204
205SCEVCastExpr::~SCEVCastExpr() {}
206
207bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
208 return Op->dominates(BB, DT);
209}
210
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
212// particular input. Don't use a SCEVHandle here, or else the object will
213// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000214static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 SCEVTruncateExpr*> > SCEVTruncates;
216
217SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000218 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000219 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
220 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222}
223
224SCEVTruncateExpr::~SCEVTruncateExpr() {
225 SCEVTruncates->erase(std::make_pair(Op, Ty));
226}
227
Dan Gohman13058cc2009-04-21 00:47:46 +0000228void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000229 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230}
231
232// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
233// particular input. Don't use a SCEVHandle here, or else the object will never
234// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000235static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 SCEVZeroExtendExpr*> > SCEVZeroExtends;
237
238SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000239 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000240 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
241 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243}
244
245SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
246 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
247}
248
Dan Gohman13058cc2009-04-21 00:47:46 +0000249void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000250 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251}
252
253// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254// particular input. Don't use a SCEVHandle here, or else the object will never
255// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000256static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 SCEVSignExtendExpr*> > SCEVSignExtends;
258
259SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000260 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000261 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
262 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264}
265
266SCEVSignExtendExpr::~SCEVSignExtendExpr() {
267 SCEVSignExtends->erase(std::make_pair(Op, Ty));
268}
269
Dan Gohman13058cc2009-04-21 00:47:46 +0000270void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000271 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272}
273
274// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
275// particular input. Don't use a SCEVHandle here, or else the object will never
276// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000277static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 SCEVCommutativeExpr*> > SCEVCommExprs;
279
280SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000281 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
282 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283}
284
Dan Gohman13058cc2009-04-21 00:47:46 +0000285void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
287 const char *OpStr = getOperationStr();
288 OS << "(" << *Operands[0];
289 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
290 OS << OpStr << *Operands[i];
291 OS << ")";
292}
293
294SCEVHandle SCEVCommutativeExpr::
295replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000296 const SCEVHandle &Conc,
297 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000299 SCEVHandle H =
300 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 if (H != getOperand(i)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000302 SmallVector<SCEVHandle, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 NewOps.reserve(getNumOperands());
304 for (unsigned j = 0; j != i; ++j)
305 NewOps.push_back(getOperand(j));
306 NewOps.push_back(H);
307 for (++i; i != e; ++i)
308 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000309 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310
311 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000312 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000314 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000315 else if (isa<SCEVSMaxExpr>(this))
316 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000317 else if (isa<SCEVUMaxExpr>(this))
318 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 else
320 assert(0 && "Unknown commutative expr!");
321 }
322 }
323 return this;
324}
325
Dan Gohman72a8a022009-05-07 14:00:19 +0000326bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000327 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
328 if (!getOperand(i)->dominates(BB, DT))
329 return false;
330 }
331 return true;
332}
333
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336// input. Don't use a SCEVHandle here, or else the object will never be
337// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000338static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000339 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000341SCEVUDivExpr::~SCEVUDivExpr() {
342 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343}
344
Evan Cheng98c073b2009-02-17 00:13:06 +0000345bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
346 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
347}
348
Dan Gohman13058cc2009-04-21 00:47:46 +0000349void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000350 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351}
352
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000353const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000354 // In most cases the types of LHS and RHS will be the same, but in some
355 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
356 // depend on the type for correctness, but handling types carefully can
357 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
358 // a pointer type than the RHS, so use the RHS' type here.
359 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360}
361
362// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
363// particular input. Don't use a SCEVHandle here, or else the object will never
364// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000365static ManagedStatic<std::map<std::pair<const Loop *,
366 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 SCEVAddRecExpr*> > SCEVAddRecExprs;
368
369SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000370 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
371 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372}
373
374SCEVHandle SCEVAddRecExpr::
375replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000376 const SCEVHandle &Conc,
377 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000379 SCEVHandle H =
380 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 if (H != getOperand(i)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000382 SmallVector<SCEVHandle, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 NewOps.reserve(getNumOperands());
384 for (unsigned j = 0; j != i; ++j)
385 NewOps.push_back(getOperand(j));
386 NewOps.push_back(H);
387 for (++i; i != e; ++i)
388 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000389 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390
Dan Gohman89f85052007-10-22 18:31:58 +0000391 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 }
393 }
394 return this;
395}
396
397
398bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
399 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
400 // contain L and if the start is invariant.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000401 // Add recurrences are never invariant in the function-body (null loop).
402 return QueryLoop &&
403 !QueryLoop->contains(L->getHeader()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 getOperand(0)->isLoopInvariant(QueryLoop);
405}
406
407
Dan Gohman13058cc2009-04-21 00:47:46 +0000408void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 OS << "{" << *Operands[0];
410 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
411 OS << ",+," << *Operands[i];
412 OS << "}<" << L->getHeader()->getName() + ">";
413}
414
415// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
416// value. Don't use a SCEVHandle here, or else the object will never be
417// deleted!
418static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
419
420SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
421
422bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
423 // All non-instruction values are loop invariant. All instructions are loop
424 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000425 // Instructions are never considered invariant in the function body
426 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000428 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 return true;
430}
431
Evan Cheng98c073b2009-02-17 00:13:06 +0000432bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
433 if (Instruction *I = dyn_cast<Instruction>(getValue()))
434 return DT->dominates(I->getParent(), BB);
435 return true;
436}
437
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438const Type *SCEVUnknown::getType() const {
439 return V->getType();
440}
441
Dan Gohman13058cc2009-04-21 00:47:46 +0000442void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 WriteAsOperand(OS, V, false);
444}
445
446//===----------------------------------------------------------------------===//
447// SCEV Utilities
448//===----------------------------------------------------------------------===//
449
450namespace {
451 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
452 /// than the complexity of the RHS. This comparator is used to canonicalize
453 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000454 class VISIBILITY_HIDDEN SCEVComplexityCompare {
455 LoopInfo *LI;
456 public:
457 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
458
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000459 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000460 // Primarily, sort the SCEVs by their getSCEVType().
461 if (LHS->getSCEVType() != RHS->getSCEVType())
462 return LHS->getSCEVType() < RHS->getSCEVType();
463
464 // Aside from the getSCEVType() ordering, the particular ordering
465 // isn't very important except that it's beneficial to be consistent,
466 // so that (a + b) and (b + a) don't end up as different expressions.
467
468 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
469 // not as complete as it could be.
470 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
471 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
472
Dan Gohmand0c01232009-05-19 02:15:55 +0000473 // Order pointer values after integer values. This helps SCEVExpander
474 // form GEPs.
475 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
476 return false;
477 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
478 return true;
479
Dan Gohman5d486452009-05-07 14:39:04 +0000480 // Compare getValueID values.
481 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
482 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
483
484 // Sort arguments by their position.
485 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
486 const Argument *RA = cast<Argument>(RU->getValue());
487 return LA->getArgNo() < RA->getArgNo();
488 }
489
490 // For instructions, compare their loop depth, and their opcode.
491 // This is pretty loose.
492 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
493 Instruction *RV = cast<Instruction>(RU->getValue());
494
495 // Compare loop depths.
496 if (LI->getLoopDepth(LV->getParent()) !=
497 LI->getLoopDepth(RV->getParent()))
498 return LI->getLoopDepth(LV->getParent()) <
499 LI->getLoopDepth(RV->getParent());
500
501 // Compare opcodes.
502 if (LV->getOpcode() != RV->getOpcode())
503 return LV->getOpcode() < RV->getOpcode();
504
505 // Compare the number of operands.
506 if (LV->getNumOperands() != RV->getNumOperands())
507 return LV->getNumOperands() < RV->getNumOperands();
508 }
509
510 return false;
511 }
512
Dan Gohman56fc8f12009-06-14 22:51:25 +0000513 // Compare constant values.
514 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
515 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
516 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
517 }
518
519 // Compare addrec loop depths.
520 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
521 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
522 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
523 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
524 }
Dan Gohman5d486452009-05-07 14:39:04 +0000525
526 // Lexicographically compare n-ary expressions.
527 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
528 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
529 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
530 if (i >= RC->getNumOperands())
531 return false;
532 if (operator()(LC->getOperand(i), RC->getOperand(i)))
533 return true;
534 if (operator()(RC->getOperand(i), LC->getOperand(i)))
535 return false;
536 }
537 return LC->getNumOperands() < RC->getNumOperands();
538 }
539
Dan Gohman6e10db12009-05-07 19:23:21 +0000540 // Lexicographically compare udiv expressions.
541 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
542 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
543 if (operator()(LC->getLHS(), RC->getLHS()))
544 return true;
545 if (operator()(RC->getLHS(), LC->getLHS()))
546 return false;
547 if (operator()(LC->getRHS(), RC->getRHS()))
548 return true;
549 if (operator()(RC->getRHS(), LC->getRHS()))
550 return false;
551 return false;
552 }
553
Dan Gohman5d486452009-05-07 14:39:04 +0000554 // Compare cast expressions by operand.
555 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
556 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
557 return operator()(LC->getOperand(), RC->getOperand());
558 }
559
560 assert(0 && "Unknown SCEV kind!");
561 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562 }
563 };
564}
565
566/// GroupByComplexity - Given a list of SCEV objects, order them by their
567/// complexity, and group objects of the same complexity together by value.
568/// When this routine is finished, we know that any duplicates in the vector are
569/// consecutive and that complexity is monotonically increasing.
570///
571/// Note that we go take special precautions to ensure that we get determinstic
572/// results from this routine. In other words, we don't want the results of
573/// this to depend on where the addresses of various SCEV objects happened to
574/// land in memory.
575///
Dan Gohman02ff9392009-06-14 22:47:23 +0000576static void GroupByComplexity(SmallVectorImpl<SCEVHandle> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000577 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 if (Ops.size() < 2) return; // Noop
579 if (Ops.size() == 2) {
580 // This is the common case, which also happens to be trivially simple.
581 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000582 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 std::swap(Ops[0], Ops[1]);
584 return;
585 }
586
587 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000588 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589
590 // Now that we are sorted by complexity, group elements of the same
591 // complexity. Note that this is, at worst, N^2, but the vector is likely to
592 // be extremely short in practice. Note that we take this approach because we
593 // do not want to depend on the addresses of the objects we are grouping.
594 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000595 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 unsigned Complexity = S->getSCEVType();
597
598 // If there are any objects of the same complexity and same value as this
599 // one, group them.
600 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
601 if (Ops[j] == S) { // Found a duplicate.
602 // Move it to immediately after i'th element.
603 std::swap(Ops[i+1], Ops[j]);
604 ++i; // no need to rescan it.
605 if (i == e-2) return; // Done!
606 }
607 }
608 }
609}
610
611
612
613//===----------------------------------------------------------------------===//
614// Simple SCEV method implementations
615//===----------------------------------------------------------------------===//
616
Eli Friedman7489ec92008-08-04 23:49:06 +0000617/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000618/// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000619static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000620 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000621 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000622 // Handle the simplest case efficiently.
623 if (K == 1)
624 return SE.getTruncateOrZeroExtend(It, ResultTy);
625
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000626 // We are using the following formula for BC(It, K):
627 //
628 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
629 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000630 // Suppose, W is the bitwidth of the return value. We must be prepared for
631 // overflow. Hence, we must assure that the result of our computation is
632 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
633 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000634 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000635 // However, this code doesn't use exactly that formula; the formula it uses
636 // is something like the following, where T is the number of factors of 2 in
637 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
638 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000639 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000640 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000641 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000642 // This formula is trivially equivalent to the previous formula. However,
643 // this formula can be implemented much more efficiently. The trick is that
644 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
645 // arithmetic. To do exact division in modular arithmetic, all we have
646 // to do is multiply by the inverse. Therefore, this step can be done at
647 // width W.
648 //
649 // The next issue is how to safely do the division by 2^T. The way this
650 // is done is by doing the multiplication step at a width of at least W + T
651 // bits. This way, the bottom W+T bits of the product are accurate. Then,
652 // when we perform the division by 2^T (which is equivalent to a right shift
653 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
654 // truncated out after the division by 2^T.
655 //
656 // In comparison to just directly using the first formula, this technique
657 // is much more efficient; using the first formula requires W * K bits,
658 // but this formula less than W + K bits. Also, the first formula requires
659 // a division step, whereas this formula only requires multiplies and shifts.
660 //
661 // It doesn't matter whether the subtraction step is done in the calculation
662 // width or the input iteration count's width; if the subtraction overflows,
663 // the result must be zero anyway. We prefer here to do it in the width of
664 // the induction variable because it helps a lot for certain cases; CodeGen
665 // isn't smart enough to ignore the overflow, which leads to much less
666 // efficient code if the width of the subtraction is wider than the native
667 // register width.
668 //
669 // (It's possible to not widen at all by pulling out factors of 2 before
670 // the multiplication; for example, K=2 can be calculated as
671 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
672 // extra arithmetic, so it's not an obvious win, and it gets
673 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000674
Eli Friedman7489ec92008-08-04 23:49:06 +0000675 // Protection from insane SCEVs; this bound is conservative,
676 // but it probably doesn't matter.
677 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000678 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000679
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000680 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000681
Eli Friedman7489ec92008-08-04 23:49:06 +0000682 // Calculate K! / 2^T and T; we divide out the factors of two before
683 // multiplying for calculating K! / 2^T to avoid overflow.
684 // Other overflow doesn't matter because we only care about the bottom
685 // W bits of the result.
686 APInt OddFactorial(W, 1);
687 unsigned T = 1;
688 for (unsigned i = 3; i <= K; ++i) {
689 APInt Mult(W, i);
690 unsigned TwoFactors = Mult.countTrailingZeros();
691 T += TwoFactors;
692 Mult = Mult.lshr(TwoFactors);
693 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000695
Eli Friedman7489ec92008-08-04 23:49:06 +0000696 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000697 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000698
699 // Calcuate 2^T, at width T+W.
700 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
701
702 // Calculate the multiplicative inverse of K! / 2^T;
703 // this multiplication factor will perform the exact division by
704 // K! / 2^T.
705 APInt Mod = APInt::getSignedMinValue(W+1);
706 APInt MultiplyFactor = OddFactorial.zext(W+1);
707 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
708 MultiplyFactor = MultiplyFactor.trunc(W);
709
710 // Calculate the product, at width T+W
711 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
712 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
713 for (unsigned i = 1; i != K; ++i) {
714 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
715 Dividend = SE.getMulExpr(Dividend,
716 SE.getTruncateOrZeroExtend(S, CalculationTy));
717 }
718
719 // Divide by 2^T
720 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
721
722 // Truncate the result, and divide by K! / 2^T.
723
724 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
725 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726}
727
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728/// evaluateAtIteration - Return the value of this chain of recurrences at
729/// the specified iteration number. We can evaluate this recurrence by
730/// multiplying each element in the chain by the binomial coefficient
731/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
732///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000733/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000735/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736///
Dan Gohman89f85052007-10-22 18:31:58 +0000737SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
738 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000741 // The computation is correct in the face of overflow provided that the
742 // multiplication is performed _after_ the evaluation of the binomial
743 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000744 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000745 if (isa<SCEVCouldNotCompute>(Coeff))
746 return Coeff;
747
748 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 }
750 return Result;
751}
752
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753//===----------------------------------------------------------------------===//
754// SCEV Expression folder implementations
755//===----------------------------------------------------------------------===//
756
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000757SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
758 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000759 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000760 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000761 assert(isSCEVable(Ty) &&
762 "This is not a conversion to a SCEVable type!");
763 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000764
Dan Gohmanc76b5452009-05-04 22:02:23 +0000765 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000766 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 ConstantExpr::getTrunc(SC->getValue(), Ty));
768
Dan Gohman1a5c4992009-04-22 16:20:48 +0000769 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000770 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000771 return getTruncateExpr(ST->getOperand(), Ty);
772
Nick Lewycky37d04642009-04-23 05:15:08 +0000773 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000774 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000775 return getTruncateOrSignExtend(SS->getOperand(), Ty);
776
777 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000778 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000779 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
780
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000781 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000782 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000783 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000785 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
786 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 }
788
789 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
790 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
791 return Result;
792}
793
Dan Gohman36d40922009-04-16 19:25:55 +0000794SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
795 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000796 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000797 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000798 assert(isSCEVable(Ty) &&
799 "This is not a conversion to a SCEVable type!");
800 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000801
Dan Gohmanc76b5452009-05-04 22:02:23 +0000802 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000803 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000804 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
805 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
806 return getUnknown(C);
807 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808
Dan Gohman1a5c4992009-04-22 16:20:48 +0000809 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000810 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000811 return getZeroExtendExpr(SZ->getOperand(), Ty);
812
Dan Gohmana9dba962009-04-27 20:16:15 +0000813 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000815 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000817 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000818 if (AR->isAffine()) {
819 // Check whether the backedge-taken count is SCEVCouldNotCompute.
820 // Note that this serves two purposes: It filters out loops that are
821 // simply not analyzable, and it covers the case where this code is
822 // being called from within backedge-taken count analysis, such that
823 // attempting to ask for the backedge-taken count would likely result
824 // in infinite recursion. In the later case, the analysis code will
825 // cope with a conservative value, and it will take care to purge
826 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000827 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
828 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000829 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000830 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000831 SCEVHandle Start = AR->getStart();
832 SCEVHandle Step = AR->getStepRecurrence(*this);
833
834 // Check whether the backedge-taken count can be losslessly casted to
835 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000836 SCEVHandle CastedMaxBECount =
837 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000838 SCEVHandle RecastedMaxBECount =
839 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
840 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000841 const Type *WideTy =
842 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000843 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000844 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000845 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000846 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000847 SCEVHandle Add = getAddExpr(Start, ZMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000848 SCEVHandle OperandExtendedAdd =
849 getAddExpr(getZeroExtendExpr(Start, WideTy),
850 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
851 getZeroExtendExpr(Step, WideTy)));
852 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000853 // Return the expression with the addrec on the outside.
854 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
855 getZeroExtendExpr(Step, Ty),
856 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000857
858 // Similar to above, only this time treat the step value as signed.
859 // This covers loops that count down.
860 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000861 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000862 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000863 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000864 OperandExtendedAdd =
865 getAddExpr(getZeroExtendExpr(Start, WideTy),
866 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
867 getSignExtendExpr(Step, WideTy)));
868 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000869 // Return the expression with the addrec on the outside.
870 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
871 getSignExtendExpr(Step, Ty),
872 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000873 }
874 }
875 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876
877 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
878 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
879 return Result;
880}
881
Dan Gohmana9dba962009-04-27 20:16:15 +0000882SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
883 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000884 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000885 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000886 assert(isSCEVable(Ty) &&
887 "This is not a conversion to a SCEVable type!");
888 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000889
Dan Gohmanc76b5452009-05-04 22:02:23 +0000890 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000891 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000892 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
893 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
894 return getUnknown(C);
895 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896
Dan Gohman1a5c4992009-04-22 16:20:48 +0000897 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000898 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000899 return getSignExtendExpr(SS->getOperand(), Ty);
900
Dan Gohmana9dba962009-04-27 20:16:15 +0000901 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000903 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000905 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000906 if (AR->isAffine()) {
907 // Check whether the backedge-taken count is SCEVCouldNotCompute.
908 // Note that this serves two purposes: It filters out loops that are
909 // simply not analyzable, and it covers the case where this code is
910 // being called from within backedge-taken count analysis, such that
911 // attempting to ask for the backedge-taken count would likely result
912 // in infinite recursion. In the later case, the analysis code will
913 // cope with a conservative value, and it will take care to purge
914 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000915 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
916 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000917 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000918 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000919 SCEVHandle Start = AR->getStart();
920 SCEVHandle Step = AR->getStepRecurrence(*this);
921
922 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000923 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000924 SCEVHandle CastedMaxBECount =
925 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000926 SCEVHandle RecastedMaxBECount =
927 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
928 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000929 const Type *WideTy =
930 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000931 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000932 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000933 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000934 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000935 SCEVHandle Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000936 SCEVHandle OperandExtendedAdd =
937 getAddExpr(getSignExtendExpr(Start, WideTy),
938 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
939 getSignExtendExpr(Step, WideTy)));
940 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000941 // Return the expression with the addrec on the outside.
942 return getAddRecExpr(getSignExtendExpr(Start, Ty),
943 getSignExtendExpr(Step, Ty),
944 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000945 }
946 }
947 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948
949 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
950 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
951 return Result;
952}
953
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000954/// getAnyExtendExpr - Return a SCEV for the given operand extended with
955/// unspecified bits out to the given type.
956///
957SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
958 const Type *Ty) {
959 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
960 "This is not an extending conversion!");
961 assert(isSCEVable(Ty) &&
962 "This is not a conversion to a SCEVable type!");
963 Ty = getEffectiveSCEVType(Ty);
964
965 // Sign-extend negative constants.
966 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
967 if (SC->getValue()->getValue().isNegative())
968 return getSignExtendExpr(Op, Ty);
969
970 // Peel off a truncate cast.
971 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
972 SCEVHandle NewOp = T->getOperand();
973 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
974 return getAnyExtendExpr(NewOp, Ty);
975 return getTruncateOrNoop(NewOp, Ty);
976 }
977
978 // Next try a zext cast. If the cast is folded, use it.
979 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
980 if (!isa<SCEVZeroExtendExpr>(ZExt))
981 return ZExt;
982
983 // Next try a sext cast. If the cast is folded, use it.
984 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
985 if (!isa<SCEVSignExtendExpr>(SExt))
986 return SExt;
987
988 // If the expression is obviously signed, use the sext cast value.
989 if (isa<SCEVSMaxExpr>(Op))
990 return SExt;
991
992 // Absent any other information, use the zext cast value.
993 return ZExt;
994}
995
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000996/// CollectAddOperandsWithScales - Process the given Ops list, which is
997/// a list of operands to be added under the given scale, update the given
998/// map. This is a helper function for getAddRecExpr. As an example of
999/// what it does, given a sequence of operands that would form an add
1000/// expression like this:
1001///
1002/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1003///
1004/// where A and B are constants, update the map with these values:
1005///
1006/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1007///
1008/// and add 13 + A*B*29 to AccumulatedConstant.
1009/// This will allow getAddRecExpr to produce this:
1010///
1011/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1012///
1013/// This form often exposes folding opportunities that are hidden in
1014/// the original operand list.
1015///
1016/// Return true iff it appears that any interesting folding opportunities
1017/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1018/// the common case where no interesting opportunities are present, and
1019/// is also used as a check to avoid infinite recursion.
1020///
1021static bool
1022CollectAddOperandsWithScales(DenseMap<SCEVHandle, APInt> &M,
1023 SmallVector<SCEVHandle, 8> &NewOps,
1024 APInt &AccumulatedConstant,
1025 const SmallVectorImpl<SCEVHandle> &Ops,
1026 const APInt &Scale,
1027 ScalarEvolution &SE) {
1028 bool Interesting = false;
1029
1030 // Iterate over the add operands.
1031 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1032 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1033 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1034 APInt NewScale =
1035 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1036 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1037 // A multiplication of a constant with another add; recurse.
1038 Interesting |=
1039 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1040 cast<SCEVAddExpr>(Mul->getOperand(1))
1041 ->getOperands(),
1042 NewScale, SE);
1043 } else {
1044 // A multiplication of a constant with some other value. Update
1045 // the map.
1046 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1047 SCEVHandle Key = SE.getMulExpr(MulOps);
1048 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1049 M.insert(std::make_pair(Key, APInt()));
1050 if (Pair.second) {
1051 Pair.first->second = NewScale;
1052 NewOps.push_back(Pair.first->first);
1053 } else {
1054 Pair.first->second += NewScale;
1055 // The map already had an entry for this value, which may indicate
1056 // a folding opportunity.
1057 Interesting = true;
1058 }
1059 }
1060 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1061 // Pull a buried constant out to the outside.
1062 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1063 Interesting = true;
1064 AccumulatedConstant += Scale * C->getValue()->getValue();
1065 } else {
1066 // An ordinary operand. Update the map.
1067 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1068 M.insert(std::make_pair(Ops[i], APInt()));
1069 if (Pair.second) {
1070 Pair.first->second = Scale;
1071 NewOps.push_back(Pair.first->first);
1072 } else {
1073 Pair.first->second += Scale;
1074 // The map already had an entry for this value, which may indicate
1075 // a folding opportunity.
1076 Interesting = true;
1077 }
1078 }
1079 }
1080
1081 return Interesting;
1082}
1083
1084namespace {
1085 struct APIntCompare {
1086 bool operator()(const APInt &LHS, const APInt &RHS) const {
1087 return LHS.ult(RHS);
1088 }
1089 };
1090}
1091
Dan Gohmanc8a29272009-05-24 23:45:28 +00001092/// getAddExpr - Get a canonical add expression, or something simpler if
1093/// possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001094SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 assert(!Ops.empty() && "Cannot get empty add!");
1096 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001097#ifndef NDEBUG
1098 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1099 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1100 getEffectiveSCEVType(Ops[0]->getType()) &&
1101 "SCEVAddExpr operand types don't match!");
1102#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103
1104 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001105 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106
1107 // If there are any constants, fold them together.
1108 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001109 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110 ++Idx;
1111 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001112 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001114 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1115 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001116 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001117 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001118 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 }
1120
1121 // If we are left with a constant zero being added, strip it off.
1122 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1123 Ops.erase(Ops.begin());
1124 --Idx;
1125 }
1126 }
1127
1128 if (Ops.size() == 1) return Ops[0];
1129
1130 // Okay, check to see if the same value occurs in the operand list twice. If
1131 // so, merge them together into an multiply expression. Since we sorted the
1132 // list, these values are required to be adjacent.
1133 const Type *Ty = Ops[0]->getType();
1134 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1135 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1136 // Found a match, merge the two values into a multiply, and add any
1137 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +00001138 SCEVHandle Two = getIntegerSCEV(2, Ty);
1139 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 if (Ops.size() == 2)
1141 return Mul;
1142 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1143 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001144 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145 }
1146
Dan Gohman45b3b542009-05-08 21:03:19 +00001147 // Check for truncates. If all the operands are truncated from the same
1148 // type, see if factoring out the truncate would permit the result to be
1149 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1150 // if the contents of the resulting outer trunc fold to something simple.
1151 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1152 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1153 const Type *DstType = Trunc->getType();
1154 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman02ff9392009-06-14 22:47:23 +00001155 SmallVector<SCEVHandle, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001156 bool Ok = true;
1157 // Check all the operands to see if they can be represented in the
1158 // source type of the truncate.
1159 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1160 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1161 if (T->getOperand()->getType() != SrcType) {
1162 Ok = false;
1163 break;
1164 }
1165 LargeOps.push_back(T->getOperand());
1166 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1167 // This could be either sign or zero extension, but sign extension
1168 // is much more likely to be foldable here.
1169 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1170 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001171 SmallVector<SCEVHandle, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001172 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1173 if (const SCEVTruncateExpr *T =
1174 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1175 if (T->getOperand()->getType() != SrcType) {
1176 Ok = false;
1177 break;
1178 }
1179 LargeMulOps.push_back(T->getOperand());
1180 } else if (const SCEVConstant *C =
1181 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1182 // This could be either sign or zero extension, but sign extension
1183 // is much more likely to be foldable here.
1184 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1185 } else {
1186 Ok = false;
1187 break;
1188 }
1189 }
1190 if (Ok)
1191 LargeOps.push_back(getMulExpr(LargeMulOps));
1192 } else {
1193 Ok = false;
1194 break;
1195 }
1196 }
1197 if (Ok) {
1198 // Evaluate the expression in the larger type.
1199 SCEVHandle Fold = getAddExpr(LargeOps);
1200 // If it folds to something simple, use it. Otherwise, don't.
1201 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1202 return getTruncateExpr(Fold, DstType);
1203 }
1204 }
1205
1206 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1208 ++Idx;
1209
1210 // If there are add operands they would be next.
1211 if (Idx < Ops.size()) {
1212 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001213 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 // If we have an add, expand the add operands onto the end of the operands
1215 // list.
1216 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1217 Ops.erase(Ops.begin()+Idx);
1218 DeletedAdd = true;
1219 }
1220
1221 // If we deleted at least one add, we added operands to the end of the list,
1222 // and they are not necessarily sorted. Recurse to resort and resimplify
1223 // any operands we just aquired.
1224 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001225 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 }
1227
1228 // Skip over the add expression until we get to a multiply.
1229 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1230 ++Idx;
1231
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001232 // Check to see if there are any folding opportunities present with
1233 // operands multiplied by constant values.
1234 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1235 uint64_t BitWidth = getTypeSizeInBits(Ty);
1236 DenseMap<SCEVHandle, APInt> M;
1237 SmallVector<SCEVHandle, 8> NewOps;
1238 APInt AccumulatedConstant(BitWidth, 0);
1239 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1240 Ops, APInt(BitWidth, 1), *this)) {
1241 // Some interesting folding opportunity is present, so its worthwhile to
1242 // re-generate the operands list. Group the operands by constant scale,
1243 // to avoid multiplying by the same constant scale multiple times.
1244 std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare> MulOpLists;
1245 for (SmallVector<SCEVHandle, 8>::iterator I = NewOps.begin(),
1246 E = NewOps.end(); I != E; ++I)
1247 MulOpLists[M.find(*I)->second].push_back(*I);
1248 // Re-generate the operands list.
1249 Ops.clear();
1250 if (AccumulatedConstant != 0)
1251 Ops.push_back(getConstant(AccumulatedConstant));
1252 for (std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare>::iterator I =
1253 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1254 if (I->first != 0)
1255 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1256 if (Ops.empty())
1257 return getIntegerSCEV(0, Ty);
1258 if (Ops.size() == 1)
1259 return Ops[0];
1260 return getAddExpr(Ops);
1261 }
1262 }
1263
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 // If we are adding something to a multiply expression, make sure the
1265 // something is not already an operand of the multiply. If so, merge it into
1266 // the multiply.
1267 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001268 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001270 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001272 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1274 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1275 if (Mul->getNumOperands() != 2) {
1276 // If the multiply has more than two operands, we must get the
1277 // Y*Z term.
Dan Gohman02ff9392009-06-14 22:47:23 +00001278 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001280 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 }
Dan Gohman89f85052007-10-22 18:31:58 +00001282 SCEVHandle One = getIntegerSCEV(1, Ty);
1283 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1284 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 if (Ops.size() == 2) return OuterMul;
1286 if (AddOp < Idx) {
1287 Ops.erase(Ops.begin()+AddOp);
1288 Ops.erase(Ops.begin()+Idx-1);
1289 } else {
1290 Ops.erase(Ops.begin()+Idx);
1291 Ops.erase(Ops.begin()+AddOp-1);
1292 }
1293 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001294 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 }
1296
1297 // Check this multiply against other multiplies being added together.
1298 for (unsigned OtherMulIdx = Idx+1;
1299 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1300 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001301 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 // If MulOp occurs in OtherMul, we can fold the two multiplies
1303 // together.
1304 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1305 OMulOp != e; ++OMulOp)
1306 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1307 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1308 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1309 if (Mul->getNumOperands() != 2) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001310 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001312 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 }
1314 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1315 if (OtherMul->getNumOperands() != 2) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001316 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 OtherMul->op_end());
1318 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001319 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 }
Dan Gohman89f85052007-10-22 18:31:58 +00001321 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1322 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 if (Ops.size() == 2) return OuterMul;
1324 Ops.erase(Ops.begin()+Idx);
1325 Ops.erase(Ops.begin()+OtherMulIdx-1);
1326 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001327 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 }
1329 }
1330 }
1331 }
1332
1333 // If there are any add recurrences in the operands list, see if any other
1334 // added values are loop invariant. If so, we can fold them into the
1335 // recurrence.
1336 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1337 ++Idx;
1338
1339 // Scan over all recurrences, trying to fold loop invariants into them.
1340 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1341 // Scan all of the other operands to this add and add them to the vector if
1342 // they are loop invariant w.r.t. the recurrence.
Dan Gohman02ff9392009-06-14 22:47:23 +00001343 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001344 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1346 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1347 LIOps.push_back(Ops[i]);
1348 Ops.erase(Ops.begin()+i);
1349 --i; --e;
1350 }
1351
1352 // If we found some loop invariants, fold them into the recurrence.
1353 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001354 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 LIOps.push_back(AddRec->getStart());
1356
Dan Gohman02ff9392009-06-14 22:47:23 +00001357 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1358 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001359 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360
Dan Gohman89f85052007-10-22 18:31:58 +00001361 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362 // If all of the other operands were loop invariant, we are done.
1363 if (Ops.size() == 1) return NewRec;
1364
1365 // Otherwise, add the folded AddRec by the non-liv parts.
1366 for (unsigned i = 0;; ++i)
1367 if (Ops[i] == AddRec) {
1368 Ops[i] = NewRec;
1369 break;
1370 }
Dan Gohman89f85052007-10-22 18:31:58 +00001371 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001372 }
1373
1374 // Okay, if there weren't any loop invariants to be folded, check to see if
1375 // there are multiple AddRec's with the same loop induction variable being
1376 // added together. If so, we can fold them.
1377 for (unsigned OtherIdx = Idx+1;
1378 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1379 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001380 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1382 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman02ff9392009-06-14 22:47:23 +00001383 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001384 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1385 if (i >= NewOps.size()) {
1386 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1387 OtherAddRec->op_end());
1388 break;
1389 }
Dan Gohman89f85052007-10-22 18:31:58 +00001390 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 }
Dan Gohman89f85052007-10-22 18:31:58 +00001392 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393
1394 if (Ops.size() == 2) return NewAddRec;
1395
1396 Ops.erase(Ops.begin()+Idx);
1397 Ops.erase(Ops.begin()+OtherIdx-1);
1398 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001399 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001400 }
1401 }
1402
1403 // Otherwise couldn't fold anything into this recurrence. Move onto the
1404 // next one.
1405 }
1406
1407 // Okay, it looks like we really DO need an add expr. Check to see if we
1408 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001409 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1411 SCEVOps)];
1412 if (Result == 0) Result = new SCEVAddExpr(Ops);
1413 return Result;
1414}
1415
1416
Dan Gohmanc8a29272009-05-24 23:45:28 +00001417/// getMulExpr - Get a canonical multiply expression, or something simpler if
1418/// possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001419SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001421#ifndef NDEBUG
1422 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1423 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1424 getEffectiveSCEVType(Ops[0]->getType()) &&
1425 "SCEVMulExpr operand types don't match!");
1426#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427
1428 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001429 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430
1431 // If there are any constants, fold them together.
1432 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001433 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434
1435 // C1*(C2+V) -> C1*C2 + C1*V
1436 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001437 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 if (Add->getNumOperands() == 2 &&
1439 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001440 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1441 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442
1443
1444 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001445 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001447 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1448 RHSC->getValue()->getValue());
1449 Ops[0] = getConstant(Fold);
1450 Ops.erase(Ops.begin()+1); // Erase the folded element
1451 if (Ops.size() == 1) return Ops[0];
1452 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 }
1454
1455 // If we are left with a constant one being multiplied, strip it off.
1456 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1457 Ops.erase(Ops.begin());
1458 --Idx;
1459 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1460 // If we have a multiply of zero, it will always be zero.
1461 return Ops[0];
1462 }
1463 }
1464
1465 // Skip over the add expression until we get to a multiply.
1466 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1467 ++Idx;
1468
1469 if (Ops.size() == 1)
1470 return Ops[0];
1471
1472 // If there are mul operands inline them all into this expression.
1473 if (Idx < Ops.size()) {
1474 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001475 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001476 // If we have an mul, expand the mul operands onto the end of the operands
1477 // list.
1478 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1479 Ops.erase(Ops.begin()+Idx);
1480 DeletedMul = true;
1481 }
1482
1483 // If we deleted at least one mul, we added operands to the end of the list,
1484 // and they are not necessarily sorted. Recurse to resort and resimplify
1485 // any operands we just aquired.
1486 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001487 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488 }
1489
1490 // If there are any add recurrences in the operands list, see if any other
1491 // added values are loop invariant. If so, we can fold them into the
1492 // recurrence.
1493 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1494 ++Idx;
1495
1496 // Scan over all recurrences, trying to fold loop invariants into them.
1497 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1498 // Scan all of the other operands to this mul and add them to the vector if
1499 // they are loop invariant w.r.t. the recurrence.
Dan Gohman02ff9392009-06-14 22:47:23 +00001500 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001501 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001502 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1503 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1504 LIOps.push_back(Ops[i]);
1505 Ops.erase(Ops.begin()+i);
1506 --i; --e;
1507 }
1508
1509 // If we found some loop invariants, fold them into the recurrence.
1510 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001511 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman02ff9392009-06-14 22:47:23 +00001512 SmallVector<SCEVHandle, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 NewOps.reserve(AddRec->getNumOperands());
1514 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001515 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001517 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518 } else {
1519 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001520 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001522 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523 }
1524 }
1525
Dan Gohman89f85052007-10-22 18:31:58 +00001526 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001527
1528 // If all of the other operands were loop invariant, we are done.
1529 if (Ops.size() == 1) return NewRec;
1530
1531 // Otherwise, multiply the folded AddRec by the non-liv parts.
1532 for (unsigned i = 0;; ++i)
1533 if (Ops[i] == AddRec) {
1534 Ops[i] = NewRec;
1535 break;
1536 }
Dan Gohman89f85052007-10-22 18:31:58 +00001537 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538 }
1539
1540 // Okay, if there weren't any loop invariants to be folded, check to see if
1541 // there are multiple AddRec's with the same loop induction variable being
1542 // multiplied together. If so, we can fold them.
1543 for (unsigned OtherIdx = Idx+1;
1544 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1545 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001546 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1548 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001549 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001550 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001552 SCEVHandle B = F->getStepRecurrence(*this);
1553 SCEVHandle D = G->getStepRecurrence(*this);
1554 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1555 getMulExpr(G, B),
1556 getMulExpr(B, D));
1557 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1558 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001559 if (Ops.size() == 2) return NewAddRec;
1560
1561 Ops.erase(Ops.begin()+Idx);
1562 Ops.erase(Ops.begin()+OtherIdx-1);
1563 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001564 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001565 }
1566 }
1567
1568 // Otherwise couldn't fold anything into this recurrence. Move onto the
1569 // next one.
1570 }
1571
1572 // Okay, it looks like we really DO need an mul expr. Check to see if we
1573 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001574 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001575 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1576 SCEVOps)];
1577 if (Result == 0)
1578 Result = new SCEVMulExpr(Ops);
1579 return Result;
1580}
1581
Dan Gohmanc8a29272009-05-24 23:45:28 +00001582/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1583/// possible.
Dan Gohman77841cd2009-05-04 22:23:18 +00001584SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1585 const SCEVHandle &RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001586 assert(getEffectiveSCEVType(LHS->getType()) ==
1587 getEffectiveSCEVType(RHS->getType()) &&
1588 "SCEVUDivExpr operand types don't match!");
1589
Dan Gohmanc76b5452009-05-04 22:02:23 +00001590 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001592 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001593 if (RHSC->isZero())
1594 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001595
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001596 // Determine if the division can be folded into the operands of
1597 // its operands.
1598 // TODO: Generalize this to non-constants by using known-bits information.
1599 const Type *Ty = LHS->getType();
1600 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1601 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1602 // For non-power-of-two values, effectively round the value up to the
1603 // nearest power of two.
1604 if (!RHSC->getValue()->getValue().isPowerOf2())
1605 ++MaxShiftAmt;
1606 const IntegerType *ExtTy =
1607 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1608 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1609 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1610 if (const SCEVConstant *Step =
1611 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1612 if (!Step->getValue()->getValue()
1613 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001614 getZeroExtendExpr(AR, ExtTy) ==
1615 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1616 getZeroExtendExpr(Step, ExtTy),
1617 AR->getLoop())) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001618 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001619 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1620 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1621 return getAddRecExpr(Operands, AR->getLoop());
1622 }
1623 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001624 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001625 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001626 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1627 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1628 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001629 // Find an operand that's safely divisible.
1630 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1631 SCEVHandle Op = M->getOperand(i);
1632 SCEVHandle Div = getUDivExpr(Op, RHSC);
1633 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001634 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1635 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1636 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001637 Operands[i] = Div;
1638 return getMulExpr(Operands);
1639 }
1640 }
Dan Gohman14374d32009-05-08 23:11:16 +00001641 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001642 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001643 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001644 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001645 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1646 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1647 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1648 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001649 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1650 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1651 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1652 break;
1653 Operands.push_back(Op);
1654 }
1655 if (Operands.size() == A->getNumOperands())
1656 return getAddExpr(Operands);
1657 }
Dan Gohman14374d32009-05-08 23:11:16 +00001658 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001659
1660 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001661 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001662 Constant *LHSCV = LHSC->getValue();
1663 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001664 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001665 }
1666 }
1667
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001668 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1669 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670 return Result;
1671}
1672
1673
Dan Gohmanc8a29272009-05-24 23:45:28 +00001674/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1675/// Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001676SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001677 const SCEVHandle &Step, const Loop *L) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001678 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001680 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681 if (StepChrec->getLoop() == L) {
1682 Operands.insert(Operands.end(), StepChrec->op_begin(),
1683 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001684 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001685 }
1686
1687 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001688 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689}
1690
Dan Gohmanc8a29272009-05-24 23:45:28 +00001691/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1692/// Simplify the expression as much as possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001693SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001694 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001695 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001696#ifndef NDEBUG
1697 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1698 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1699 getEffectiveSCEVType(Operands[0]->getType()) &&
1700 "SCEVAddRecExpr operand types don't match!");
1701#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702
Dan Gohman7b560c42008-06-18 16:23:07 +00001703 if (Operands.back()->isZero()) {
1704 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001705 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001706 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001707
Dan Gohman42936882008-08-08 18:33:12 +00001708 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001709 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001710 const Loop* NestedLoop = NestedAR->getLoop();
1711 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001712 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1713 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001714 SCEVHandle NestedARHandle(NestedAR);
1715 Operands[0] = NestedAR->getStart();
1716 NestedOperands[0] = getAddRecExpr(Operands, L);
1717 return getAddRecExpr(NestedOperands, NestedLoop);
1718 }
1719 }
1720
Dan Gohmanbff6b582009-05-04 22:30:44 +00001721 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1722 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1724 return Result;
1725}
1726
Nick Lewycky711640a2007-11-25 22:41:31 +00001727SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1728 const SCEVHandle &RHS) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001729 SmallVector<SCEVHandle, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001730 Ops.push_back(LHS);
1731 Ops.push_back(RHS);
1732 return getSMaxExpr(Ops);
1733}
1734
Dan Gohman02ff9392009-06-14 22:47:23 +00001735SCEVHandle
1736ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001737 assert(!Ops.empty() && "Cannot get empty smax!");
1738 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001739#ifndef NDEBUG
1740 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1741 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1742 getEffectiveSCEVType(Ops[0]->getType()) &&
1743 "SCEVSMaxExpr operand types don't match!");
1744#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001745
1746 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001747 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001748
1749 // If there are any constants, fold them together.
1750 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001751 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001752 ++Idx;
1753 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001754 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001755 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001756 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001757 APIntOps::smax(LHSC->getValue()->getValue(),
1758 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001759 Ops[0] = getConstant(Fold);
1760 Ops.erase(Ops.begin()+1); // Erase the folded element
1761 if (Ops.size() == 1) return Ops[0];
1762 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001763 }
1764
1765 // If we are left with a constant -inf, strip it off.
1766 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1767 Ops.erase(Ops.begin());
1768 --Idx;
1769 }
1770 }
1771
1772 if (Ops.size() == 1) return Ops[0];
1773
1774 // Find the first SMax
1775 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1776 ++Idx;
1777
1778 // Check to see if one of the operands is an SMax. If so, expand its operands
1779 // onto our operand list, and recurse to simplify.
1780 if (Idx < Ops.size()) {
1781 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001782 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001783 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1784 Ops.erase(Ops.begin()+Idx);
1785 DeletedSMax = true;
1786 }
1787
1788 if (DeletedSMax)
1789 return getSMaxExpr(Ops);
1790 }
1791
1792 // Okay, check to see if the same value occurs in the operand list twice. If
1793 // so, delete one. Since we sorted the list, these values are required to
1794 // be adjacent.
1795 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1796 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1797 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1798 --i; --e;
1799 }
1800
1801 if (Ops.size() == 1) return Ops[0];
1802
1803 assert(!Ops.empty() && "Reduced smax down to nothing!");
1804
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001805 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001806 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001807 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001808 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1809 SCEVOps)];
1810 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1811 return Result;
1812}
1813
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001814SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1815 const SCEVHandle &RHS) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001816 SmallVector<SCEVHandle, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001817 Ops.push_back(LHS);
1818 Ops.push_back(RHS);
1819 return getUMaxExpr(Ops);
1820}
1821
Dan Gohman02ff9392009-06-14 22:47:23 +00001822SCEVHandle
1823ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001824 assert(!Ops.empty() && "Cannot get empty umax!");
1825 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001826#ifndef NDEBUG
1827 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1828 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1829 getEffectiveSCEVType(Ops[0]->getType()) &&
1830 "SCEVUMaxExpr operand types don't match!");
1831#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001832
1833 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001834 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001835
1836 // If there are any constants, fold them together.
1837 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001838 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001839 ++Idx;
1840 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001841 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001842 // We found two constants, fold them together!
1843 ConstantInt *Fold = ConstantInt::get(
1844 APIntOps::umax(LHSC->getValue()->getValue(),
1845 RHSC->getValue()->getValue()));
1846 Ops[0] = getConstant(Fold);
1847 Ops.erase(Ops.begin()+1); // Erase the folded element
1848 if (Ops.size() == 1) return Ops[0];
1849 LHSC = cast<SCEVConstant>(Ops[0]);
1850 }
1851
1852 // If we are left with a constant zero, strip it off.
1853 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1854 Ops.erase(Ops.begin());
1855 --Idx;
1856 }
1857 }
1858
1859 if (Ops.size() == 1) return Ops[0];
1860
1861 // Find the first UMax
1862 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1863 ++Idx;
1864
1865 // Check to see if one of the operands is a UMax. If so, expand its operands
1866 // onto our operand list, and recurse to simplify.
1867 if (Idx < Ops.size()) {
1868 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001869 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001870 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1871 Ops.erase(Ops.begin()+Idx);
1872 DeletedUMax = true;
1873 }
1874
1875 if (DeletedUMax)
1876 return getUMaxExpr(Ops);
1877 }
1878
1879 // Okay, check to see if the same value occurs in the operand list twice. If
1880 // so, delete one. Since we sorted the list, these values are required to
1881 // be adjacent.
1882 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1883 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1884 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1885 --i; --e;
1886 }
1887
1888 if (Ops.size() == 1) return Ops[0];
1889
1890 assert(!Ops.empty() && "Reduced umax down to nothing!");
1891
1892 // Okay, it looks like we really DO need a umax expr. Check to see if we
1893 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001894 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001895 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1896 SCEVOps)];
1897 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1898 return Result;
1899}
1900
Dan Gohman89f85052007-10-22 18:31:58 +00001901SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001903 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001904 if (isa<ConstantPointerNull>(V))
1905 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1907 if (Result == 0) Result = new SCEVUnknown(V);
1908 return Result;
1909}
1910
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001911//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001912// Basic SCEV Analysis and PHI Idiom Recognition Code
1913//
1914
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001915/// isSCEVable - Test if values of the given type are analyzable within
1916/// the SCEV framework. This primarily includes integer types, and it
1917/// can optionally include pointer types if the ScalarEvolution class
1918/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001919bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001920 // Integers are always SCEVable.
1921 if (Ty->isInteger())
1922 return true;
1923
1924 // Pointers are SCEVable if TargetData information is available
1925 // to provide pointer size information.
1926 if (isa<PointerType>(Ty))
1927 return TD != NULL;
1928
1929 // Otherwise it's not SCEVable.
1930 return false;
1931}
1932
1933/// getTypeSizeInBits - Return the size in bits of the specified type,
1934/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001935uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001936 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1937
1938 // If we have a TargetData, use it!
1939 if (TD)
1940 return TD->getTypeSizeInBits(Ty);
1941
1942 // Otherwise, we support only integer types.
1943 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1944 return Ty->getPrimitiveSizeInBits();
1945}
1946
1947/// getEffectiveSCEVType - Return a type with the same bitwidth as
1948/// the given type and which represents how SCEV will treat the given
1949/// type, for which isSCEVable must return true. For pointer types,
1950/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001951const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001952 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1953
1954 if (Ty->isInteger())
1955 return Ty;
1956
1957 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1958 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001959}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001960
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001961SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001962 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001963}
1964
Dan Gohmand83d4af2009-05-04 22:20:30 +00001965/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001966/// computed.
1967bool ScalarEvolution::hasSCEV(Value *V) const {
1968 return Scalars.count(V);
1969}
1970
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001971/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1972/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001973SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001974 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001975
Dan Gohmanbff6b582009-05-04 22:30:44 +00001976 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977 if (I != Scalars.end()) return I->second;
1978 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001979 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001980 return S;
1981}
1982
Dan Gohman01c2ee72009-04-16 03:18:22 +00001983/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1984/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001985SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1986 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001987 Constant *C;
1988 if (Val == 0)
1989 C = Constant::getNullValue(Ty);
1990 else if (Ty->isFloatingPoint())
1991 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1992 APFloat::IEEEdouble, Val));
1993 else
1994 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001995 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001996}
1997
1998/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1999///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002000SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002001 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002002 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002003
2004 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002005 Ty = getEffectiveSCEVType(Ty);
2006 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002007}
2008
2009/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002010SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002011 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002012 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002013
2014 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002015 Ty = getEffectiveSCEVType(Ty);
2016 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002017 return getMinusSCEV(AllOnes, V);
2018}
2019
2020/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2021///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002022SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00002023 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002024 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002025 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002026}
2027
2028/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2029/// input value to the specified type. If the type must be extended, it is zero
2030/// extended.
2031SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002032ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002033 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002034 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002035 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2036 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002037 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002038 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002039 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002040 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002041 return getTruncateExpr(V, Ty);
2042 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002043}
2044
2045/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2046/// input value to the specified type. If the type must be extended, it is sign
2047/// extended.
2048SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002049ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002050 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002051 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002052 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2053 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002054 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002055 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002056 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002057 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002058 return getTruncateExpr(V, Ty);
2059 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002060}
2061
Dan Gohmanac959332009-05-13 03:46:30 +00002062/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2063/// input value to the specified type. If the type must be extended, it is zero
2064/// extended. The conversion must not be narrowing.
2065SCEVHandle
2066ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
2067 const Type *SrcTy = V->getType();
2068 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2069 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2070 "Cannot noop or zero extend with non-integer arguments!");
2071 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2072 "getNoopOrZeroExtend cannot truncate!");
2073 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2074 return V; // No conversion
2075 return getZeroExtendExpr(V, Ty);
2076}
2077
2078/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2079/// input value to the specified type. If the type must be extended, it is sign
2080/// extended. The conversion must not be narrowing.
2081SCEVHandle
2082ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
2083 const Type *SrcTy = V->getType();
2084 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2085 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2086 "Cannot noop or sign extend with non-integer arguments!");
2087 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2088 "getNoopOrSignExtend cannot truncate!");
2089 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2090 return V; // No conversion
2091 return getSignExtendExpr(V, Ty);
2092}
2093
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002094/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2095/// the input value to the specified type. If the type must be extended,
2096/// it is extended with unspecified bits. The conversion must not be
2097/// narrowing.
2098SCEVHandle
2099ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
2100 const Type *SrcTy = V->getType();
2101 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2102 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2103 "Cannot noop or any extend with non-integer arguments!");
2104 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2105 "getNoopOrAnyExtend cannot truncate!");
2106 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2107 return V; // No conversion
2108 return getAnyExtendExpr(V, Ty);
2109}
2110
Dan Gohmanac959332009-05-13 03:46:30 +00002111/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2112/// input value to the specified type. The conversion must not be widening.
2113SCEVHandle
2114ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
2115 const Type *SrcTy = V->getType();
2116 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2117 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2118 "Cannot truncate or noop with non-integer arguments!");
2119 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2120 "getTruncateOrNoop cannot extend!");
2121 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2122 return V; // No conversion
2123 return getTruncateExpr(V, Ty);
2124}
2125
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002126/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2127/// the specified instruction and replaces any references to the symbolic value
2128/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002129void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
2131 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002132 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2133 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002134 if (SI == Scalars.end()) return;
2135
2136 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002137 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002138 if (NV == SI->second) return; // No change.
2139
2140 SI->second = NV; // Update the scalars map!
2141
2142 // Any instruction values that use this instruction might also need to be
2143 // updated!
2144 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2145 UI != E; ++UI)
2146 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2147}
2148
2149/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2150/// a loop header, making it a potential recurrence, or it doesn't.
2151///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002152SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002153 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002154 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 if (L->getHeader() == PN->getParent()) {
2156 // If it lives in the loop header, it has two incoming values, one
2157 // from outside the loop, and one from inside.
2158 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2159 unsigned BackEdge = IncomingEdge^1;
2160
2161 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002162 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002163 assert(Scalars.find(PN) == Scalars.end() &&
2164 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002165 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166
2167 // Using this symbolic name for the PHI, analyze the value coming around
2168 // the back-edge.
2169 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2170
2171 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2172 // has a special value for the first iteration of the loop.
2173
2174 // If the value coming around the backedge is an add with the symbolic
2175 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002176 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 // If there is a single occurrence of the symbolic value, replace it
2178 // with a recurrence.
2179 unsigned FoundIndex = Add->getNumOperands();
2180 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2181 if (Add->getOperand(i) == SymbolicName)
2182 if (FoundIndex == e) {
2183 FoundIndex = i;
2184 break;
2185 }
2186
2187 if (FoundIndex != Add->getNumOperands()) {
2188 // Create an add with everything but the specified operand.
Dan Gohman02ff9392009-06-14 22:47:23 +00002189 SmallVector<SCEVHandle, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002190 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2191 if (i != FoundIndex)
2192 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002193 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002194
2195 // This is not a valid addrec if the step amount is varying each
2196 // loop iteration, but is not itself an addrec in this loop.
2197 if (Accum->isLoopInvariant(L) ||
2198 (isa<SCEVAddRecExpr>(Accum) &&
2199 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2200 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002201 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002202
2203 // Okay, for the entire analysis of this edge we assumed the PHI
2204 // to be symbolic. We now need to go back and update all of the
2205 // entries for the scalars that use the PHI (except for the PHI
2206 // itself) to use the new analyzed value instead of the "symbolic"
2207 // value.
2208 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2209 return PHISCEV;
2210 }
2211 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002212 } else if (const SCEVAddRecExpr *AddRec =
2213 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002214 // Otherwise, this could be a loop like this:
2215 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2216 // In this case, j = {1,+,1} and BEValue is j.
2217 // Because the other in-value of i (0) fits the evolution of BEValue
2218 // i really is an addrec evolution.
2219 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2220 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2221
2222 // If StartVal = j.start - j.stride, we can use StartVal as the
2223 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002224 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002225 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002226 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002227 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002228
2229 // Okay, for the entire analysis of this edge we assumed the PHI
2230 // to be symbolic. We now need to go back and update all of the
2231 // entries for the scalars that use the PHI (except for the PHI
2232 // itself) to use the new analyzed value instead of the "symbolic"
2233 // value.
2234 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2235 return PHISCEV;
2236 }
2237 }
2238 }
2239
2240 return SymbolicName;
2241 }
2242
2243 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002244 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002245}
2246
Dan Gohman509cf4d2009-05-08 20:26:55 +00002247/// createNodeForGEP - Expand GEP instructions into add and multiply
2248/// operations. This allows them to be analyzed by regular SCEV code.
2249///
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002250SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002251
2252 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002253 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002254 // Don't attempt to analyze GEPs over unsized objects.
2255 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2256 return getUnknown(GEP);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002257 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002258 gep_type_iterator GTI = gep_type_begin(GEP);
2259 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2260 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002261 I != E; ++I) {
2262 Value *Index = *I;
2263 // Compute the (potentially symbolic) offset in bytes for this index.
2264 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2265 // For a struct, add the member offset.
2266 const StructLayout &SL = *TD->getStructLayout(STy);
2267 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2268 uint64_t Offset = SL.getElementOffset(FieldNo);
2269 TotalOffset = getAddExpr(TotalOffset,
2270 getIntegerSCEV(Offset, IntPtrTy));
2271 } else {
2272 // For an array, add the element offset, explicitly scaled.
2273 SCEVHandle LocalOffset = getSCEV(Index);
2274 if (!isa<PointerType>(LocalOffset->getType()))
2275 // Getelementptr indicies are signed.
2276 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2277 IntPtrTy);
2278 LocalOffset =
2279 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002280 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002281 IntPtrTy));
2282 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2283 }
2284 }
2285 return getAddExpr(getSCEV(Base), TotalOffset);
2286}
2287
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002288/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2289/// guaranteed to end in (at every loop iteration). It is, at the same time,
2290/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2291/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002292static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002293 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002294 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295
Dan Gohmanc76b5452009-05-04 22:02:23 +00002296 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002297 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2298 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002299
Dan Gohmanc76b5452009-05-04 22:02:23 +00002300 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002301 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2302 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002303 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002304 }
2305
Dan Gohmanc76b5452009-05-04 22:02:23 +00002306 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002307 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2308 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002309 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002310 }
2311
Dan Gohmanc76b5452009-05-04 22:02:23 +00002312 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002313 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002314 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002315 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002316 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002317 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002318 }
2319
Dan Gohmanc76b5452009-05-04 22:02:23 +00002320 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002321 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002322 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2323 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002324 for (unsigned i = 1, e = M->getNumOperands();
2325 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002326 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002327 BitWidth);
2328 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002329 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002330
Dan Gohmanc76b5452009-05-04 22:02:23 +00002331 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002332 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002333 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002334 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002335 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002336 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002337 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002338
Dan Gohmanc76b5452009-05-04 22:02:23 +00002339 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002340 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002341 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00002342 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002343 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00002344 return MinOpRes;
2345 }
2346
Dan Gohmanc76b5452009-05-04 22:02:23 +00002347 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002348 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002349 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002350 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002351 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002352 return MinOpRes;
2353 }
2354
Nick Lewycky35b56022009-01-13 09:18:58 +00002355 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002356 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002357}
2358
2359/// createSCEV - We know that there is no SCEV for the specified value.
2360/// Analyze the expression.
2361///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002362SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002363 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002364 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002365
Dan Gohman3996f472008-06-22 19:56:46 +00002366 unsigned Opcode = Instruction::UserOp1;
2367 if (Instruction *I = dyn_cast<Instruction>(V))
2368 Opcode = I->getOpcode();
2369 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2370 Opcode = CE->getOpcode();
2371 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002372 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002373
Dan Gohman3996f472008-06-22 19:56:46 +00002374 User *U = cast<User>(V);
2375 switch (Opcode) {
2376 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002377 return getAddExpr(getSCEV(U->getOperand(0)),
2378 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002379 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002380 return getMulExpr(getSCEV(U->getOperand(0)),
2381 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002382 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002383 return getUDivExpr(getSCEV(U->getOperand(0)),
2384 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002385 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002386 return getMinusSCEV(getSCEV(U->getOperand(0)),
2387 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002388 case Instruction::And:
2389 // For an expression like x&255 that merely masks off the high bits,
2390 // use zext(trunc(x)) as the SCEV expression.
2391 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002392 if (CI->isNullValue())
2393 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002394 if (CI->isAllOnesValue())
2395 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002396 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002397
2398 // Instcombine's ShrinkDemandedConstant may strip bits out of
2399 // constants, obscuring what would otherwise be a low-bits mask.
2400 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2401 // knew about to reconstruct a low-bits mask value.
2402 unsigned LZ = A.countLeadingZeros();
2403 unsigned BitWidth = A.getBitWidth();
2404 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2405 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2406 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2407
2408 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2409
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002410 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002411 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002412 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002413 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002414 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002415 }
2416 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002417
Dan Gohman3996f472008-06-22 19:56:46 +00002418 case Instruction::Or:
2419 // If the RHS of the Or is a constant, we may have something like:
2420 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2421 // optimizations will transparently handle this case.
2422 //
2423 // In order for this transformation to be safe, the LHS must be of the
2424 // form X*(2^n) and the Or constant must be less than 2^n.
2425 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2426 SCEVHandle LHS = getSCEV(U->getOperand(0));
2427 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002428 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002429 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002430 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002431 }
Dan Gohman3996f472008-06-22 19:56:46 +00002432 break;
2433 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002434 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002435 // If the RHS of the xor is a signbit, then this is just an add.
2436 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002437 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002438 return getAddExpr(getSCEV(U->getOperand(0)),
2439 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002440
2441 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002442 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002443 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002444
2445 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2446 // This is a variant of the check for xor with -1, and it handles
2447 // the case where instcombine has trimmed non-demanded bits out
2448 // of an xor with -1.
2449 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2450 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2451 if (BO->getOpcode() == Instruction::And &&
2452 LCI->getValue() == CI->getValue())
2453 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002454 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002455 const Type *UTy = U->getType();
2456 SCEVHandle Z0 = Z->getOperand();
2457 const Type *Z0Ty = Z0->getType();
2458 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2459
2460 // If C is a low-bits mask, the zero extend is zerving to
2461 // mask off the high bits. Complement the operand and
2462 // re-apply the zext.
2463 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2464 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2465
2466 // If C is a single bit, it may be in the sign-bit position
2467 // before the zero-extend. In this case, represent the xor
2468 // using an add, which is equivalent, and re-apply the zext.
2469 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2470 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2471 Trunc.isSignBit())
2472 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2473 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002474 }
Dan Gohman3996f472008-06-22 19:56:46 +00002475 }
2476 break;
2477
2478 case Instruction::Shl:
2479 // Turn shift left of a constant amount into a multiply.
2480 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2481 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2482 Constant *X = ConstantInt::get(
2483 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002484 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002485 }
2486 break;
2487
Nick Lewycky7fd27892008-07-07 06:15:49 +00002488 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002489 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002490 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2491 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2492 Constant *X = ConstantInt::get(
2493 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002494 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002495 }
2496 break;
2497
Dan Gohman53bf64a2009-04-21 02:26:00 +00002498 case Instruction::AShr:
2499 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2500 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2501 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2502 if (L->getOpcode() == Instruction::Shl &&
2503 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002504 unsigned BitWidth = getTypeSizeInBits(U->getType());
2505 uint64_t Amt = BitWidth - CI->getZExtValue();
2506 if (Amt == BitWidth)
2507 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2508 if (Amt > BitWidth)
2509 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002510 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002511 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002512 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002513 U->getType());
2514 }
2515 break;
2516
Dan Gohman3996f472008-06-22 19:56:46 +00002517 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002518 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002519
2520 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002521 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002522
2523 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002524 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002525
2526 case Instruction::BitCast:
2527 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002528 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002529 return getSCEV(U->getOperand(0));
2530 break;
2531
Dan Gohman01c2ee72009-04-16 03:18:22 +00002532 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002533 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002534 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002535 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002536
2537 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002538 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002539 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2540 U->getType());
2541
Dan Gohman509cf4d2009-05-08 20:26:55 +00002542 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002543 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002544 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002545
Dan Gohman3996f472008-06-22 19:56:46 +00002546 case Instruction::PHI:
2547 return createNodeForPHI(cast<PHINode>(U));
2548
2549 case Instruction::Select:
2550 // This could be a smax or umax that was lowered earlier.
2551 // Try to recover it.
2552 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2553 Value *LHS = ICI->getOperand(0);
2554 Value *RHS = ICI->getOperand(1);
2555 switch (ICI->getPredicate()) {
2556 case ICmpInst::ICMP_SLT:
2557 case ICmpInst::ICMP_SLE:
2558 std::swap(LHS, RHS);
2559 // fall through
2560 case ICmpInst::ICMP_SGT:
2561 case ICmpInst::ICMP_SGE:
2562 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002563 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002564 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002565 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002566 return getNotSCEV(getSMaxExpr(
2567 getNotSCEV(getSCEV(LHS)),
2568 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002569 break;
2570 case ICmpInst::ICMP_ULT:
2571 case ICmpInst::ICMP_ULE:
2572 std::swap(LHS, RHS);
2573 // fall through
2574 case ICmpInst::ICMP_UGT:
2575 case ICmpInst::ICMP_UGE:
2576 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002577 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002578 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2579 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002580 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2581 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002582 break;
2583 default:
2584 break;
2585 }
2586 }
2587
2588 default: // We cannot analyze this expression.
2589 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590 }
2591
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002592 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002593}
2594
2595
2596
2597//===----------------------------------------------------------------------===//
2598// Iteration Count Computation Code
2599//
2600
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002601/// getBackedgeTakenCount - If the specified loop has a predictable
2602/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2603/// object. The backedge-taken count is the number of times the loop header
2604/// will be branched to from within the loop. This is one less than the
2605/// trip count of the loop, since it doesn't count the first iteration,
2606/// when the header is branched to from outside the loop.
2607///
2608/// Note that it is not valid to call this method on a loop without a
2609/// loop-invariant backedge-taken count (see
2610/// hasLoopInvariantBackedgeTakenCount).
2611///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002612SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002613 return getBackedgeTakenInfo(L).Exact;
2614}
2615
2616/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2617/// return the least SCEV value that is known never to be less than the
2618/// actual backedge taken count.
2619SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2620 return getBackedgeTakenInfo(L).Max;
2621}
2622
2623const ScalarEvolution::BackedgeTakenInfo &
2624ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002625 // Initially insert a CouldNotCompute for this loop. If the insertion
2626 // succeeds, procede to actually compute a backedge-taken count and
2627 // update the value. The temporary CouldNotCompute value tells SCEV
2628 // code elsewhere that it shouldn't attempt to request a new
2629 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002630 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002631 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2632 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002633 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002634 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002635 assert(ItCount.Exact->isLoopInvariant(L) &&
2636 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002637 "Computed trip count isn't loop invariant for loop!");
2638 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002639
Dan Gohmana9dba962009-04-27 20:16:15 +00002640 // Update the value in the map.
2641 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002642 } else if (isa<PHINode>(L->getHeader()->begin())) {
2643 // Only count loops that have phi nodes as not being computable.
2644 ++NumTripCountsNotComputed;
2645 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002646
2647 // Now that we know more about the trip count for this loop, forget any
2648 // existing SCEV values for PHI nodes in this loop since they are only
2649 // conservative estimates made without the benefit
2650 // of trip count information.
2651 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002652 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002653 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002654 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002655}
2656
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002657/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002658/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002659/// ScalarEvolution's ability to compute a trip count, or if the loop
2660/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002661void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002662 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002663 forgetLoopPHIs(L);
2664}
2665
2666/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2667/// PHI nodes in the given loop. This is used when the trip count of
2668/// the loop may have changed.
2669void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002670 BasicBlock *Header = L->getHeader();
2671
Dan Gohman9fd4a002009-05-12 01:27:58 +00002672 // Push all Loop-header PHIs onto the Worklist stack, except those
2673 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2674 // a PHI either means that it has an unrecognized structure, or it's
2675 // a PHI that's in the progress of being computed by createNodeForPHI.
2676 // In the former case, additional loop trip count information isn't
2677 // going to change anything. In the later case, createNodeForPHI will
2678 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002679 SmallVector<Instruction *, 16> Worklist;
2680 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002681 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2682 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2683 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2684 Worklist.push_back(PN);
2685 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002686
2687 while (!Worklist.empty()) {
2688 Instruction *I = Worklist.pop_back_val();
2689 if (Scalars.erase(I))
2690 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2691 UI != UE; ++UI)
2692 Worklist.push_back(cast<Instruction>(UI));
2693 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002694}
2695
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002696/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2697/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002698ScalarEvolution::BackedgeTakenInfo
2699ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002700 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel7388a9a2009-06-05 23:08:56 +00002701 BasicBlock *ExitBlock = L->getExitBlock();
2702 if (!ExitBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002703 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002704
2705 // Okay, there is one exit block. Try to find the condition that causes the
2706 // loop to be exited.
Devang Patel7388a9a2009-06-05 23:08:56 +00002707 BasicBlock *ExitingBlock = L->getExitingBlock();
2708 if (!ExitingBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002709 return CouldNotCompute; // More than one block exiting!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002710
2711 // Okay, we've computed the exiting block. See what condition causes us to
2712 // exit.
2713 //
2714 // FIXME: we should be able to handle switch instructions (with a single exit)
2715 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002716 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002717 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2718
2719 // At this point, we know we have a conditional branch that determines whether
2720 // the loop is exited. However, we don't know if the branch is executed each
2721 // time through the loop. If not, then the execution count of the branch will
2722 // not be equal to the trip count of the loop.
2723 //
2724 // Currently we check for this by checking to see if the Exit branch goes to
2725 // the loop header. If so, we know it will always execute the same number of
2726 // times as the loop. We also handle the case where the exit block *is* the
2727 // loop header. This is common for un-rotated loops. More extensive analysis
2728 // could be done to handle more cases here.
2729 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2730 ExitBr->getSuccessor(1) != L->getHeader() &&
2731 ExitBr->getParent() != L->getHeader())
Dan Gohman0c850912009-06-06 14:37:11 +00002732 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733
2734 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2735
Eli Friedman459d7292009-05-09 12:32:42 +00002736 // If it's not an integer or pointer comparison then compute it the hard way.
2737 if (ExitCond == 0)
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002738 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739 ExitBr->getSuccessor(0) == ExitBlock);
2740
2741 // If the condition was exit on true, convert the condition to exit on false
2742 ICmpInst::Predicate Cond;
2743 if (ExitBr->getSuccessor(1) == ExitBlock)
2744 Cond = ExitCond->getPredicate();
2745 else
2746 Cond = ExitCond->getInversePredicate();
2747
2748 // Handle common loops like: for (X = "string"; *X; ++X)
2749 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2750 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2751 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002752 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2754 }
2755
2756 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2757 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2758
2759 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00002760 LHS = getSCEVAtScope(LHS, L);
2761 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002762
2763 // At this point, we would like to compute how many iterations of the
2764 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002765 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2766 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002767 std::swap(LHS, RHS);
2768 Cond = ICmpInst::getSwappedPredicate(Cond);
2769 }
2770
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 // If we have a comparison of a chrec against a constant, try to use value
2772 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002773 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2774 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00002776 // Form the constant range.
2777 ConstantRange CompRange(
2778 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779
Eli Friedman459d7292009-05-09 12:32:42 +00002780 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2781 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 }
2783
2784 switch (Cond) {
2785 case ICmpInst::ICMP_NE: { // while (X != Y)
2786 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002787 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002788 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2789 break;
2790 }
2791 case ICmpInst::ICMP_EQ: {
2792 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002793 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002794 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2795 break;
2796 }
2797 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002798 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2799 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002800 break;
2801 }
2802 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002803 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2804 getNotSCEV(RHS), L, true);
2805 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002806 break;
2807 }
2808 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002809 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2810 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002811 break;
2812 }
2813 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002814 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2815 getNotSCEV(RHS), L, false);
2816 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002817 break;
2818 }
2819 default:
2820#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002821 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002823 errs() << "[unsigned] ";
2824 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002825 << Instruction::getOpcodeName(Instruction::ICmp)
2826 << " " << *RHS << "\n";
2827#endif
2828 break;
2829 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002830 return
2831 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2832 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002833}
2834
2835static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002836EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2837 ScalarEvolution &SE) {
2838 SCEVHandle InVal = SE.getConstant(C);
2839 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840 assert(isa<SCEVConstant>(Val) &&
2841 "Evaluation of SCEV at constant didn't fold correctly?");
2842 return cast<SCEVConstant>(Val)->getValue();
2843}
2844
2845/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2846/// and a GEP expression (missing the pointer index) indexing into it, return
2847/// the addressed element of the initializer or null if the index expression is
2848/// invalid.
2849static Constant *
2850GetAddressedElementFromGlobal(GlobalVariable *GV,
2851 const std::vector<ConstantInt*> &Indices) {
2852 Constant *Init = GV->getInitializer();
2853 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2854 uint64_t Idx = Indices[i]->getZExtValue();
2855 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2856 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2857 Init = cast<Constant>(CS->getOperand(Idx));
2858 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2859 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2860 Init = cast<Constant>(CA->getOperand(Idx));
2861 } else if (isa<ConstantAggregateZero>(Init)) {
2862 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2863 assert(Idx < STy->getNumElements() && "Bad struct index!");
2864 Init = Constant::getNullValue(STy->getElementType(Idx));
2865 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2866 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2867 Init = Constant::getNullValue(ATy->getElementType());
2868 } else {
2869 assert(0 && "Unknown constant aggregate type!");
2870 }
2871 return 0;
2872 } else {
2873 return 0; // Unknown initializer type
2874 }
2875 }
2876 return Init;
2877}
2878
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002879/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2880/// 'icmp op load X, cst', try to see if we can compute the backedge
2881/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002882SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002883ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2884 const Loop *L,
2885 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00002886 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002887
2888 // Check to see if the loaded pointer is a getelementptr of a global.
2889 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00002890 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891
2892 // Make sure that it is really a constant global we are gepping, with an
2893 // initializer, and make sure the first IDX is really 0.
2894 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2895 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2896 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2897 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00002898 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002899
2900 // Okay, we allow one non-constant index into the GEP instruction.
2901 Value *VarIdx = 0;
2902 std::vector<ConstantInt*> Indexes;
2903 unsigned VarIdxNum = 0;
2904 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2905 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2906 Indexes.push_back(CI);
2907 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00002908 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002909 VarIdx = GEP->getOperand(i);
2910 VarIdxNum = i-2;
2911 Indexes.push_back(0);
2912 }
2913
2914 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2915 // Check to see if X is a loop variant variable value now.
2916 SCEVHandle Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00002917 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918
2919 // We can only recognize very limited forms of loop index expressions, in
2920 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002921 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002922 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2923 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2924 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00002925 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002926
2927 unsigned MaxSteps = MaxBruteForceIterations;
2928 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2929 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00002930 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002931 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932
2933 // Form the GEP offset.
2934 Indexes[VarIdxNum] = Val;
2935
2936 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2937 if (Result == 0) break; // Cannot compute!
2938
2939 // Evaluate the condition for this iteration.
2940 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2941 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2942 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2943#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002944 errs() << "\n***\n*** Computed loop count " << *ItCst
2945 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2946 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002947#endif
2948 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002949 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950 }
2951 }
Dan Gohman0c850912009-06-06 14:37:11 +00002952 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002953}
2954
2955
2956/// CanConstantFold - Return true if we can constant fold an instruction of the
2957/// specified type, assuming that all operands were constants.
2958static bool CanConstantFold(const Instruction *I) {
2959 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2960 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2961 return true;
2962
2963 if (const CallInst *CI = dyn_cast<CallInst>(I))
2964 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002965 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 return false;
2967}
2968
2969/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2970/// in the loop that V is derived from. We allow arbitrary operations along the
2971/// way, but the operands of an operation must either be constants or a value
2972/// derived from a constant PHI. If this expression does not fit with these
2973/// constraints, return null.
2974static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2975 // If this is not an instruction, or if this is an instruction outside of the
2976 // loop, it can't be derived from a loop PHI.
2977 Instruction *I = dyn_cast<Instruction>(V);
2978 if (I == 0 || !L->contains(I->getParent())) return 0;
2979
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002980 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 if (L->getHeader() == I->getParent())
2982 return PN;
2983 else
2984 // We don't currently keep track of the control flow needed to evaluate
2985 // PHIs, so we cannot handle PHIs inside of loops.
2986 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002987 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988
2989 // If we won't be able to constant fold this expression even if the operands
2990 // are constants, return early.
2991 if (!CanConstantFold(I)) return 0;
2992
2993 // Otherwise, we can evaluate this instruction if all of its operands are
2994 // constant or derived from a PHI node themselves.
2995 PHINode *PHI = 0;
2996 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2997 if (!(isa<Constant>(I->getOperand(Op)) ||
2998 isa<GlobalValue>(I->getOperand(Op)))) {
2999 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3000 if (P == 0) return 0; // Not evolving from PHI
3001 if (PHI == 0)
3002 PHI = P;
3003 else if (PHI != P)
3004 return 0; // Evolving from multiple different PHIs.
3005 }
3006
3007 // This is a expression evolving from a constant PHI!
3008 return PHI;
3009}
3010
3011/// EvaluateExpression - Given an expression that passes the
3012/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3013/// in the loop has the value PHIVal. If we can't fold this expression for some
3014/// reason, return null.
3015static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3016 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003018 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003019 Instruction *I = cast<Instruction>(V);
3020
3021 std::vector<Constant*> Operands;
3022 Operands.resize(I->getNumOperands());
3023
3024 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3025 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3026 if (Operands[i] == 0) return 0;
3027 }
3028
Chris Lattnerd6e56912007-12-10 22:53:04 +00003029 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3030 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3031 &Operands[0], Operands.size());
3032 else
3033 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3034 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035}
3036
3037/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3038/// in the header of its containing loop, we know the loop executes a
3039/// constant number of times, and the PHI node is just a recurrence
3040/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003041Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003042getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043 std::map<PHINode*, Constant*>::iterator I =
3044 ConstantEvolutionLoopExitValue.find(PN);
3045 if (I != ConstantEvolutionLoopExitValue.end())
3046 return I->second;
3047
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003048 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003049 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3050
3051 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3052
3053 // Since the loop is canonicalized, the PHI node must have two entries. One
3054 // entry must be a constant (coming in from outside of the loop), and the
3055 // second must be derived from the same PHI.
3056 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3057 Constant *StartCST =
3058 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3059 if (StartCST == 0)
3060 return RetVal = 0; // Must be a constant.
3061
3062 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3063 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3064 if (PN2 != PN)
3065 return RetVal = 0; // Not derived from same PHI.
3066
3067 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003068 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003069 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3070
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003071 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003072 unsigned IterationNum = 0;
3073 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3074 if (IterationNum == NumIterations)
3075 return RetVal = PHIVal; // Got exit value!
3076
3077 // Compute the value of the PHI node for the next iteration.
3078 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3079 if (NextPHI == PHIVal)
3080 return RetVal = NextPHI; // Stopped evolving!
3081 if (NextPHI == 0)
3082 return 0; // Couldn't evaluate!
3083 PHIVal = NextPHI;
3084 }
3085}
3086
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003087/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003088/// constant number of times (the condition evolves only from constants),
3089/// try to evaluate a few iterations of the loop until we get the exit
3090/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00003091/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003092SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003093ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003094 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003095 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003096
3097 // Since the loop is canonicalized, the PHI node must have two entries. One
3098 // entry must be a constant (coming in from outside of the loop), and the
3099 // second must be derived from the same PHI.
3100 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3101 Constant *StartCST =
3102 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00003103 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003104
3105 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3106 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003107 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003108
3109 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3110 // the loop symbolically to determine when the condition gets a value of
3111 // "ExitWhen".
3112 unsigned IterationNum = 0;
3113 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3114 for (Constant *PHIVal = StartCST;
3115 IterationNum != MaxIterations; ++IterationNum) {
3116 ConstantInt *CondVal =
3117 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3118
3119 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003120 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121
3122 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3123 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3124 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003125 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003126 }
3127
3128 // Compute the value of the PHI node for the next iteration.
3129 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3130 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00003131 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003132 PHIVal = NextPHI;
3133 }
3134
3135 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003136 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003137}
3138
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003139/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3140/// at the specified scope in the program. The L value specifies a loop
3141/// nest to evaluate the expression at, where null is the top-level or a
3142/// specified loop is immediately inside of the loop.
3143///
3144/// This method can be used to compute the exit value for a variable defined
3145/// in a loop by querying what the value will hold in the parent loop.
3146///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003147/// In the case that a relevant loop exit value cannot be computed, the
3148/// original value V is returned.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003149SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003150 // FIXME: this should be turned into a virtual method on SCEV!
3151
3152 if (isa<SCEVConstant>(V)) return V;
3153
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003154 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003156 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003157 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003158 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3160 if (PHINode *PN = dyn_cast<PHINode>(I))
3161 if (PN->getParent() == LI->getHeader()) {
3162 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003163 // to see if the loop that contains it has a known backedge-taken
3164 // count. If so, we may be able to force computation of the exit
3165 // value.
3166 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003167 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003168 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003169 // Okay, we know how many times the containing loop executes. If
3170 // this is a constant evolving PHI node, get the final value at
3171 // the specified iteration number.
3172 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003173 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003174 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003175 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176 }
3177 }
3178
3179 // Okay, this is an expression that we cannot symbolically evaluate
3180 // into a SCEV. Check to see if it's possible to symbolically evaluate
3181 // the arguments into constants, and if so, try to constant propagate the
3182 // result. This is particularly useful for computing loop exit values.
3183 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003184 // Check to see if we've folded this instruction at this loop before.
3185 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3186 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3187 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3188 if (!Pair.second)
3189 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3190
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003191 std::vector<Constant*> Operands;
3192 Operands.reserve(I->getNumOperands());
3193 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3194 Value *Op = I->getOperand(i);
3195 if (Constant *C = dyn_cast<Constant>(Op)) {
3196 Operands.push_back(C);
3197 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003198 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003199 // non-integer and non-pointer, don't even try to analyze them
3200 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003201 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003202 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003203
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003205 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003206 Constant *C = SC->getValue();
3207 if (C->getType() != Op->getType())
3208 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3209 Op->getType(),
3210 false),
3211 C, Op->getType());
3212 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003213 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003214 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3215 if (C->getType() != Op->getType())
3216 C =
3217 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3218 Op->getType(),
3219 false),
3220 C, Op->getType());
3221 Operands.push_back(C);
3222 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003223 return V;
3224 } else {
3225 return V;
3226 }
3227 }
3228 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00003229
3230 Constant *C;
3231 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3232 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3233 &Operands[0], Operands.size());
3234 else
3235 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3236 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003237 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003238 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003239 }
3240 }
3241
3242 // This is some other type of SCEVUnknown, just return it.
3243 return V;
3244 }
3245
Dan Gohmanc76b5452009-05-04 22:02:23 +00003246 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003247 // Avoid performing the look-up in the common case where the specified
3248 // expression has no loop-variant portions.
3249 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3250 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3251 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003252 // Okay, at least one of these operands is loop variant but might be
3253 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman02ff9392009-06-14 22:47:23 +00003254 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003255 NewOps.push_back(OpAtScope);
3256
3257 for (++i; i != e; ++i) {
3258 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 NewOps.push_back(OpAtScope);
3260 }
3261 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003262 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003263 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003264 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003265 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003266 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003267 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003268 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003269 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003270 }
3271 }
3272 // If we got here, all operands are loop invariant.
3273 return Comm;
3274 }
3275
Dan Gohmanc76b5452009-05-04 22:02:23 +00003276 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003277 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003278 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003279 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3280 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003281 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003282 }
3283
3284 // If this is a loop recurrence for a loop that does not contain L, then we
3285 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003286 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003287 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3288 // To evaluate this recurrence, we need to know how many times the AddRec
3289 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003290 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003291 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292
Eli Friedman7489ec92008-08-04 23:49:06 +00003293 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003294 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003296 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003297 }
3298
Dan Gohmanc76b5452009-05-04 22:02:23 +00003299 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003300 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003301 if (Op == Cast->getOperand())
3302 return Cast; // must be loop invariant
3303 return getZeroExtendExpr(Op, Cast->getType());
3304 }
3305
Dan Gohmanc76b5452009-05-04 22:02:23 +00003306 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003307 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003308 if (Op == Cast->getOperand())
3309 return Cast; // must be loop invariant
3310 return getSignExtendExpr(Op, Cast->getType());
3311 }
3312
Dan Gohmanc76b5452009-05-04 22:02:23 +00003313 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003314 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003315 if (Op == Cast->getOperand())
3316 return Cast; // must be loop invariant
3317 return getTruncateExpr(Op, Cast->getType());
3318 }
3319
3320 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003321 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003322}
3323
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003324/// getSCEVAtScope - This is a convenience function which does
3325/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003326SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3327 return getSCEVAtScope(getSCEV(V), L);
3328}
3329
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003330/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3331/// following equation:
3332///
3333/// A * X = B (mod N)
3334///
3335/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3336/// A and B isn't important.
3337///
3338/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3339static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3340 ScalarEvolution &SE) {
3341 uint32_t BW = A.getBitWidth();
3342 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3343 assert(A != 0 && "A must be non-zero.");
3344
3345 // 1. D = gcd(A, N)
3346 //
3347 // The gcd of A and N may have only one prime factor: 2. The number of
3348 // trailing zeros in A is its multiplicity
3349 uint32_t Mult2 = A.countTrailingZeros();
3350 // D = 2^Mult2
3351
3352 // 2. Check if B is divisible by D.
3353 //
3354 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3355 // is not less than multiplicity of this prime factor for D.
3356 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003357 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003358
3359 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3360 // modulo (N / D).
3361 //
3362 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3363 // bit width during computations.
3364 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3365 APInt Mod(BW + 1, 0);
3366 Mod.set(BW - Mult2); // Mod = N / D
3367 APInt I = AD.multiplicativeInverse(Mod);
3368
3369 // 4. Compute the minimum unsigned root of the equation:
3370 // I * (B / D) mod (N / D)
3371 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3372
3373 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3374 // bits.
3375 return SE.getConstant(Result.trunc(BW));
3376}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377
3378/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3379/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3380/// might be the same) or two SCEVCouldNotCompute objects.
3381///
3382static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00003383SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003385 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3386 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3387 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003388
3389 // We currently can only solve this if the coefficients are constants.
3390 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003391 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003392 return std::make_pair(CNC, CNC);
3393 }
3394
3395 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3396 const APInt &L = LC->getValue()->getValue();
3397 const APInt &M = MC->getValue()->getValue();
3398 const APInt &N = NC->getValue()->getValue();
3399 APInt Two(BitWidth, 2);
3400 APInt Four(BitWidth, 4);
3401
3402 {
3403 using namespace APIntOps;
3404 const APInt& C = L;
3405 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3406 // The B coefficient is M-N/2
3407 APInt B(M);
3408 B -= sdiv(N,Two);
3409
3410 // The A coefficient is N/2
3411 APInt A(N.sdiv(Two));
3412
3413 // Compute the B^2-4ac term.
3414 APInt SqrtTerm(B);
3415 SqrtTerm *= B;
3416 SqrtTerm -= Four * (A * C);
3417
3418 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3419 // integer value or else APInt::sqrt() will assert.
3420 APInt SqrtVal(SqrtTerm.sqrt());
3421
3422 // Compute the two solutions for the quadratic formula.
3423 // The divisions must be performed as signed divisions.
3424 APInt NegB(-B);
3425 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003426 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003427 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003428 return std::make_pair(CNC, CNC);
3429 }
3430
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003431 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3432 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3433
Dan Gohman89f85052007-10-22 18:31:58 +00003434 return std::make_pair(SE.getConstant(Solution1),
3435 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003436 } // end APIntOps namespace
3437}
3438
3439/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003440/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003441SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003443 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 // If the value is already zero, the branch will execute zero times.
3445 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003446 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447 }
3448
Dan Gohmanbff6b582009-05-04 22:30:44 +00003449 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003450 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003451 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003452
3453 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003454 // If this is an affine expression, the execution count of this branch is
3455 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003457 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003458 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003459 // equivalent to:
3460 //
3461 // Step*N = -Start (mod 2^BW)
3462 //
3463 // where BW is the common bit width of Start and Step.
3464
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003465 // Get the initial value for the loop.
3466 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003467 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003468
Dan Gohmanc76b5452009-05-04 22:02:23 +00003469 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003470 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003471
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003472 // First, handle unitary steps.
3473 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003474 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003475 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3476 return Start; // N = Start (as unsigned)
3477
3478 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003479 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003480 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003481 -StartC->getValue()->getValue(),
3482 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003483 }
3484 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3485 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3486 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003487 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3488 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003489 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3490 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003491 if (R1) {
3492#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003493 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3494 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495#endif
3496 // Pick the smallest positive root value.
3497 if (ConstantInt *CB =
3498 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3499 R1->getValue(), R2->getValue()))) {
3500 if (CB->getZExtValue() == false)
3501 std::swap(R1, R2); // R1 is the minimum root now.
3502
3503 // We can only use this value if the chrec ends up with an exact zero
3504 // value at this index. When solving for "X*X != 5", for example, we
3505 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003506 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003507 if (Val->isZero())
3508 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003509 }
3510 }
3511 }
3512
Dan Gohman0c850912009-06-06 14:37:11 +00003513 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514}
3515
3516/// HowFarToNonZero - Return the number of times a backedge checking the
3517/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003518/// CouldNotCompute
Dan Gohmanbff6b582009-05-04 22:30:44 +00003519SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520 // Loops that look like: while (X == 0) are very strange indeed. We don't
3521 // handle them yet except for the trivial case. This could be expanded in the
3522 // future as needed.
3523
3524 // If the value is a constant, check to see if it is known to be non-zero
3525 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003526 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003527 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003528 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003529 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003530 }
3531
3532 // We could implement others, but I really doubt anyone writes loops like
3533 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003534 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003535}
3536
Dan Gohmanab157b22009-05-18 15:36:09 +00003537/// getLoopPredecessor - If the given loop's header has exactly one unique
3538/// predecessor outside the loop, return it. Otherwise return null.
3539///
3540BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3541 BasicBlock *Header = L->getHeader();
3542 BasicBlock *Pred = 0;
3543 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3544 PI != E; ++PI)
3545 if (!L->contains(*PI)) {
3546 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3547 Pred = *PI;
3548 }
3549 return Pred;
3550}
3551
Dan Gohman1cddf972008-09-15 22:18:04 +00003552/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3553/// (which may not be an immediate predecessor) which has exactly one
3554/// successor from which BB is reachable, or null if no such block is
3555/// found.
3556///
3557BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003558ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003559 // If the block has a unique predecessor, then there is no path from the
3560 // predecessor to the block that does not go through the direct edge
3561 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003562 if (BasicBlock *Pred = BB->getSinglePredecessor())
3563 return Pred;
3564
3565 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003566 // If the header has a unique predecessor outside the loop, it must be
3567 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003568 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003569 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003570
3571 return 0;
3572}
3573
Dan Gohmancacd2012009-02-12 22:19:27 +00003574/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003575/// a conditional between LHS and RHS. This is used to help avoid max
3576/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003577bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003578 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003579 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003580 // Interpret a null as meaning no loop, where there is obviously no guard
3581 // (interprocedural conditions notwithstanding).
3582 if (!L) return false;
3583
Dan Gohmanab157b22009-05-18 15:36:09 +00003584 BasicBlock *Predecessor = getLoopPredecessor(L);
3585 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003586
Dan Gohmanab157b22009-05-18 15:36:09 +00003587 // Starting at the loop predecessor, climb up the predecessor chain, as long
3588 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003589 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003590 for (; Predecessor;
3591 PredecessorDest = Predecessor,
3592 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003593
3594 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003595 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003596 if (!LoopEntryPredicate ||
3597 LoopEntryPredicate->isUnconditional())
3598 continue;
3599
3600 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3601 if (!ICI) continue;
3602
3603 // Now that we found a conditional branch that dominates the loop, check to
3604 // see if it is the comparison we are looking for.
3605 Value *PreCondLHS = ICI->getOperand(0);
3606 Value *PreCondRHS = ICI->getOperand(1);
3607 ICmpInst::Predicate Cond;
Dan Gohmanab157b22009-05-18 15:36:09 +00003608 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohmanab678fb2008-08-12 20:17:31 +00003609 Cond = ICI->getPredicate();
3610 else
3611 Cond = ICI->getInversePredicate();
3612
Dan Gohmancacd2012009-02-12 22:19:27 +00003613 if (Cond == Pred)
3614 ; // An exact match.
3615 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3616 ; // The actual condition is beyond sufficient.
3617 else
3618 // Check a few special cases.
3619 switch (Cond) {
3620 case ICmpInst::ICMP_UGT:
3621 if (Pred == ICmpInst::ICMP_ULT) {
3622 std::swap(PreCondLHS, PreCondRHS);
3623 Cond = ICmpInst::ICMP_ULT;
3624 break;
3625 }
3626 continue;
3627 case ICmpInst::ICMP_SGT:
3628 if (Pred == ICmpInst::ICMP_SLT) {
3629 std::swap(PreCondLHS, PreCondRHS);
3630 Cond = ICmpInst::ICMP_SLT;
3631 break;
3632 }
3633 continue;
3634 case ICmpInst::ICMP_NE:
3635 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3636 // so check for this case by checking if the NE is comparing against
3637 // a minimum or maximum constant.
3638 if (!ICmpInst::isTrueWhenEqual(Pred))
3639 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3640 const APInt &A = CI->getValue();
3641 switch (Pred) {
3642 case ICmpInst::ICMP_SLT:
3643 if (A.isMaxSignedValue()) break;
3644 continue;
3645 case ICmpInst::ICMP_SGT:
3646 if (A.isMinSignedValue()) break;
3647 continue;
3648 case ICmpInst::ICMP_ULT:
3649 if (A.isMaxValue()) break;
3650 continue;
3651 case ICmpInst::ICMP_UGT:
3652 if (A.isMinValue()) break;
3653 continue;
3654 default:
3655 continue;
3656 }
3657 Cond = ICmpInst::ICMP_NE;
3658 // NE is symmetric but the original comparison may not be. Swap
3659 // the operands if necessary so that they match below.
3660 if (isa<SCEVConstant>(LHS))
3661 std::swap(PreCondLHS, PreCondRHS);
3662 break;
3663 }
3664 continue;
3665 default:
3666 // We weren't able to reconcile the condition.
3667 continue;
3668 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003669
3670 if (!PreCondLHS->getType()->isInteger()) continue;
3671
3672 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3673 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3674 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003675 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3676 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003677 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003678 }
3679
Dan Gohmanab678fb2008-08-12 20:17:31 +00003680 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003681}
3682
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003683/// HowManyLessThans - Return the number of times a backedge containing the
3684/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003685/// CouldNotCompute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003686ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003687HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3688 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003689 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00003690 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691
Dan Gohmanbff6b582009-05-04 22:30:44 +00003692 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003694 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003695
3696 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003697 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003698 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3699 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3700 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3701
3702 // TODO: handle non-constant strides.
3703 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3704 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00003705 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00003706 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003707 // With unit stride, the iteration never steps past the limit value.
3708 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3709 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3710 // Test whether a positive iteration iteration can step past the limit
3711 // value and past the maximum value for its type in a single step.
3712 if (isSigned) {
3713 APInt Max = APInt::getSignedMaxValue(BitWidth);
3714 if ((Max - CStep->getValue()->getValue())
3715 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003716 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003717 } else {
3718 APInt Max = APInt::getMaxValue(BitWidth);
3719 if ((Max - CStep->getValue()->getValue())
3720 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003721 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003722 }
3723 } else
3724 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00003725 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003726 } else
3727 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00003728 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003729
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003730 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3731 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3732 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003733 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003734
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003735 // First, we get the value of the LHS in the first iteration: n
3736 SCEVHandle Start = AddRec->getOperand(0);
3737
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003738 // Determine the minimum constant start value.
3739 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3740 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3741 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003742
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003743 // If we know that the condition is true in order to enter the loop,
3744 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00003745 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3746 // the division must round up.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003747 SCEVHandle End = RHS;
3748 if (!isLoopGuardedByCond(L,
3749 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3750 getMinusSCEV(Start, Step), RHS))
3751 End = isSigned ? getSMaxExpr(RHS, Start)
3752 : getUMaxExpr(RHS, Start);
3753
3754 // Determine the maximum constant end value.
3755 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3756 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3757 APInt::getMaxValue(BitWidth));
3758
3759 // Finally, we subtract these two values and divide, rounding up, to get
3760 // the number of times the backedge is executed.
3761 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3762 getAddExpr(Step, NegOne)),
3763 Step);
3764
3765 // The maximum backedge count is similar, except using the minimum start
3766 // value and the maximum end value.
3767 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3768 MinStart),
3769 getAddExpr(Step, NegOne)),
3770 Step);
3771
3772 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003773 }
3774
Dan Gohman0c850912009-06-06 14:37:11 +00003775 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003776}
3777
3778/// getNumIterationsInRange - Return the number of iterations of this loop that
3779/// produce values in the specified constant range. Another way of looking at
3780/// this is that it returns the first iteration number where the value is not in
3781/// the condition, thus computing the exit count. If the iteration count can't
3782/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003783SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3784 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003785 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003786 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003787
3788 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003789 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003790 if (!SC->getValue()->isZero()) {
Dan Gohman02ff9392009-06-14 22:47:23 +00003791 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003792 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3793 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003794 if (const SCEVAddRecExpr *ShiftedAddRec =
3795 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003797 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003798 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003799 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003800 }
3801
3802 // The only time we can solve this is when we have all constant indices.
3803 // Otherwise, we cannot determine the overflow conditions.
3804 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3805 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003806 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807
3808
3809 // Okay at this point we know that all elements of the chrec are constants and
3810 // that the start element is zero.
3811
3812 // First check to see if the range contains zero. If not, the first
3813 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003814 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003815 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00003816 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003817
3818 if (isAffine()) {
3819 // If this is an affine expression then we have this situation:
3820 // Solve {0,+,A} in Range === Ax in Range
3821
3822 // We know that zero is in the range. If A is positive then we know that
3823 // the upper value of the range must be the first possible exit value.
3824 // If A is negative then the lower of the range is the last possible loop
3825 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003826 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003827 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3828 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3829
3830 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003831 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3833
3834 // Evaluate at the exit value. If we really did fall out of the valid
3835 // range, then we computed our trip count, otherwise wrap around or other
3836 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003837 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003838 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003839 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003840
3841 // Ensure that the previous value is in the range. This is a sanity check.
3842 assert(Range.contains(
3843 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003844 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003845 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003846 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003847 } else if (isQuadratic()) {
3848 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3849 // quadratic equation to solve it. To do this, we must frame our problem in
3850 // terms of figuring out when zero is crossed, instead of when
3851 // Range.getUpper() is crossed.
Dan Gohman02ff9392009-06-14 22:47:23 +00003852 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003853 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3854 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003855
3856 // Next, solve the constructed addrec
3857 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003858 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003859 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3860 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003861 if (R1) {
3862 // Pick the smallest positive root value.
3863 if (ConstantInt *CB =
3864 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3865 R1->getValue(), R2->getValue()))) {
3866 if (CB->getZExtValue() == false)
3867 std::swap(R1, R2); // R1 is the minimum root now.
3868
3869 // Make sure the root is not off by one. The returned iteration should
3870 // not be in the range, but the previous one should be. When solving
3871 // for "X*X < 5", for example, we should not return a root of 2.
3872 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003873 R1->getValue(),
3874 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003875 if (Range.contains(R1Val->getValue())) {
3876 // The next iteration must be out of the range...
3877 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3878
Dan Gohman89f85052007-10-22 18:31:58 +00003879 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003880 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003881 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003882 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003883 }
3884
3885 // If R1 was not in the range, then it is a good return value. Make
3886 // sure that R1-1 WAS in the range though, just in case.
3887 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003888 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003889 if (Range.contains(R1Val->getValue()))
3890 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003891 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003892 }
3893 }
3894 }
3895
Dan Gohman0ad08b02009-04-18 17:58:19 +00003896 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003897}
3898
3899
3900
3901//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003902// SCEVCallbackVH Class Implementation
3903//===----------------------------------------------------------------------===//
3904
Dan Gohman999d14e2009-05-19 19:22:47 +00003905void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003906 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3907 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3908 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003909 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3910 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003911 SE->Scalars.erase(getValPtr());
3912 // this now dangles!
3913}
3914
Dan Gohman999d14e2009-05-19 19:22:47 +00003915void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003916 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3917
3918 // Forget all the expressions associated with users of the old value,
3919 // so that future queries will recompute the expressions using the new
3920 // value.
3921 SmallVector<User *, 16> Worklist;
3922 Value *Old = getValPtr();
3923 bool DeleteOld = false;
3924 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3925 UI != UE; ++UI)
3926 Worklist.push_back(*UI);
3927 while (!Worklist.empty()) {
3928 User *U = Worklist.pop_back_val();
3929 // Deleting the Old value will cause this to dangle. Postpone
3930 // that until everything else is done.
3931 if (U == Old) {
3932 DeleteOld = true;
3933 continue;
3934 }
3935 if (PHINode *PN = dyn_cast<PHINode>(U))
3936 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003937 if (Instruction *I = dyn_cast<Instruction>(U))
3938 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003939 if (SE->Scalars.erase(U))
3940 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3941 UI != UE; ++UI)
3942 Worklist.push_back(*UI);
3943 }
3944 if (DeleteOld) {
3945 if (PHINode *PN = dyn_cast<PHINode>(Old))
3946 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003947 if (Instruction *I = dyn_cast<Instruction>(Old))
3948 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003949 SE->Scalars.erase(Old);
3950 // this now dangles!
3951 }
3952 // this may dangle!
3953}
3954
Dan Gohman999d14e2009-05-19 19:22:47 +00003955ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00003956 : CallbackVH(V), SE(se) {}
3957
3958//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003959// ScalarEvolution Class Implementation
3960//===----------------------------------------------------------------------===//
3961
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003962ScalarEvolution::ScalarEvolution()
Dan Gohman0c850912009-06-06 14:37:11 +00003963 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003964}
3965
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003966bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003967 this->F = &F;
3968 LI = &getAnalysis<LoopInfo>();
3969 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003970 return false;
3971}
3972
3973void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003974 Scalars.clear();
3975 BackedgeTakenCounts.clear();
3976 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00003977 ValuesAtScopes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003978}
3979
3980void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3981 AU.setPreservesAll();
3982 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003983}
3984
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003985bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003986 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003987}
3988
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003989static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003990 const Loop *L) {
3991 // Print all inner loops first
3992 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3993 PrintLoopInfo(OS, SE, *I);
3994
Nick Lewyckye5da1912008-01-02 02:49:20 +00003995 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003996
Devang Patel02451fa2007-08-21 00:31:24 +00003997 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003998 L->getExitBlocks(ExitBlocks);
3999 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004000 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004001
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004002 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4003 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004004 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004005 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004006 }
4007
Nick Lewyckye5da1912008-01-02 02:49:20 +00004008 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004009}
4010
Dan Gohman13058cc2009-04-21 00:47:46 +00004011void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004012 // ScalarEvolution's implementaiton of the print method is to print
4013 // out SCEV values of all instructions that are interesting. Doing
4014 // this potentially causes it to create new SCEV objects though,
4015 // which technically conflicts with the const qualifier. This isn't
4016 // observable from outside the class though (the hasSCEV function
4017 // notwithstanding), so casting away the const isn't dangerous.
4018 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004019
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004020 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004021 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004022 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004023 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004024 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004025 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004026 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004027
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004028 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004029 OS << "\t\t" "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004030 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004031 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004032 OS << "<<Unknown>>";
4033 } else {
4034 OS << *ExitValue;
4035 }
4036 }
4037
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004038 OS << "\n";
4039 }
4040
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004041 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4042 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4043 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004044}
Dan Gohman13058cc2009-04-21 00:47:46 +00004045
4046void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4047 raw_os_ostream OS(o);
4048 print(OS, M);
4049}