blob: 94b75baeee0451db8f07a09d58db92823ab2e7d6 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000070#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000073#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000074#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000075#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000076#include "llvm/Support/ConstantRange.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000077#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000078#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000079#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000080#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000081#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000082#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000083#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000084#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000085using namespace llvm;
86
Chris Lattner3b27d682006-12-19 22:30:33 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman844731a2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman844731a2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000104char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
Chris Lattner53e677a2004-04-02 20:23:17 +0000113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000122}
123
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohman70a1fe72009-05-18 15:22:39 +0000130bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
133 return false;
134}
Chris Lattner53e677a2004-04-02 20:23:17 +0000135
Owen Anderson4a7893b2009-06-18 22:25:12 +0000136SCEVCouldNotCompute::SCEVCouldNotCompute(const ScalarEvolution* p) :
137 SCEV(scCouldNotCompute, p) {}
Dan Gohmanf8a8be82009-04-21 23:15:49 +0000138SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
Chris Lattner4dc534c2005-02-13 04:37:18 +0000155SCEVHandle SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000159 return this;
160}
161
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000162void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000163 OS << "***COULDNOTCOMPUTE***";
164}
165
166bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
168}
169
170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171// SCEVConstants - Only allow the creation of one SCEVConstant for any
172// particular value. Don't use a SCEVHandle here, or else the object will
173// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000174static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000175
Chris Lattner53e677a2004-04-02 20:23:17 +0000176
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000178 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000179}
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Dan Gohman246b2562007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000182 SCEVConstant *&R = (*SCEVConstants)[V];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000183 if (R == 0) R = new SCEVConstant(V, this);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184 return R;
185}
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Dan Gohman246b2562007-10-22 18:31:58 +0000187SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
188 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000189}
190
Dan Gohman6de29f82009-06-15 22:12:54 +0000191SCEVHandle
192ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
193 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
194}
195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000198void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 WriteAsOperand(OS, V, false);
200}
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Dan Gohman84923602009-04-21 01:25:57 +0000202SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Anderson4a7893b2009-06-18 22:25:12 +0000203 const SCEVHandle &op, const Type *ty,
204 const ScalarEvolution* p)
205 : SCEV(SCEVTy, p), Op(op), Ty(ty) {}
Dan Gohman84923602009-04-21 01:25:57 +0000206
207SCEVCastExpr::~SCEVCastExpr() {}
208
209bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->dominates(BB, DT);
211}
212
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
214// particular input. Don't use a SCEVHandle here, or else the object will
215// never be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000216static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Chris Lattnerb3364092006-10-04 21:49:37 +0000217 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Owen Anderson4a7893b2009-06-18 22:25:12 +0000219SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty,
220 const ScalarEvolution* p)
221 : SCEVCastExpr(scTruncate, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000222 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
223 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000225}
Chris Lattner53e677a2004-04-02 20:23:17 +0000226
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000228 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000229}
Chris Lattner53e677a2004-04-02 20:23:17 +0000230
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000231void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000232 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233}
234
235// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
236// particular input. Don't use a SCEVHandle here, or else the object will never
237// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000238static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Chris Lattnerb3364092006-10-04 21:49:37 +0000239 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000240
Owen Anderson4a7893b2009-06-18 22:25:12 +0000241SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty,
242 const ScalarEvolution* p)
243 : SCEVCastExpr(scZeroExtend, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000244 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
245 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000246 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000247}
248
249SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000250 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251}
252
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000253void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000254 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000255}
256
Dan Gohmand19534a2007-06-15 14:38:12 +0000257// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
258// particular input. Don't use a SCEVHandle here, or else the object will never
259// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000260static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmand19534a2007-06-15 14:38:12 +0000261 SCEVSignExtendExpr*> > SCEVSignExtends;
262
Owen Anderson4a7893b2009-06-18 22:25:12 +0000263SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty,
264 const ScalarEvolution* p)
265 : SCEVCastExpr(scSignExtend, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000266 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
267 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000268 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000269}
270
271SCEVSignExtendExpr::~SCEVSignExtendExpr() {
272 SCEVSignExtends->erase(std::make_pair(Op, Ty));
273}
274
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000275void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000276 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000277}
278
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000279// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
280// particular input. Don't use a SCEVHandle here, or else the object will never
281// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000282static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Chris Lattnerb3364092006-10-04 21:49:37 +0000283 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000284
285SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohman35738ac2009-05-04 22:30:44 +0000286 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
287 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000288}
289
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000290void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000291 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
292 const char *OpStr = getOperationStr();
293 OS << "(" << *Operands[0];
294 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
295 OS << OpStr << *Operands[i];
296 OS << ")";
297}
298
Chris Lattner4dc534c2005-02-13 04:37:18 +0000299SCEVHandle SCEVCommutativeExpr::
300replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000301 const SCEVHandle &Conc,
302 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000303 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000304 SCEVHandle H =
305 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000306 if (H != getOperand(i)) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000307 SmallVector<SCEVHandle, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000308 NewOps.reserve(getNumOperands());
309 for (unsigned j = 0; j != i; ++j)
310 NewOps.push_back(getOperand(j));
311 NewOps.push_back(H);
312 for (++i; i != e; ++i)
313 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000314 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000315
316 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000317 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000318 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000319 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000320 else if (isa<SCEVSMaxExpr>(this))
321 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000322 else if (isa<SCEVUMaxExpr>(this))
323 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000324 else
325 assert(0 && "Unknown commutative expr!");
326 }
327 }
328 return this;
329}
330
Dan Gohmanecb403a2009-05-07 14:00:19 +0000331bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000332 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
333 if (!getOperand(i)->dominates(BB, DT))
334 return false;
335 }
336 return true;
337}
338
Chris Lattner4dc534c2005-02-13 04:37:18 +0000339
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000340// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000341// input. Don't use a SCEVHandle here, or else the object will never be
342// deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000343static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000344 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000346SCEVUDivExpr::~SCEVUDivExpr() {
347 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000348}
349
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000350bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
351 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
352}
353
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000354void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000355 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000356}
357
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000358const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000359 // In most cases the types of LHS and RHS will be the same, but in some
360 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
361 // depend on the type for correctness, but handling types carefully can
362 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
363 // a pointer type than the RHS, so use the RHS' type here.
364 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000365}
366
367// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
368// particular input. Don't use a SCEVHandle here, or else the object will never
369// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000370static ManagedStatic<std::map<std::pair<const Loop *,
371 std::vector<const SCEV*> >,
Chris Lattnerb3364092006-10-04 21:49:37 +0000372 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000373
374SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohman35738ac2009-05-04 22:30:44 +0000375 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
376 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000377}
378
Chris Lattner4dc534c2005-02-13 04:37:18 +0000379SCEVHandle SCEVAddRecExpr::
380replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000381 const SCEVHandle &Conc,
382 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000383 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000384 SCEVHandle H =
385 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000386 if (H != getOperand(i)) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000387 SmallVector<SCEVHandle, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000388 NewOps.reserve(getNumOperands());
389 for (unsigned j = 0; j != i; ++j)
390 NewOps.push_back(getOperand(j));
391 NewOps.push_back(H);
392 for (++i; i != e; ++i)
393 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000394 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000395
Dan Gohman246b2562007-10-22 18:31:58 +0000396 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000397 }
398 }
399 return this;
400}
401
402
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000403bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
404 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000405 // contain L and if the start is invariant.
Dan Gohmana3035a62009-05-20 01:01:24 +0000406 // Add recurrences are never invariant in the function-body (null loop).
407 return QueryLoop &&
408 !QueryLoop->contains(L->getHeader()) &&
Chris Lattnerff2006a2005-08-16 00:37:01 +0000409 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000410}
411
412
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000413void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000414 OS << "{" << *Operands[0];
415 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
416 OS << ",+," << *Operands[i];
417 OS << "}<" << L->getHeader()->getName() + ">";
418}
Chris Lattner53e677a2004-04-02 20:23:17 +0000419
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000420// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
421// value. Don't use a SCEVHandle here, or else the object will never be
422// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000423static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000424
Chris Lattnerb3364092006-10-04 21:49:37 +0000425SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000426
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000427bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
428 // All non-instruction values are loop invariant. All instructions are loop
429 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000430 // Instructions are never considered invariant in the function body
431 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000432 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000433 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000434 return true;
435}
Chris Lattner53e677a2004-04-02 20:23:17 +0000436
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000437bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
438 if (Instruction *I = dyn_cast<Instruction>(getValue()))
439 return DT->dominates(I->getParent(), BB);
440 return true;
441}
442
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000443const Type *SCEVUnknown::getType() const {
444 return V->getType();
445}
Chris Lattner53e677a2004-04-02 20:23:17 +0000446
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000447void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000448 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000449}
450
Chris Lattner8d741b82004-06-20 06:23:15 +0000451//===----------------------------------------------------------------------===//
452// SCEV Utilities
453//===----------------------------------------------------------------------===//
454
455namespace {
456 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
457 /// than the complexity of the RHS. This comparator is used to canonicalize
458 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000459 class VISIBILITY_HIDDEN SCEVComplexityCompare {
460 LoopInfo *LI;
461 public:
462 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
463
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000464 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000465 // Primarily, sort the SCEVs by their getSCEVType().
466 if (LHS->getSCEVType() != RHS->getSCEVType())
467 return LHS->getSCEVType() < RHS->getSCEVType();
468
469 // Aside from the getSCEVType() ordering, the particular ordering
470 // isn't very important except that it's beneficial to be consistent,
471 // so that (a + b) and (b + a) don't end up as different expressions.
472
473 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
474 // not as complete as it could be.
475 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
476 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
477
Dan Gohman5be18e82009-05-19 02:15:55 +0000478 // Order pointer values after integer values. This helps SCEVExpander
479 // form GEPs.
480 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
481 return false;
482 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
483 return true;
484
Dan Gohman72861302009-05-07 14:39:04 +0000485 // Compare getValueID values.
486 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
487 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
488
489 // Sort arguments by their position.
490 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
491 const Argument *RA = cast<Argument>(RU->getValue());
492 return LA->getArgNo() < RA->getArgNo();
493 }
494
495 // For instructions, compare their loop depth, and their opcode.
496 // This is pretty loose.
497 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
498 Instruction *RV = cast<Instruction>(RU->getValue());
499
500 // Compare loop depths.
501 if (LI->getLoopDepth(LV->getParent()) !=
502 LI->getLoopDepth(RV->getParent()))
503 return LI->getLoopDepth(LV->getParent()) <
504 LI->getLoopDepth(RV->getParent());
505
506 // Compare opcodes.
507 if (LV->getOpcode() != RV->getOpcode())
508 return LV->getOpcode() < RV->getOpcode();
509
510 // Compare the number of operands.
511 if (LV->getNumOperands() != RV->getNumOperands())
512 return LV->getNumOperands() < RV->getNumOperands();
513 }
514
515 return false;
516 }
517
Dan Gohman4dfad292009-06-14 22:51:25 +0000518 // Compare constant values.
519 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
520 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
521 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
522 }
523
524 // Compare addrec loop depths.
525 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
526 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
527 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
528 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
529 }
Dan Gohman72861302009-05-07 14:39:04 +0000530
531 // Lexicographically compare n-ary expressions.
532 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
533 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
534 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
535 if (i >= RC->getNumOperands())
536 return false;
537 if (operator()(LC->getOperand(i), RC->getOperand(i)))
538 return true;
539 if (operator()(RC->getOperand(i), LC->getOperand(i)))
540 return false;
541 }
542 return LC->getNumOperands() < RC->getNumOperands();
543 }
544
Dan Gohmana6b35e22009-05-07 19:23:21 +0000545 // Lexicographically compare udiv expressions.
546 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
547 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
548 if (operator()(LC->getLHS(), RC->getLHS()))
549 return true;
550 if (operator()(RC->getLHS(), LC->getLHS()))
551 return false;
552 if (operator()(LC->getRHS(), RC->getRHS()))
553 return true;
554 if (operator()(RC->getRHS(), LC->getRHS()))
555 return false;
556 return false;
557 }
558
Dan Gohman72861302009-05-07 14:39:04 +0000559 // Compare cast expressions by operand.
560 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
561 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
562 return operator()(LC->getOperand(), RC->getOperand());
563 }
564
565 assert(0 && "Unknown SCEV kind!");
566 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000567 }
568 };
569}
570
571/// GroupByComplexity - Given a list of SCEV objects, order them by their
572/// complexity, and group objects of the same complexity together by value.
573/// When this routine is finished, we know that any duplicates in the vector are
574/// consecutive and that complexity is monotonically increasing.
575///
576/// Note that we go take special precautions to ensure that we get determinstic
577/// results from this routine. In other words, we don't want the results of
578/// this to depend on where the addresses of various SCEV objects happened to
579/// land in memory.
580///
Dan Gohmana82752c2009-06-14 22:47:23 +0000581static void GroupByComplexity(SmallVectorImpl<SCEVHandle> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000582 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000583 if (Ops.size() < 2) return; // Noop
584 if (Ops.size() == 2) {
585 // This is the common case, which also happens to be trivially simple.
586 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000587 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000588 std::swap(Ops[0], Ops[1]);
589 return;
590 }
591
592 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000593 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000594
595 // Now that we are sorted by complexity, group elements of the same
596 // complexity. Note that this is, at worst, N^2, but the vector is likely to
597 // be extremely short in practice. Note that we take this approach because we
598 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000599 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000600 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000601 unsigned Complexity = S->getSCEVType();
602
603 // If there are any objects of the same complexity and same value as this
604 // one, group them.
605 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
606 if (Ops[j] == S) { // Found a duplicate.
607 // Move it to immediately after i'th element.
608 std::swap(Ops[i+1], Ops[j]);
609 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000610 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000611 }
612 }
613 }
614}
615
Chris Lattner53e677a2004-04-02 20:23:17 +0000616
Chris Lattner53e677a2004-04-02 20:23:17 +0000617
618//===----------------------------------------------------------------------===//
619// Simple SCEV method implementations
620//===----------------------------------------------------------------------===//
621
Eli Friedmanb42a6262008-08-04 23:49:06 +0000622/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000623/// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000624static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000625 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000626 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000627 // Handle the simplest case efficiently.
628 if (K == 1)
629 return SE.getTruncateOrZeroExtend(It, ResultTy);
630
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000631 // We are using the following formula for BC(It, K):
632 //
633 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
634 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000635 // Suppose, W is the bitwidth of the return value. We must be prepared for
636 // overflow. Hence, we must assure that the result of our computation is
637 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
638 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000639 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000640 // However, this code doesn't use exactly that formula; the formula it uses
641 // is something like the following, where T is the number of factors of 2 in
642 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
643 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000644 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000645 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000646 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000647 // This formula is trivially equivalent to the previous formula. However,
648 // this formula can be implemented much more efficiently. The trick is that
649 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
650 // arithmetic. To do exact division in modular arithmetic, all we have
651 // to do is multiply by the inverse. Therefore, this step can be done at
652 // width W.
653 //
654 // The next issue is how to safely do the division by 2^T. The way this
655 // is done is by doing the multiplication step at a width of at least W + T
656 // bits. This way, the bottom W+T bits of the product are accurate. Then,
657 // when we perform the division by 2^T (which is equivalent to a right shift
658 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
659 // truncated out after the division by 2^T.
660 //
661 // In comparison to just directly using the first formula, this technique
662 // is much more efficient; using the first formula requires W * K bits,
663 // but this formula less than W + K bits. Also, the first formula requires
664 // a division step, whereas this formula only requires multiplies and shifts.
665 //
666 // It doesn't matter whether the subtraction step is done in the calculation
667 // width or the input iteration count's width; if the subtraction overflows,
668 // the result must be zero anyway. We prefer here to do it in the width of
669 // the induction variable because it helps a lot for certain cases; CodeGen
670 // isn't smart enough to ignore the overflow, which leads to much less
671 // efficient code if the width of the subtraction is wider than the native
672 // register width.
673 //
674 // (It's possible to not widen at all by pulling out factors of 2 before
675 // the multiplication; for example, K=2 can be calculated as
676 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
677 // extra arithmetic, so it's not an obvious win, and it gets
678 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000679
Eli Friedmanb42a6262008-08-04 23:49:06 +0000680 // Protection from insane SCEVs; this bound is conservative,
681 // but it probably doesn't matter.
682 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000683 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000684
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000685 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000686
Eli Friedmanb42a6262008-08-04 23:49:06 +0000687 // Calculate K! / 2^T and T; we divide out the factors of two before
688 // multiplying for calculating K! / 2^T to avoid overflow.
689 // Other overflow doesn't matter because we only care about the bottom
690 // W bits of the result.
691 APInt OddFactorial(W, 1);
692 unsigned T = 1;
693 for (unsigned i = 3; i <= K; ++i) {
694 APInt Mult(W, i);
695 unsigned TwoFactors = Mult.countTrailingZeros();
696 T += TwoFactors;
697 Mult = Mult.lshr(TwoFactors);
698 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000699 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000700
Eli Friedmanb42a6262008-08-04 23:49:06 +0000701 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000702 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000703
704 // Calcuate 2^T, at width T+W.
705 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
706
707 // Calculate the multiplicative inverse of K! / 2^T;
708 // this multiplication factor will perform the exact division by
709 // K! / 2^T.
710 APInt Mod = APInt::getSignedMinValue(W+1);
711 APInt MultiplyFactor = OddFactorial.zext(W+1);
712 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
713 MultiplyFactor = MultiplyFactor.trunc(W);
714
715 // Calculate the product, at width T+W
716 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
717 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
718 for (unsigned i = 1; i != K; ++i) {
719 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
720 Dividend = SE.getMulExpr(Dividend,
721 SE.getTruncateOrZeroExtend(S, CalculationTy));
722 }
723
724 // Divide by 2^T
725 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
726
727 // Truncate the result, and divide by K! / 2^T.
728
729 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
730 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000731}
732
Chris Lattner53e677a2004-04-02 20:23:17 +0000733/// evaluateAtIteration - Return the value of this chain of recurrences at
734/// the specified iteration number. We can evaluate this recurrence by
735/// multiplying each element in the chain by the binomial coefficient
736/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
737///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000738/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000739///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000740/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000741///
Dan Gohman246b2562007-10-22 18:31:58 +0000742SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
743 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000744 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000745 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000746 // The computation is correct in the face of overflow provided that the
747 // multiplication is performed _after_ the evaluation of the binomial
748 // coefficient.
Dan Gohman2d1be872009-04-16 03:18:22 +0000749 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000750 if (isa<SCEVCouldNotCompute>(Coeff))
751 return Coeff;
752
753 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000754 }
755 return Result;
756}
757
Chris Lattner53e677a2004-04-02 20:23:17 +0000758//===----------------------------------------------------------------------===//
759// SCEV Expression folder implementations
760//===----------------------------------------------------------------------===//
761
Dan Gohman99243b32009-05-01 16:44:56 +0000762SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
763 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000764 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000765 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000766 assert(isSCEVable(Ty) &&
767 "This is not a conversion to a SCEVable type!");
768 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000769
Dan Gohman622ed672009-05-04 22:02:23 +0000770 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000771 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000772 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000773
Dan Gohman20900ca2009-04-22 16:20:48 +0000774 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000775 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000776 return getTruncateExpr(ST->getOperand(), Ty);
777
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000778 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000779 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000780 return getTruncateOrSignExtend(SS->getOperand(), Ty);
781
782 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000783 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000784 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
785
Dan Gohman6864db62009-06-18 16:24:47 +0000786 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000787 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000788 SmallVector<SCEVHandle, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000789 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000790 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
791 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000792 }
793
Chris Lattnerb3364092006-10-04 21:49:37 +0000794 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000795 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty, this);
Chris Lattner53e677a2004-04-02 20:23:17 +0000796 return Result;
797}
798
Dan Gohman8170a682009-04-16 19:25:55 +0000799SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
800 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000801 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000802 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000803 assert(isSCEVable(Ty) &&
804 "This is not a conversion to a SCEVable type!");
805 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000806
Dan Gohman622ed672009-05-04 22:02:23 +0000807 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000808 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000809 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
810 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
811 return getUnknown(C);
812 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000813
Dan Gohman20900ca2009-04-22 16:20:48 +0000814 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000815 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000816 return getZeroExtendExpr(SZ->getOperand(), Ty);
817
Dan Gohman01ecca22009-04-27 20:16:15 +0000818 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000819 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000820 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000821 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000822 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000823 if (AR->isAffine()) {
824 // Check whether the backedge-taken count is SCEVCouldNotCompute.
825 // Note that this serves two purposes: It filters out loops that are
826 // simply not analyzable, and it covers the case where this code is
827 // being called from within backedge-taken count analysis, such that
828 // attempting to ask for the backedge-taken count would likely result
829 // in infinite recursion. In the later case, the analysis code will
830 // cope with a conservative value, and it will take care to purge
831 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000832 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
833 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000834 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000835 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000836 SCEVHandle Start = AR->getStart();
837 SCEVHandle Step = AR->getStepRecurrence(*this);
838
839 // Check whether the backedge-taken count can be losslessly casted to
840 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000841 SCEVHandle CastedMaxBECount =
842 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman5183cae2009-05-18 15:58:39 +0000843 SCEVHandle RecastedMaxBECount =
844 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
845 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000846 const Type *WideTy =
847 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000848 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000849 SCEVHandle ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000850 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000851 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000852 SCEVHandle Add = getAddExpr(Start, ZMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000853 SCEVHandle OperandExtendedAdd =
854 getAddExpr(getZeroExtendExpr(Start, WideTy),
855 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
856 getZeroExtendExpr(Step, WideTy)));
857 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000858 // Return the expression with the addrec on the outside.
859 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
860 getZeroExtendExpr(Step, Ty),
861 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000862
863 // Similar to above, only this time treat the step value as signed.
864 // This covers loops that count down.
865 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000866 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000867 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000868 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000869 OperandExtendedAdd =
870 getAddExpr(getZeroExtendExpr(Start, WideTy),
871 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
872 getSignExtendExpr(Step, WideTy)));
873 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000874 // Return the expression with the addrec on the outside.
875 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
876 getSignExtendExpr(Step, Ty),
877 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000878 }
879 }
880 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000881
Chris Lattnerb3364092006-10-04 21:49:37 +0000882 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000883 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty, this);
Chris Lattner53e677a2004-04-02 20:23:17 +0000884 return Result;
885}
886
Dan Gohman01ecca22009-04-27 20:16:15 +0000887SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
888 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000889 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000890 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000891 assert(isSCEVable(Ty) &&
892 "This is not a conversion to a SCEVable type!");
893 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000894
Dan Gohman622ed672009-05-04 22:02:23 +0000895 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000896 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000897 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
898 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
899 return getUnknown(C);
900 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000901
Dan Gohman20900ca2009-04-22 16:20:48 +0000902 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000903 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000904 return getSignExtendExpr(SS->getOperand(), Ty);
905
Dan Gohman01ecca22009-04-27 20:16:15 +0000906 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000907 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000908 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000909 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000910 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000911 if (AR->isAffine()) {
912 // Check whether the backedge-taken count is SCEVCouldNotCompute.
913 // Note that this serves two purposes: It filters out loops that are
914 // simply not analyzable, and it covers the case where this code is
915 // being called from within backedge-taken count analysis, such that
916 // attempting to ask for the backedge-taken count would likely result
917 // in infinite recursion. In the later case, the analysis code will
918 // cope with a conservative value, and it will take care to purge
919 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000920 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
921 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000922 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000923 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000924 SCEVHandle Start = AR->getStart();
925 SCEVHandle Step = AR->getStepRecurrence(*this);
926
927 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000928 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000929 SCEVHandle CastedMaxBECount =
930 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman5183cae2009-05-18 15:58:39 +0000931 SCEVHandle RecastedMaxBECount =
932 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
933 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000934 const Type *WideTy =
935 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000936 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000937 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000938 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000939 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000940 SCEVHandle Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000941 SCEVHandle OperandExtendedAdd =
942 getAddExpr(getSignExtendExpr(Start, WideTy),
943 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
944 getSignExtendExpr(Step, WideTy)));
945 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000946 // Return the expression with the addrec on the outside.
947 return getAddRecExpr(getSignExtendExpr(Start, Ty),
948 getSignExtendExpr(Step, Ty),
949 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000950 }
951 }
952 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000953
954 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000955 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty, this);
Dan Gohmand19534a2007-06-15 14:38:12 +0000956 return Result;
957}
958
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000959/// getAnyExtendExpr - Return a SCEV for the given operand extended with
960/// unspecified bits out to the given type.
961///
962SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
963 const Type *Ty) {
964 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
965 "This is not an extending conversion!");
966 assert(isSCEVable(Ty) &&
967 "This is not a conversion to a SCEVable type!");
968 Ty = getEffectiveSCEVType(Ty);
969
970 // Sign-extend negative constants.
971 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
972 if (SC->getValue()->getValue().isNegative())
973 return getSignExtendExpr(Op, Ty);
974
975 // Peel off a truncate cast.
976 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
977 SCEVHandle NewOp = T->getOperand();
978 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
979 return getAnyExtendExpr(NewOp, Ty);
980 return getTruncateOrNoop(NewOp, Ty);
981 }
982
983 // Next try a zext cast. If the cast is folded, use it.
984 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
985 if (!isa<SCEVZeroExtendExpr>(ZExt))
986 return ZExt;
987
988 // Next try a sext cast. If the cast is folded, use it.
989 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
990 if (!isa<SCEVSignExtendExpr>(SExt))
991 return SExt;
992
993 // If the expression is obviously signed, use the sext cast value.
994 if (isa<SCEVSMaxExpr>(Op))
995 return SExt;
996
997 // Absent any other information, use the zext cast value.
998 return ZExt;
999}
1000
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001001/// CollectAddOperandsWithScales - Process the given Ops list, which is
1002/// a list of operands to be added under the given scale, update the given
1003/// map. This is a helper function for getAddRecExpr. As an example of
1004/// what it does, given a sequence of operands that would form an add
1005/// expression like this:
1006///
1007/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1008///
1009/// where A and B are constants, update the map with these values:
1010///
1011/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1012///
1013/// and add 13 + A*B*29 to AccumulatedConstant.
1014/// This will allow getAddRecExpr to produce this:
1015///
1016/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1017///
1018/// This form often exposes folding opportunities that are hidden in
1019/// the original operand list.
1020///
1021/// Return true iff it appears that any interesting folding opportunities
1022/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1023/// the common case where no interesting opportunities are present, and
1024/// is also used as a check to avoid infinite recursion.
1025///
1026static bool
1027CollectAddOperandsWithScales(DenseMap<SCEVHandle, APInt> &M,
1028 SmallVector<SCEVHandle, 8> &NewOps,
1029 APInt &AccumulatedConstant,
1030 const SmallVectorImpl<SCEVHandle> &Ops,
1031 const APInt &Scale,
1032 ScalarEvolution &SE) {
1033 bool Interesting = false;
1034
1035 // Iterate over the add operands.
1036 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1037 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1038 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1039 APInt NewScale =
1040 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1041 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1042 // A multiplication of a constant with another add; recurse.
1043 Interesting |=
1044 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1045 cast<SCEVAddExpr>(Mul->getOperand(1))
1046 ->getOperands(),
1047 NewScale, SE);
1048 } else {
1049 // A multiplication of a constant with some other value. Update
1050 // the map.
1051 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1052 SCEVHandle Key = SE.getMulExpr(MulOps);
1053 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1054 M.insert(std::make_pair(Key, APInt()));
1055 if (Pair.second) {
1056 Pair.first->second = NewScale;
1057 NewOps.push_back(Pair.first->first);
1058 } else {
1059 Pair.first->second += NewScale;
1060 // The map already had an entry for this value, which may indicate
1061 // a folding opportunity.
1062 Interesting = true;
1063 }
1064 }
1065 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1066 // Pull a buried constant out to the outside.
1067 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1068 Interesting = true;
1069 AccumulatedConstant += Scale * C->getValue()->getValue();
1070 } else {
1071 // An ordinary operand. Update the map.
1072 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1073 M.insert(std::make_pair(Ops[i], APInt()));
1074 if (Pair.second) {
1075 Pair.first->second = Scale;
1076 NewOps.push_back(Pair.first->first);
1077 } else {
1078 Pair.first->second += Scale;
1079 // The map already had an entry for this value, which may indicate
1080 // a folding opportunity.
1081 Interesting = true;
1082 }
1083 }
1084 }
1085
1086 return Interesting;
1087}
1088
1089namespace {
1090 struct APIntCompare {
1091 bool operator()(const APInt &LHS, const APInt &RHS) const {
1092 return LHS.ult(RHS);
1093 }
1094 };
1095}
1096
Dan Gohman6c0866c2009-05-24 23:45:28 +00001097/// getAddExpr - Get a canonical add expression, or something simpler if
1098/// possible.
Dan Gohmana82752c2009-06-14 22:47:23 +00001099SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001100 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001101 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001102#ifndef NDEBUG
1103 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1104 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1105 getEffectiveSCEVType(Ops[0]->getType()) &&
1106 "SCEVAddExpr operand types don't match!");
1107#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001108
1109 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001110 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001111
1112 // If there are any constants, fold them together.
1113 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001114 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001115 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001116 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001117 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001118 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001119 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1120 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001121 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001122 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001123 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001124 }
1125
1126 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001127 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001128 Ops.erase(Ops.begin());
1129 --Idx;
1130 }
1131 }
1132
Chris Lattner627018b2004-04-07 16:16:11 +00001133 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001134
Chris Lattner53e677a2004-04-02 20:23:17 +00001135 // Okay, check to see if the same value occurs in the operand list twice. If
1136 // so, merge them together into an multiply expression. Since we sorted the
1137 // list, these values are required to be adjacent.
1138 const Type *Ty = Ops[0]->getType();
1139 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1140 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1141 // Found a match, merge the two values into a multiply, and add any
1142 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +00001143 SCEVHandle Two = getIntegerSCEV(2, Ty);
1144 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001145 if (Ops.size() == 2)
1146 return Mul;
1147 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1148 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001149 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001150 }
1151
Dan Gohman728c7f32009-05-08 21:03:19 +00001152 // Check for truncates. If all the operands are truncated from the same
1153 // type, see if factoring out the truncate would permit the result to be
1154 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1155 // if the contents of the resulting outer trunc fold to something simple.
1156 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1157 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1158 const Type *DstType = Trunc->getType();
1159 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmana82752c2009-06-14 22:47:23 +00001160 SmallVector<SCEVHandle, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001161 bool Ok = true;
1162 // Check all the operands to see if they can be represented in the
1163 // source type of the truncate.
1164 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1165 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1166 if (T->getOperand()->getType() != SrcType) {
1167 Ok = false;
1168 break;
1169 }
1170 LargeOps.push_back(T->getOperand());
1171 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1172 // This could be either sign or zero extension, but sign extension
1173 // is much more likely to be foldable here.
1174 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1175 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001176 SmallVector<SCEVHandle, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001177 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1178 if (const SCEVTruncateExpr *T =
1179 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1180 if (T->getOperand()->getType() != SrcType) {
1181 Ok = false;
1182 break;
1183 }
1184 LargeMulOps.push_back(T->getOperand());
1185 } else if (const SCEVConstant *C =
1186 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1187 // This could be either sign or zero extension, but sign extension
1188 // is much more likely to be foldable here.
1189 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1190 } else {
1191 Ok = false;
1192 break;
1193 }
1194 }
1195 if (Ok)
1196 LargeOps.push_back(getMulExpr(LargeMulOps));
1197 } else {
1198 Ok = false;
1199 break;
1200 }
1201 }
1202 if (Ok) {
1203 // Evaluate the expression in the larger type.
1204 SCEVHandle Fold = getAddExpr(LargeOps);
1205 // If it folds to something simple, use it. Otherwise, don't.
1206 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1207 return getTruncateExpr(Fold, DstType);
1208 }
1209 }
1210
1211 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001212 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1213 ++Idx;
1214
1215 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001216 if (Idx < Ops.size()) {
1217 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001218 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001219 // If we have an add, expand the add operands onto the end of the operands
1220 // list.
1221 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1222 Ops.erase(Ops.begin()+Idx);
1223 DeletedAdd = true;
1224 }
1225
1226 // If we deleted at least one add, we added operands to the end of the list,
1227 // and they are not necessarily sorted. Recurse to resort and resimplify
1228 // any operands we just aquired.
1229 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001230 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001231 }
1232
1233 // Skip over the add expression until we get to a multiply.
1234 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1235 ++Idx;
1236
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001237 // Check to see if there are any folding opportunities present with
1238 // operands multiplied by constant values.
1239 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1240 uint64_t BitWidth = getTypeSizeInBits(Ty);
1241 DenseMap<SCEVHandle, APInt> M;
1242 SmallVector<SCEVHandle, 8> NewOps;
1243 APInt AccumulatedConstant(BitWidth, 0);
1244 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1245 Ops, APInt(BitWidth, 1), *this)) {
1246 // Some interesting folding opportunity is present, so its worthwhile to
1247 // re-generate the operands list. Group the operands by constant scale,
1248 // to avoid multiplying by the same constant scale multiple times.
1249 std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare> MulOpLists;
1250 for (SmallVector<SCEVHandle, 8>::iterator I = NewOps.begin(),
1251 E = NewOps.end(); I != E; ++I)
1252 MulOpLists[M.find(*I)->second].push_back(*I);
1253 // Re-generate the operands list.
1254 Ops.clear();
1255 if (AccumulatedConstant != 0)
1256 Ops.push_back(getConstant(AccumulatedConstant));
1257 for (std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare>::iterator I =
1258 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1259 if (I->first != 0)
1260 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1261 if (Ops.empty())
1262 return getIntegerSCEV(0, Ty);
1263 if (Ops.size() == 1)
1264 return Ops[0];
1265 return getAddExpr(Ops);
1266 }
1267 }
1268
Chris Lattner53e677a2004-04-02 20:23:17 +00001269 // If we are adding something to a multiply expression, make sure the
1270 // something is not already an operand of the multiply. If so, merge it into
1271 // the multiply.
1272 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001273 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001274 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001275 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001276 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001277 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001278 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1279 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1280 if (Mul->getNumOperands() != 2) {
1281 // If the multiply has more than two operands, we must get the
1282 // Y*Z term.
Dan Gohmana82752c2009-06-14 22:47:23 +00001283 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001284 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001285 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001286 }
Dan Gohman246b2562007-10-22 18:31:58 +00001287 SCEVHandle One = getIntegerSCEV(1, Ty);
1288 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1289 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001290 if (Ops.size() == 2) return OuterMul;
1291 if (AddOp < Idx) {
1292 Ops.erase(Ops.begin()+AddOp);
1293 Ops.erase(Ops.begin()+Idx-1);
1294 } else {
1295 Ops.erase(Ops.begin()+Idx);
1296 Ops.erase(Ops.begin()+AddOp-1);
1297 }
1298 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001299 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001300 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001301
Chris Lattner53e677a2004-04-02 20:23:17 +00001302 // Check this multiply against other multiplies being added together.
1303 for (unsigned OtherMulIdx = Idx+1;
1304 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1305 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001306 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001307 // If MulOp occurs in OtherMul, we can fold the two multiplies
1308 // together.
1309 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1310 OMulOp != e; ++OMulOp)
1311 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1312 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1313 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1314 if (Mul->getNumOperands() != 2) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001315 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001316 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001317 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001318 }
1319 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1320 if (OtherMul->getNumOperands() != 2) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001321 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001322 OtherMul->op_end());
1323 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001324 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001325 }
Dan Gohman246b2562007-10-22 18:31:58 +00001326 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1327 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001328 if (Ops.size() == 2) return OuterMul;
1329 Ops.erase(Ops.begin()+Idx);
1330 Ops.erase(Ops.begin()+OtherMulIdx-1);
1331 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001332 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001333 }
1334 }
1335 }
1336 }
1337
1338 // If there are any add recurrences in the operands list, see if any other
1339 // added values are loop invariant. If so, we can fold them into the
1340 // recurrence.
1341 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1342 ++Idx;
1343
1344 // Scan over all recurrences, trying to fold loop invariants into them.
1345 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1346 // Scan all of the other operands to this add and add them to the vector if
1347 // they are loop invariant w.r.t. the recurrence.
Dan Gohmana82752c2009-06-14 22:47:23 +00001348 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001349 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001350 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1351 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1352 LIOps.push_back(Ops[i]);
1353 Ops.erase(Ops.begin()+i);
1354 --i; --e;
1355 }
1356
1357 // If we found some loop invariants, fold them into the recurrence.
1358 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001359 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 LIOps.push_back(AddRec->getStart());
1361
Dan Gohmana82752c2009-06-14 22:47:23 +00001362 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1363 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001364 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001365
Dan Gohman246b2562007-10-22 18:31:58 +00001366 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001367 // If all of the other operands were loop invariant, we are done.
1368 if (Ops.size() == 1) return NewRec;
1369
1370 // Otherwise, add the folded AddRec by the non-liv parts.
1371 for (unsigned i = 0;; ++i)
1372 if (Ops[i] == AddRec) {
1373 Ops[i] = NewRec;
1374 break;
1375 }
Dan Gohman246b2562007-10-22 18:31:58 +00001376 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001377 }
1378
1379 // Okay, if there weren't any loop invariants to be folded, check to see if
1380 // there are multiple AddRec's with the same loop induction variable being
1381 // added together. If so, we can fold them.
1382 for (unsigned OtherIdx = Idx+1;
1383 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1384 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001385 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001386 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1387 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohmana82752c2009-06-14 22:47:23 +00001388 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001389 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1390 if (i >= NewOps.size()) {
1391 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1392 OtherAddRec->op_end());
1393 break;
1394 }
Dan Gohman246b2562007-10-22 18:31:58 +00001395 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 }
Dan Gohman246b2562007-10-22 18:31:58 +00001397 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001398
1399 if (Ops.size() == 2) return NewAddRec;
1400
1401 Ops.erase(Ops.begin()+Idx);
1402 Ops.erase(Ops.begin()+OtherIdx-1);
1403 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001404 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001405 }
1406 }
1407
1408 // Otherwise couldn't fold anything into this recurrence. Move onto the
1409 // next one.
1410 }
1411
1412 // Okay, it looks like we really DO need an add expr. Check to see if we
1413 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001414 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001415 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1416 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001417 if (Result == 0) Result = new SCEVAddExpr(Ops, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001418 return Result;
1419}
1420
1421
Dan Gohman6c0866c2009-05-24 23:45:28 +00001422/// getMulExpr - Get a canonical multiply expression, or something simpler if
1423/// possible.
Dan Gohmana82752c2009-06-14 22:47:23 +00001424SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001425 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001426#ifndef NDEBUG
1427 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1428 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1429 getEffectiveSCEVType(Ops[0]->getType()) &&
1430 "SCEVMulExpr operand types don't match!");
1431#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001432
1433 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001434 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001435
1436 // If there are any constants, fold them together.
1437 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001438 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001439
1440 // C1*(C2+V) -> C1*C2 + C1*V
1441 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001442 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001443 if (Add->getNumOperands() == 2 &&
1444 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001445 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1446 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001447
1448
1449 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001450 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001451 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001452 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1453 RHSC->getValue()->getValue());
1454 Ops[0] = getConstant(Fold);
1455 Ops.erase(Ops.begin()+1); // Erase the folded element
1456 if (Ops.size() == 1) return Ops[0];
1457 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001458 }
1459
1460 // If we are left with a constant one being multiplied, strip it off.
1461 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1462 Ops.erase(Ops.begin());
1463 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001464 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 // If we have a multiply of zero, it will always be zero.
1466 return Ops[0];
1467 }
1468 }
1469
1470 // Skip over the add expression until we get to a multiply.
1471 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1472 ++Idx;
1473
1474 if (Ops.size() == 1)
1475 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001476
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 // If there are mul operands inline them all into this expression.
1478 if (Idx < Ops.size()) {
1479 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001480 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001481 // If we have an mul, expand the mul operands onto the end of the operands
1482 // list.
1483 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1484 Ops.erase(Ops.begin()+Idx);
1485 DeletedMul = true;
1486 }
1487
1488 // If we deleted at least one mul, we added operands to the end of the list,
1489 // and they are not necessarily sorted. Recurse to resort and resimplify
1490 // any operands we just aquired.
1491 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001492 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 }
1494
1495 // If there are any add recurrences in the operands list, see if any other
1496 // added values are loop invariant. If so, we can fold them into the
1497 // recurrence.
1498 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1499 ++Idx;
1500
1501 // Scan over all recurrences, trying to fold loop invariants into them.
1502 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1503 // Scan all of the other operands to this mul and add them to the vector if
1504 // they are loop invariant w.r.t. the recurrence.
Dan Gohmana82752c2009-06-14 22:47:23 +00001505 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001506 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001507 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1508 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1509 LIOps.push_back(Ops[i]);
1510 Ops.erase(Ops.begin()+i);
1511 --i; --e;
1512 }
1513
1514 // If we found some loop invariants, fold them into the recurrence.
1515 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001516 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmana82752c2009-06-14 22:47:23 +00001517 SmallVector<SCEVHandle, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001518 NewOps.reserve(AddRec->getNumOperands());
1519 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001520 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001521 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001522 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001523 } else {
1524 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001525 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001526 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001527 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001528 }
1529 }
1530
Dan Gohman246b2562007-10-22 18:31:58 +00001531 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001532
1533 // If all of the other operands were loop invariant, we are done.
1534 if (Ops.size() == 1) return NewRec;
1535
1536 // Otherwise, multiply the folded AddRec by the non-liv parts.
1537 for (unsigned i = 0;; ++i)
1538 if (Ops[i] == AddRec) {
1539 Ops[i] = NewRec;
1540 break;
1541 }
Dan Gohman246b2562007-10-22 18:31:58 +00001542 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001543 }
1544
1545 // Okay, if there weren't any loop invariants to be folded, check to see if
1546 // there are multiple AddRec's with the same loop induction variable being
1547 // multiplied together. If so, we can fold them.
1548 for (unsigned OtherIdx = Idx+1;
1549 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1550 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001551 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001552 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1553 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001554 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001555 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001556 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001557 SCEVHandle B = F->getStepRecurrence(*this);
1558 SCEVHandle D = G->getStepRecurrence(*this);
1559 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1560 getMulExpr(G, B),
1561 getMulExpr(B, D));
1562 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1563 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001564 if (Ops.size() == 2) return NewAddRec;
1565
1566 Ops.erase(Ops.begin()+Idx);
1567 Ops.erase(Ops.begin()+OtherIdx-1);
1568 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001569 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001570 }
1571 }
1572
1573 // Otherwise couldn't fold anything into this recurrence. Move onto the
1574 // next one.
1575 }
1576
1577 // Okay, it looks like we really DO need an mul expr. Check to see if we
1578 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001579 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001580 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1581 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001582 if (Result == 0)
Owen Anderson4a7893b2009-06-18 22:25:12 +00001583 Result = new SCEVMulExpr(Ops, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001584 return Result;
1585}
1586
Dan Gohman6c0866c2009-05-24 23:45:28 +00001587/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1588/// possible.
Dan Gohmanbf2176a2009-05-04 22:23:18 +00001589SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1590 const SCEVHandle &RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001591 assert(getEffectiveSCEVType(LHS->getType()) ==
1592 getEffectiveSCEVType(RHS->getType()) &&
1593 "SCEVUDivExpr operand types don't match!");
1594
Dan Gohman622ed672009-05-04 22:02:23 +00001595 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001596 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001597 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001598 if (RHSC->isZero())
1599 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001600
Dan Gohman185cf032009-05-08 20:18:49 +00001601 // Determine if the division can be folded into the operands of
1602 // its operands.
1603 // TODO: Generalize this to non-constants by using known-bits information.
1604 const Type *Ty = LHS->getType();
1605 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1606 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1607 // For non-power-of-two values, effectively round the value up to the
1608 // nearest power of two.
1609 if (!RHSC->getValue()->getValue().isPowerOf2())
1610 ++MaxShiftAmt;
1611 const IntegerType *ExtTy =
1612 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1613 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1614 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1615 if (const SCEVConstant *Step =
1616 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1617 if (!Step->getValue()->getValue()
1618 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001619 getZeroExtendExpr(AR, ExtTy) ==
1620 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1621 getZeroExtendExpr(Step, ExtTy),
1622 AR->getLoop())) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001623 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001624 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1625 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1626 return getAddRecExpr(Operands, AR->getLoop());
1627 }
1628 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001629 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001630 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001631 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1632 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1633 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001634 // Find an operand that's safely divisible.
1635 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1636 SCEVHandle Op = M->getOperand(i);
1637 SCEVHandle Div = getUDivExpr(Op, RHSC);
1638 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001639 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1640 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1641 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001642 Operands[i] = Div;
1643 return getMulExpr(Operands);
1644 }
1645 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001646 }
Dan Gohman185cf032009-05-08 20:18:49 +00001647 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001648 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001649 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001650 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1651 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1652 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1653 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001654 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1655 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1656 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1657 break;
1658 Operands.push_back(Op);
1659 }
1660 if (Operands.size() == A->getNumOperands())
1661 return getAddExpr(Operands);
1662 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001663 }
Dan Gohman185cf032009-05-08 20:18:49 +00001664
1665 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001666 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001667 Constant *LHSCV = LHSC->getValue();
1668 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001669 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001670 }
1671 }
1672
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001673 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001674 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001675 return Result;
1676}
1677
1678
Dan Gohman6c0866c2009-05-24 23:45:28 +00001679/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1680/// Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001681SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 const SCEVHandle &Step, const Loop *L) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001683 SmallVector<SCEVHandle, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001684 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001685 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001686 if (StepChrec->getLoop() == L) {
1687 Operands.insert(Operands.end(), StepChrec->op_begin(),
1688 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001689 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001690 }
1691
1692 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001693 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001694}
1695
Dan Gohman6c0866c2009-05-24 23:45:28 +00001696/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1697/// Simplify the expression as much as possible.
Dan Gohmana82752c2009-06-14 22:47:23 +00001698SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001699 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001700 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001701#ifndef NDEBUG
1702 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1703 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1704 getEffectiveSCEVType(Operands[0]->getType()) &&
1705 "SCEVAddRecExpr operand types don't match!");
1706#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001707
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001708 if (Operands.back()->isZero()) {
1709 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001710 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001711 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001712
Dan Gohmand9cc7492008-08-08 18:33:12 +00001713 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001714 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001715 const Loop* NestedLoop = NestedAR->getLoop();
1716 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001717 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1718 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001719 SCEVHandle NestedARHandle(NestedAR);
1720 Operands[0] = NestedAR->getStart();
1721 NestedOperands[0] = getAddRecExpr(Operands, L);
1722 return getAddRecExpr(NestedOperands, NestedLoop);
1723 }
1724 }
1725
Dan Gohman35738ac2009-05-04 22:30:44 +00001726 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1727 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001728 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001729 return Result;
1730}
1731
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001732SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1733 const SCEVHandle &RHS) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001734 SmallVector<SCEVHandle, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001735 Ops.push_back(LHS);
1736 Ops.push_back(RHS);
1737 return getSMaxExpr(Ops);
1738}
1739
Dan Gohmana82752c2009-06-14 22:47:23 +00001740SCEVHandle
1741ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001742 assert(!Ops.empty() && "Cannot get empty smax!");
1743 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001744#ifndef NDEBUG
1745 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1746 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1747 getEffectiveSCEVType(Ops[0]->getType()) &&
1748 "SCEVSMaxExpr operand types don't match!");
1749#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001750
1751 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001752 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001753
1754 // If there are any constants, fold them together.
1755 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001756 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001757 ++Idx;
1758 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001759 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001760 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001761 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001762 APIntOps::smax(LHSC->getValue()->getValue(),
1763 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001764 Ops[0] = getConstant(Fold);
1765 Ops.erase(Ops.begin()+1); // Erase the folded element
1766 if (Ops.size() == 1) return Ops[0];
1767 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001768 }
1769
1770 // If we are left with a constant -inf, strip it off.
1771 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1772 Ops.erase(Ops.begin());
1773 --Idx;
1774 }
1775 }
1776
1777 if (Ops.size() == 1) return Ops[0];
1778
1779 // Find the first SMax
1780 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1781 ++Idx;
1782
1783 // Check to see if one of the operands is an SMax. If so, expand its operands
1784 // onto our operand list, and recurse to simplify.
1785 if (Idx < Ops.size()) {
1786 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001787 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001788 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1789 Ops.erase(Ops.begin()+Idx);
1790 DeletedSMax = true;
1791 }
1792
1793 if (DeletedSMax)
1794 return getSMaxExpr(Ops);
1795 }
1796
1797 // Okay, check to see if the same value occurs in the operand list twice. If
1798 // so, delete one. Since we sorted the list, these values are required to
1799 // be adjacent.
1800 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1801 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1802 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1803 --i; --e;
1804 }
1805
1806 if (Ops.size() == 1) return Ops[0];
1807
1808 assert(!Ops.empty() && "Reduced smax down to nothing!");
1809
Nick Lewycky3e630762008-02-20 06:48:22 +00001810 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001811 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001812 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001813 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1814 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001815 if (Result == 0) Result = new SCEVSMaxExpr(Ops, this);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001816 return Result;
1817}
1818
Nick Lewycky3e630762008-02-20 06:48:22 +00001819SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1820 const SCEVHandle &RHS) {
Dan Gohmana82752c2009-06-14 22:47:23 +00001821 SmallVector<SCEVHandle, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001822 Ops.push_back(LHS);
1823 Ops.push_back(RHS);
1824 return getUMaxExpr(Ops);
1825}
1826
Dan Gohmana82752c2009-06-14 22:47:23 +00001827SCEVHandle
1828ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001829 assert(!Ops.empty() && "Cannot get empty umax!");
1830 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001831#ifndef NDEBUG
1832 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1833 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1834 getEffectiveSCEVType(Ops[0]->getType()) &&
1835 "SCEVUMaxExpr operand types don't match!");
1836#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001837
1838 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001839 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001840
1841 // If there are any constants, fold them together.
1842 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001843 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001844 ++Idx;
1845 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001846 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001847 // We found two constants, fold them together!
1848 ConstantInt *Fold = ConstantInt::get(
1849 APIntOps::umax(LHSC->getValue()->getValue(),
1850 RHSC->getValue()->getValue()));
1851 Ops[0] = getConstant(Fold);
1852 Ops.erase(Ops.begin()+1); // Erase the folded element
1853 if (Ops.size() == 1) return Ops[0];
1854 LHSC = cast<SCEVConstant>(Ops[0]);
1855 }
1856
1857 // If we are left with a constant zero, strip it off.
1858 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1859 Ops.erase(Ops.begin());
1860 --Idx;
1861 }
1862 }
1863
1864 if (Ops.size() == 1) return Ops[0];
1865
1866 // Find the first UMax
1867 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1868 ++Idx;
1869
1870 // Check to see if one of the operands is a UMax. If so, expand its operands
1871 // onto our operand list, and recurse to simplify.
1872 if (Idx < Ops.size()) {
1873 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001874 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001875 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1876 Ops.erase(Ops.begin()+Idx);
1877 DeletedUMax = true;
1878 }
1879
1880 if (DeletedUMax)
1881 return getUMaxExpr(Ops);
1882 }
1883
1884 // Okay, check to see if the same value occurs in the operand list twice. If
1885 // so, delete one. Since we sorted the list, these values are required to
1886 // be adjacent.
1887 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1888 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1889 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1890 --i; --e;
1891 }
1892
1893 if (Ops.size() == 1) return Ops[0];
1894
1895 assert(!Ops.empty() && "Reduced umax down to nothing!");
1896
1897 // Okay, it looks like we really DO need a umax expr. Check to see if we
1898 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001899 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky3e630762008-02-20 06:48:22 +00001900 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1901 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001902 if (Result == 0) Result = new SCEVUMaxExpr(Ops, this);
Nick Lewycky3e630762008-02-20 06:48:22 +00001903 return Result;
1904}
1905
Dan Gohman246b2562007-10-22 18:31:58 +00001906SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001907 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001908 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001909 if (isa<ConstantPointerNull>(V))
1910 return getIntegerSCEV(0, V->getType());
Chris Lattnerb3364092006-10-04 21:49:37 +00001911 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001912 if (Result == 0) Result = new SCEVUnknown(V, this);
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001913 return Result;
1914}
1915
Chris Lattner53e677a2004-04-02 20:23:17 +00001916//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001917// Basic SCEV Analysis and PHI Idiom Recognition Code
1918//
1919
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001920/// isSCEVable - Test if values of the given type are analyzable within
1921/// the SCEV framework. This primarily includes integer types, and it
1922/// can optionally include pointer types if the ScalarEvolution class
1923/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001924bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001925 // Integers are always SCEVable.
1926 if (Ty->isInteger())
1927 return true;
1928
1929 // Pointers are SCEVable if TargetData information is available
1930 // to provide pointer size information.
1931 if (isa<PointerType>(Ty))
1932 return TD != NULL;
1933
1934 // Otherwise it's not SCEVable.
1935 return false;
1936}
1937
1938/// getTypeSizeInBits - Return the size in bits of the specified type,
1939/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001940uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001941 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1942
1943 // If we have a TargetData, use it!
1944 if (TD)
1945 return TD->getTypeSizeInBits(Ty);
1946
1947 // Otherwise, we support only integer types.
1948 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1949 return Ty->getPrimitiveSizeInBits();
1950}
1951
1952/// getEffectiveSCEVType - Return a type with the same bitwidth as
1953/// the given type and which represents how SCEV will treat the given
1954/// type, for which isSCEVable must return true. For pointer types,
1955/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001956const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001957 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1958
1959 if (Ty->isInteger())
1960 return Ty;
1961
1962 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1963 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001964}
Chris Lattner53e677a2004-04-02 20:23:17 +00001965
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001966SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00001967 return CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001968}
1969
Dan Gohman92fa56e2009-05-04 22:20:30 +00001970/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00001971/// computed.
1972bool ScalarEvolution::hasSCEV(Value *V) const {
1973 return Scalars.count(V);
1974}
1975
Chris Lattner53e677a2004-04-02 20:23:17 +00001976/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1977/// expression and create a new one.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001978SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001979 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001980
Dan Gohman35738ac2009-05-04 22:30:44 +00001981 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001982 if (I != Scalars.end()) return I->second;
1983 SCEVHandle S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00001984 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00001985 return S;
1986}
1987
Dan Gohman2d1be872009-04-16 03:18:22 +00001988/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1989/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001990SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1991 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001992 Constant *C;
1993 if (Val == 0)
1994 C = Constant::getNullValue(Ty);
1995 else if (Ty->isFloatingPoint())
1996 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1997 APFloat::IEEEdouble, Val));
1998 else
1999 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002000 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00002001}
2002
2003/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2004///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002005SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002006 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002007 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00002008
2009 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002010 Ty = getEffectiveSCEVType(Ty);
2011 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002012}
2013
2014/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002015SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002016 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002017 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00002018
2019 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002020 Ty = getEffectiveSCEVType(Ty);
2021 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00002022 return getMinusSCEV(AllOnes, V);
2023}
2024
2025/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2026///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002027SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002028 const SCEVHandle &RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002029 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002030 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002031}
2032
2033/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2034/// input value to the specified type. If the type must be extended, it is zero
2035/// extended.
2036SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002037ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002038 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002039 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002040 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2041 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002042 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002043 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002044 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002045 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002046 return getTruncateExpr(V, Ty);
2047 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002048}
2049
2050/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2051/// input value to the specified type. If the type must be extended, it is sign
2052/// extended.
2053SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002054ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002055 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002056 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002057 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2058 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002059 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002060 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002061 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002062 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002063 return getTruncateExpr(V, Ty);
2064 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002065}
2066
Dan Gohman467c4302009-05-13 03:46:30 +00002067/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2068/// input value to the specified type. If the type must be extended, it is zero
2069/// extended. The conversion must not be narrowing.
2070SCEVHandle
2071ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
2072 const Type *SrcTy = V->getType();
2073 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2074 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2075 "Cannot noop or zero extend with non-integer arguments!");
2076 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2077 "getNoopOrZeroExtend cannot truncate!");
2078 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2079 return V; // No conversion
2080 return getZeroExtendExpr(V, Ty);
2081}
2082
2083/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2084/// input value to the specified type. If the type must be extended, it is sign
2085/// extended. The conversion must not be narrowing.
2086SCEVHandle
2087ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
2088 const Type *SrcTy = V->getType();
2089 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2090 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2091 "Cannot noop or sign extend with non-integer arguments!");
2092 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2093 "getNoopOrSignExtend cannot truncate!");
2094 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2095 return V; // No conversion
2096 return getSignExtendExpr(V, Ty);
2097}
2098
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002099/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2100/// the input value to the specified type. If the type must be extended,
2101/// it is extended with unspecified bits. The conversion must not be
2102/// narrowing.
2103SCEVHandle
2104ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
2105 const Type *SrcTy = V->getType();
2106 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2107 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2108 "Cannot noop or any extend with non-integer arguments!");
2109 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2110 "getNoopOrAnyExtend cannot truncate!");
2111 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2112 return V; // No conversion
2113 return getAnyExtendExpr(V, Ty);
2114}
2115
Dan Gohman467c4302009-05-13 03:46:30 +00002116/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2117/// input value to the specified type. The conversion must not be widening.
2118SCEVHandle
2119ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
2120 const Type *SrcTy = V->getType();
2121 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2122 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2123 "Cannot truncate or noop with non-integer arguments!");
2124 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2125 "getTruncateOrNoop cannot extend!");
2126 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2127 return V; // No conversion
2128 return getTruncateExpr(V, Ty);
2129}
2130
Chris Lattner4dc534c2005-02-13 04:37:18 +00002131/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2132/// the specified instruction and replaces any references to the symbolic value
2133/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002134void ScalarEvolution::
Chris Lattner4dc534c2005-02-13 04:37:18 +00002135ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
2136 const SCEVHandle &NewVal) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002137 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2138 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002139 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002140
Chris Lattner4dc534c2005-02-13 04:37:18 +00002141 SCEVHandle NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002142 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002143 if (NV == SI->second) return; // No change.
2144
2145 SI->second = NV; // Update the scalars map!
2146
2147 // Any instruction values that use this instruction might also need to be
2148 // updated!
2149 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2150 UI != E; ++UI)
2151 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2152}
Chris Lattner53e677a2004-04-02 20:23:17 +00002153
2154/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2155/// a loop header, making it a potential recurrence, or it doesn't.
2156///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002157SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002158 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002159 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002160 if (L->getHeader() == PN->getParent()) {
2161 // If it lives in the loop header, it has two incoming values, one
2162 // from outside the loop, and one from inside.
2163 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2164 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002165
Chris Lattner53e677a2004-04-02 20:23:17 +00002166 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002167 SCEVHandle SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002168 assert(Scalars.find(PN) == Scalars.end() &&
2169 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002170 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002171
2172 // Using this symbolic name for the PHI, analyze the value coming around
2173 // the back-edge.
2174 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2175
2176 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2177 // has a special value for the first iteration of the loop.
2178
2179 // If the value coming around the backedge is an add with the symbolic
2180 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002181 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002182 // If there is a single occurrence of the symbolic value, replace it
2183 // with a recurrence.
2184 unsigned FoundIndex = Add->getNumOperands();
2185 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2186 if (Add->getOperand(i) == SymbolicName)
2187 if (FoundIndex == e) {
2188 FoundIndex = i;
2189 break;
2190 }
2191
2192 if (FoundIndex != Add->getNumOperands()) {
2193 // Create an add with everything but the specified operand.
Dan Gohmana82752c2009-06-14 22:47:23 +00002194 SmallVector<SCEVHandle, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002195 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2196 if (i != FoundIndex)
2197 Ops.push_back(Add->getOperand(i));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002198 SCEVHandle Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002199
2200 // This is not a valid addrec if the step amount is varying each
2201 // loop iteration, but is not itself an addrec in this loop.
2202 if (Accum->isLoopInvariant(L) ||
2203 (isa<SCEVAddRecExpr>(Accum) &&
2204 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2205 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002206 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002207
2208 // Okay, for the entire analysis of this edge we assumed the PHI
2209 // to be symbolic. We now need to go back and update all of the
2210 // entries for the scalars that use the PHI (except for the PHI
2211 // itself) to use the new analyzed value instead of the "symbolic"
2212 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002213 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002214 return PHISCEV;
2215 }
2216 }
Dan Gohman622ed672009-05-04 22:02:23 +00002217 } else if (const SCEVAddRecExpr *AddRec =
2218 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002219 // Otherwise, this could be a loop like this:
2220 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2221 // In this case, j = {1,+,1} and BEValue is j.
2222 // Because the other in-value of i (0) fits the evolution of BEValue
2223 // i really is an addrec evolution.
2224 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2225 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2226
2227 // If StartVal = j.start - j.stride, we can use StartVal as the
2228 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002229 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002230 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00002231 SCEVHandle PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002232 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002233
2234 // Okay, for the entire analysis of this edge we assumed the PHI
2235 // to be symbolic. We now need to go back and update all of the
2236 // entries for the scalars that use the PHI (except for the PHI
2237 // itself) to use the new analyzed value instead of the "symbolic"
2238 // value.
2239 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2240 return PHISCEV;
2241 }
2242 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002243 }
2244
2245 return SymbolicName;
2246 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002247
Chris Lattner53e677a2004-04-02 20:23:17 +00002248 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002249 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002250}
2251
Dan Gohman26466c02009-05-08 20:26:55 +00002252/// createNodeForGEP - Expand GEP instructions into add and multiply
2253/// operations. This allows them to be analyzed by regular SCEV code.
2254///
Dan Gohmanfb791602009-05-08 20:58:38 +00002255SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002256
2257 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002258 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002259 // Don't attempt to analyze GEPs over unsized objects.
2260 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2261 return getUnknown(GEP);
Dan Gohman26466c02009-05-08 20:26:55 +00002262 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002263 gep_type_iterator GTI = gep_type_begin(GEP);
2264 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2265 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002266 I != E; ++I) {
2267 Value *Index = *I;
2268 // Compute the (potentially symbolic) offset in bytes for this index.
2269 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2270 // For a struct, add the member offset.
2271 const StructLayout &SL = *TD->getStructLayout(STy);
2272 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2273 uint64_t Offset = SL.getElementOffset(FieldNo);
2274 TotalOffset = getAddExpr(TotalOffset,
2275 getIntegerSCEV(Offset, IntPtrTy));
2276 } else {
2277 // For an array, add the element offset, explicitly scaled.
2278 SCEVHandle LocalOffset = getSCEV(Index);
2279 if (!isa<PointerType>(LocalOffset->getType()))
2280 // Getelementptr indicies are signed.
2281 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2282 IntPtrTy);
2283 LocalOffset =
2284 getMulExpr(LocalOffset,
Duncan Sands777d2302009-05-09 07:06:46 +00002285 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman26466c02009-05-08 20:26:55 +00002286 IntPtrTy));
2287 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2288 }
2289 }
2290 return getAddExpr(getSCEV(Base), TotalOffset);
2291}
2292
Nick Lewycky83bb0052007-11-22 07:59:40 +00002293/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2294/// guaranteed to end in (at every loop iteration). It is, at the same time,
2295/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2296/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002297static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohman622ed672009-05-04 22:02:23 +00002298 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002299 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002300
Dan Gohman622ed672009-05-04 22:02:23 +00002301 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002302 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2303 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002304
Dan Gohman622ed672009-05-04 22:02:23 +00002305 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002306 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2307 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohman42a58752009-05-12 01:23:18 +00002308 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002309 }
2310
Dan Gohman622ed672009-05-04 22:02:23 +00002311 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002312 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2313 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohman42a58752009-05-12 01:23:18 +00002314 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002315 }
2316
Dan Gohman622ed672009-05-04 22:02:23 +00002317 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002318 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002319 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00002320 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002321 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002322 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002323 }
2324
Dan Gohman622ed672009-05-04 22:02:23 +00002325 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002326 // The result is the sum of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002327 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2328 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002329 for (unsigned i = 1, e = M->getNumOperands();
2330 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002331 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002332 BitWidth);
2333 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002334 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002335
Dan Gohman622ed672009-05-04 22:02:23 +00002336 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002337 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002338 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00002339 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002340 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002341 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002342 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002343
Dan Gohman622ed672009-05-04 22:02:23 +00002344 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002345 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002346 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002347 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002348 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002349 return MinOpRes;
2350 }
2351
Dan Gohman622ed672009-05-04 22:02:23 +00002352 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002353 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002354 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky3e630762008-02-20 06:48:22 +00002355 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002356 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky3e630762008-02-20 06:48:22 +00002357 return MinOpRes;
2358 }
2359
Nick Lewycky789558d2009-01-13 09:18:58 +00002360 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00002361 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002362}
Chris Lattner53e677a2004-04-02 20:23:17 +00002363
2364/// createSCEV - We know that there is no SCEV for the specified value.
2365/// Analyze the expression.
2366///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002367SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002368 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002369 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002370
Dan Gohman6c459a22008-06-22 19:56:46 +00002371 unsigned Opcode = Instruction::UserOp1;
2372 if (Instruction *I = dyn_cast<Instruction>(V))
2373 Opcode = I->getOpcode();
2374 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2375 Opcode = CE->getOpcode();
2376 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002377 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002378
Dan Gohman6c459a22008-06-22 19:56:46 +00002379 User *U = cast<User>(V);
2380 switch (Opcode) {
2381 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002382 return getAddExpr(getSCEV(U->getOperand(0)),
2383 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002384 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002385 return getMulExpr(getSCEV(U->getOperand(0)),
2386 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002387 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002388 return getUDivExpr(getSCEV(U->getOperand(0)),
2389 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002390 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002391 return getMinusSCEV(getSCEV(U->getOperand(0)),
2392 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002393 case Instruction::And:
2394 // For an expression like x&255 that merely masks off the high bits,
2395 // use zext(trunc(x)) as the SCEV expression.
2396 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002397 if (CI->isNullValue())
2398 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002399 if (CI->isAllOnesValue())
2400 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002401 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002402
2403 // Instcombine's ShrinkDemandedConstant may strip bits out of
2404 // constants, obscuring what would otherwise be a low-bits mask.
2405 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2406 // knew about to reconstruct a low-bits mask value.
2407 unsigned LZ = A.countLeadingZeros();
2408 unsigned BitWidth = A.getBitWidth();
2409 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2410 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2411 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2412
2413 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2414
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002415 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002416 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002417 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002418 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002419 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002420 }
2421 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002422
Dan Gohman6c459a22008-06-22 19:56:46 +00002423 case Instruction::Or:
2424 // If the RHS of the Or is a constant, we may have something like:
2425 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2426 // optimizations will transparently handle this case.
2427 //
2428 // In order for this transformation to be safe, the LHS must be of the
2429 // form X*(2^n) and the Or constant must be less than 2^n.
2430 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2431 SCEVHandle LHS = getSCEV(U->getOperand(0));
2432 const APInt &CIVal = CI->getValue();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002433 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002434 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002435 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002436 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002437 break;
2438 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002439 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002440 // If the RHS of the xor is a signbit, then this is just an add.
2441 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002442 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002443 return getAddExpr(getSCEV(U->getOperand(0)),
2444 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002445
2446 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002447 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002448 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002449
2450 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2451 // This is a variant of the check for xor with -1, and it handles
2452 // the case where instcombine has trimmed non-demanded bits out
2453 // of an xor with -1.
2454 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2455 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2456 if (BO->getOpcode() == Instruction::And &&
2457 LCI->getValue() == CI->getValue())
2458 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002459 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002460 const Type *UTy = U->getType();
2461 SCEVHandle Z0 = Z->getOperand();
2462 const Type *Z0Ty = Z0->getType();
2463 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2464
2465 // If C is a low-bits mask, the zero extend is zerving to
2466 // mask off the high bits. Complement the operand and
2467 // re-apply the zext.
2468 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2469 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2470
2471 // If C is a single bit, it may be in the sign-bit position
2472 // before the zero-extend. In this case, represent the xor
2473 // using an add, which is equivalent, and re-apply the zext.
2474 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2475 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2476 Trunc.isSignBit())
2477 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2478 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002479 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002480 }
2481 break;
2482
2483 case Instruction::Shl:
2484 // Turn shift left of a constant amount into a multiply.
2485 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2486 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2487 Constant *X = ConstantInt::get(
2488 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002489 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002490 }
2491 break;
2492
Nick Lewycky01eaf802008-07-07 06:15:49 +00002493 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002494 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002495 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2496 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2497 Constant *X = ConstantInt::get(
2498 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002499 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002500 }
2501 break;
2502
Dan Gohman4ee29af2009-04-21 02:26:00 +00002503 case Instruction::AShr:
2504 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2505 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2506 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2507 if (L->getOpcode() == Instruction::Shl &&
2508 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002509 unsigned BitWidth = getTypeSizeInBits(U->getType());
2510 uint64_t Amt = BitWidth - CI->getZExtValue();
2511 if (Amt == BitWidth)
2512 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2513 if (Amt > BitWidth)
2514 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002515 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002516 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002517 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002518 U->getType());
2519 }
2520 break;
2521
Dan Gohman6c459a22008-06-22 19:56:46 +00002522 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002523 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002524
2525 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002526 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002527
2528 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002529 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002530
2531 case Instruction::BitCast:
2532 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002533 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002534 return getSCEV(U->getOperand(0));
2535 break;
2536
Dan Gohman2d1be872009-04-16 03:18:22 +00002537 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002538 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002539 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002540 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002541
2542 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002543 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002544 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2545 U->getType());
2546
Dan Gohman26466c02009-05-08 20:26:55 +00002547 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002548 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002549 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002550
Dan Gohman6c459a22008-06-22 19:56:46 +00002551 case Instruction::PHI:
2552 return createNodeForPHI(cast<PHINode>(U));
2553
2554 case Instruction::Select:
2555 // This could be a smax or umax that was lowered earlier.
2556 // Try to recover it.
2557 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2558 Value *LHS = ICI->getOperand(0);
2559 Value *RHS = ICI->getOperand(1);
2560 switch (ICI->getPredicate()) {
2561 case ICmpInst::ICMP_SLT:
2562 case ICmpInst::ICMP_SLE:
2563 std::swap(LHS, RHS);
2564 // fall through
2565 case ICmpInst::ICMP_SGT:
2566 case ICmpInst::ICMP_SGE:
2567 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002568 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002569 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00002570 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002571 return getNotSCEV(getSMaxExpr(
2572 getNotSCEV(getSCEV(LHS)),
2573 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002574 break;
2575 case ICmpInst::ICMP_ULT:
2576 case ICmpInst::ICMP_ULE:
2577 std::swap(LHS, RHS);
2578 // fall through
2579 case ICmpInst::ICMP_UGT:
2580 case ICmpInst::ICMP_UGE:
2581 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002582 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002583 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2584 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002585 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2586 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002587 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002588 case ICmpInst::ICMP_NE:
2589 // n != 0 ? n : 1 -> umax(n, 1)
2590 if (LHS == U->getOperand(1) &&
2591 isa<ConstantInt>(U->getOperand(2)) &&
2592 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2593 isa<ConstantInt>(RHS) &&
2594 cast<ConstantInt>(RHS)->isZero())
2595 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2596 break;
2597 case ICmpInst::ICMP_EQ:
2598 // n == 0 ? 1 : n -> umax(n, 1)
2599 if (LHS == U->getOperand(2) &&
2600 isa<ConstantInt>(U->getOperand(1)) &&
2601 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2602 isa<ConstantInt>(RHS) &&
2603 cast<ConstantInt>(RHS)->isZero())
2604 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2605 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002606 default:
2607 break;
2608 }
2609 }
2610
2611 default: // We cannot analyze this expression.
2612 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002613 }
2614
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002615 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002616}
2617
2618
2619
2620//===----------------------------------------------------------------------===//
2621// Iteration Count Computation Code
2622//
2623
Dan Gohman46bdfb02009-02-24 18:55:53 +00002624/// getBackedgeTakenCount - If the specified loop has a predictable
2625/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2626/// object. The backedge-taken count is the number of times the loop header
2627/// will be branched to from within the loop. This is one less than the
2628/// trip count of the loop, since it doesn't count the first iteration,
2629/// when the header is branched to from outside the loop.
2630///
2631/// Note that it is not valid to call this method on a loop without a
2632/// loop-invariant backedge-taken count (see
2633/// hasLoopInvariantBackedgeTakenCount).
2634///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002635SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002636 return getBackedgeTakenInfo(L).Exact;
2637}
2638
2639/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2640/// return the least SCEV value that is known never to be less than the
2641/// actual backedge taken count.
2642SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2643 return getBackedgeTakenInfo(L).Max;
2644}
2645
2646const ScalarEvolution::BackedgeTakenInfo &
2647ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002648 // Initially insert a CouldNotCompute for this loop. If the insertion
2649 // succeeds, procede to actually compute a backedge-taken count and
2650 // update the value. The temporary CouldNotCompute value tells SCEV
2651 // code elsewhere that it shouldn't attempt to request a new
2652 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002653 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002654 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2655 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002656 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002657 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002658 assert(ItCount.Exact->isLoopInvariant(L) &&
2659 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002660 "Computed trip count isn't loop invariant for loop!");
2661 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002662
Dan Gohman01ecca22009-04-27 20:16:15 +00002663 // Update the value in the map.
2664 Pair.first->second = ItCount;
Chris Lattner53e677a2004-04-02 20:23:17 +00002665 } else if (isa<PHINode>(L->getHeader()->begin())) {
2666 // Only count loops that have phi nodes as not being computable.
2667 ++NumTripCountsNotComputed;
2668 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002669
2670 // Now that we know more about the trip count for this loop, forget any
2671 // existing SCEV values for PHI nodes in this loop since they are only
2672 // conservative estimates made without the benefit
2673 // of trip count information.
2674 if (ItCount.hasAnyInfo())
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002675 forgetLoopPHIs(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002676 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002677 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002678}
2679
Dan Gohman46bdfb02009-02-24 18:55:53 +00002680/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002681/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002682/// ScalarEvolution's ability to compute a trip count, or if the loop
2683/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002684void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002685 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002686 forgetLoopPHIs(L);
2687}
2688
2689/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2690/// PHI nodes in the given loop. This is used when the trip count of
2691/// the loop may have changed.
2692void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002693 BasicBlock *Header = L->getHeader();
2694
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002695 // Push all Loop-header PHIs onto the Worklist stack, except those
2696 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2697 // a PHI either means that it has an unrecognized structure, or it's
2698 // a PHI that's in the progress of being computed by createNodeForPHI.
2699 // In the former case, additional loop trip count information isn't
2700 // going to change anything. In the later case, createNodeForPHI will
2701 // perform the necessary updates on its own when it gets to that point.
Dan Gohman35738ac2009-05-04 22:30:44 +00002702 SmallVector<Instruction *, 16> Worklist;
2703 for (BasicBlock::iterator I = Header->begin();
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002704 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2705 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2706 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2707 Worklist.push_back(PN);
2708 }
Dan Gohman35738ac2009-05-04 22:30:44 +00002709
2710 while (!Worklist.empty()) {
2711 Instruction *I = Worklist.pop_back_val();
2712 if (Scalars.erase(I))
2713 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2714 UI != UE; ++UI)
2715 Worklist.push_back(cast<Instruction>(UI));
2716 }
Dan Gohman60f8a632009-02-17 20:49:49 +00002717}
2718
Dan Gohman46bdfb02009-02-24 18:55:53 +00002719/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2720/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002721ScalarEvolution::BackedgeTakenInfo
2722ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002723 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel5c06f612009-06-05 23:08:56 +00002724 BasicBlock *ExitBlock = L->getExitBlock();
2725 if (!ExitBlock)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002726 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00002727
2728 // Okay, there is one exit block. Try to find the condition that causes the
2729 // loop to be exited.
Devang Patel5c06f612009-06-05 23:08:56 +00002730 BasicBlock *ExitingBlock = L->getExitingBlock();
2731 if (!ExitingBlock)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002732 return CouldNotCompute; // More than one block exiting!
Chris Lattner53e677a2004-04-02 20:23:17 +00002733
2734 // Okay, we've computed the exiting block. See what condition causes us to
2735 // exit.
2736 //
2737 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002738 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002739 if (ExitBr == 0) return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00002740 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002741
2742 // At this point, we know we have a conditional branch that determines whether
2743 // the loop is exited. However, we don't know if the branch is executed each
2744 // time through the loop. If not, then the execution count of the branch will
2745 // not be equal to the trip count of the loop.
2746 //
2747 // Currently we check for this by checking to see if the Exit branch goes to
2748 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002749 // times as the loop. We also handle the case where the exit block *is* the
2750 // loop header. This is common for un-rotated loops. More extensive analysis
2751 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002752 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002753 ExitBr->getSuccessor(1) != L->getHeader() &&
2754 ExitBr->getParent() != L->getHeader())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002755 return CouldNotCompute;
Chris Lattner8b0e3602007-01-07 02:24:26 +00002756
Reid Spencere4d87aa2006-12-23 06:05:41 +00002757 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2758
Eli Friedman361e54d2009-05-09 12:32:42 +00002759 // If it's not an integer or pointer comparison then compute it the hard way.
2760 if (ExitCond == 0)
Dan Gohman46bdfb02009-02-24 18:55:53 +00002761 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Chris Lattner7980fb92004-04-17 18:36:24 +00002762 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002763
Reid Spencere4d87aa2006-12-23 06:05:41 +00002764 // If the condition was exit on true, convert the condition to exit on false
2765 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002766 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002767 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002768 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002769 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002770
2771 // Handle common loops like: for (X = "string"; *X; ++X)
2772 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2773 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2774 SCEVHandle ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002775 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Chris Lattner673e02b2004-10-12 01:49:27 +00002776 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2777 }
2778
Chris Lattner53e677a2004-04-02 20:23:17 +00002779 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2780 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2781
2782 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00002783 LHS = getSCEVAtScope(LHS, L);
2784 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002785
Reid Spencere4d87aa2006-12-23 06:05:41 +00002786 // At this point, we would like to compute how many iterations of the
2787 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002788 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2789 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002790 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002791 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002792 }
2793
Chris Lattner53e677a2004-04-02 20:23:17 +00002794 // If we have a comparison of a chrec against a constant, try to use value
2795 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00002796 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2797 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00002798 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00002799 // Form the constant range.
2800 ConstantRange CompRange(
2801 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002802
Eli Friedman361e54d2009-05-09 12:32:42 +00002803 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2804 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00002805 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002806
Chris Lattner53e677a2004-04-02 20:23:17 +00002807 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002808 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002809 // Convert to: while (X-Y != 0)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002810 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002811 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002812 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002813 }
2814 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002815 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002816 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002817 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002818 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002819 }
2820 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002821 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2822 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002823 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002824 }
2825 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002826 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2827 getNotSCEV(RHS), L, true);
2828 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002829 break;
2830 }
2831 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002832 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2833 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002834 break;
2835 }
2836 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002837 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2838 getNotSCEV(RHS), L, false);
2839 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002840 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002841 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002842 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002843#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002844 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002845 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002846 errs() << "[unsigned] ";
2847 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002848 << Instruction::getOpcodeName(Instruction::ICmp)
2849 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002850#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002851 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002852 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00002853 return
2854 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2855 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002856}
2857
Chris Lattner673e02b2004-10-12 01:49:27 +00002858static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002859EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2860 ScalarEvolution &SE) {
2861 SCEVHandle InVal = SE.getConstant(C);
2862 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002863 assert(isa<SCEVConstant>(Val) &&
2864 "Evaluation of SCEV at constant didn't fold correctly?");
2865 return cast<SCEVConstant>(Val)->getValue();
2866}
2867
2868/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2869/// and a GEP expression (missing the pointer index) indexing into it, return
2870/// the addressed element of the initializer or null if the index expression is
2871/// invalid.
2872static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002873GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002874 const std::vector<ConstantInt*> &Indices) {
2875 Constant *Init = GV->getInitializer();
2876 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002877 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002878 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2879 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2880 Init = cast<Constant>(CS->getOperand(Idx));
2881 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2882 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2883 Init = cast<Constant>(CA->getOperand(Idx));
2884 } else if (isa<ConstantAggregateZero>(Init)) {
2885 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2886 assert(Idx < STy->getNumElements() && "Bad struct index!");
2887 Init = Constant::getNullValue(STy->getElementType(Idx));
2888 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2889 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2890 Init = Constant::getNullValue(ATy->getElementType());
2891 } else {
2892 assert(0 && "Unknown constant aggregate type!");
2893 }
2894 return 0;
2895 } else {
2896 return 0; // Unknown initializer type
2897 }
2898 }
2899 return Init;
2900}
2901
Dan Gohman46bdfb02009-02-24 18:55:53 +00002902/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2903/// 'icmp op load X, cst', try to see if we can compute the backedge
2904/// execution count.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002905SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002906ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2907 const Loop *L,
2908 ICmpInst::Predicate predicate) {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002909 if (LI->isVolatile()) return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00002910
2911 // Check to see if the loaded pointer is a getelementptr of a global.
2912 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002913 if (!GEP) return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00002914
2915 // Make sure that it is really a constant global we are gepping, with an
2916 // initializer, and make sure the first IDX is really 0.
2917 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2918 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2919 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2920 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002921 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00002922
2923 // Okay, we allow one non-constant index into the GEP instruction.
2924 Value *VarIdx = 0;
2925 std::vector<ConstantInt*> Indexes;
2926 unsigned VarIdxNum = 0;
2927 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2928 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2929 Indexes.push_back(CI);
2930 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002931 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00002932 VarIdx = GEP->getOperand(i);
2933 VarIdxNum = i-2;
2934 Indexes.push_back(0);
2935 }
2936
2937 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2938 // Check to see if X is a loop variant variable value now.
2939 SCEVHandle Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00002940 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00002941
2942 // We can only recognize very limited forms of loop index expressions, in
2943 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00002944 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00002945 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2946 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2947 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002948 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00002949
2950 unsigned MaxSteps = MaxBruteForceIterations;
2951 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002952 ConstantInt *ItCst =
Dan Gohman6de29f82009-06-15 22:12:54 +00002953 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002954 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00002955
2956 // Form the GEP offset.
2957 Indexes[VarIdxNum] = Val;
2958
2959 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2960 if (Result == 0) break; // Cannot compute!
2961
2962 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002963 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002964 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002965 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002966#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002967 errs() << "\n***\n*** Computed loop count " << *ItCst
2968 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2969 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002970#endif
2971 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002972 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002973 }
2974 }
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002975 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00002976}
2977
2978
Chris Lattner3221ad02004-04-17 22:58:41 +00002979/// CanConstantFold - Return true if we can constant fold an instruction of the
2980/// specified type, assuming that all operands were constants.
2981static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002982 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002983 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2984 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002985
Chris Lattner3221ad02004-04-17 22:58:41 +00002986 if (const CallInst *CI = dyn_cast<CallInst>(I))
2987 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002988 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002989 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002990}
2991
Chris Lattner3221ad02004-04-17 22:58:41 +00002992/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2993/// in the loop that V is derived from. We allow arbitrary operations along the
2994/// way, but the operands of an operation must either be constants or a value
2995/// derived from a constant PHI. If this expression does not fit with these
2996/// constraints, return null.
2997static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2998 // If this is not an instruction, or if this is an instruction outside of the
2999 // loop, it can't be derived from a loop PHI.
3000 Instruction *I = dyn_cast<Instruction>(V);
3001 if (I == 0 || !L->contains(I->getParent())) return 0;
3002
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003003 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003004 if (L->getHeader() == I->getParent())
3005 return PN;
3006 else
3007 // We don't currently keep track of the control flow needed to evaluate
3008 // PHIs, so we cannot handle PHIs inside of loops.
3009 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003010 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003011
3012 // If we won't be able to constant fold this expression even if the operands
3013 // are constants, return early.
3014 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003015
Chris Lattner3221ad02004-04-17 22:58:41 +00003016 // Otherwise, we can evaluate this instruction if all of its operands are
3017 // constant or derived from a PHI node themselves.
3018 PHINode *PHI = 0;
3019 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3020 if (!(isa<Constant>(I->getOperand(Op)) ||
3021 isa<GlobalValue>(I->getOperand(Op)))) {
3022 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3023 if (P == 0) return 0; // Not evolving from PHI
3024 if (PHI == 0)
3025 PHI = P;
3026 else if (PHI != P)
3027 return 0; // Evolving from multiple different PHIs.
3028 }
3029
3030 // This is a expression evolving from a constant PHI!
3031 return PHI;
3032}
3033
3034/// EvaluateExpression - Given an expression that passes the
3035/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3036/// in the loop has the value PHIVal. If we can't fold this expression for some
3037/// reason, return null.
3038static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3039 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003040 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003041 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003042 Instruction *I = cast<Instruction>(V);
3043
3044 std::vector<Constant*> Operands;
3045 Operands.resize(I->getNumOperands());
3046
3047 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3048 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3049 if (Operands[i] == 0) return 0;
3050 }
3051
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003052 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3053 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3054 &Operands[0], Operands.size());
3055 else
3056 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3057 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00003058}
3059
3060/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3061/// in the header of its containing loop, we know the loop executes a
3062/// constant number of times, and the PHI node is just a recurrence
3063/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003064Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003065getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00003066 std::map<PHINode*, Constant*>::iterator I =
3067 ConstantEvolutionLoopExitValue.find(PN);
3068 if (I != ConstantEvolutionLoopExitValue.end())
3069 return I->second;
3070
Dan Gohman46bdfb02009-02-24 18:55:53 +00003071 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003072 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3073
3074 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3075
3076 // Since the loop is canonicalized, the PHI node must have two entries. One
3077 // entry must be a constant (coming in from outside of the loop), and the
3078 // second must be derived from the same PHI.
3079 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3080 Constant *StartCST =
3081 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3082 if (StartCST == 0)
3083 return RetVal = 0; // Must be a constant.
3084
3085 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3086 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3087 if (PN2 != PN)
3088 return RetVal = 0; // Not derived from same PHI.
3089
3090 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003091 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003092 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003093
Dan Gohman46bdfb02009-02-24 18:55:53 +00003094 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003095 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003096 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3097 if (IterationNum == NumIterations)
3098 return RetVal = PHIVal; // Got exit value!
3099
3100 // Compute the value of the PHI node for the next iteration.
3101 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3102 if (NextPHI == PHIVal)
3103 return RetVal = NextPHI; // Stopped evolving!
3104 if (NextPHI == 0)
3105 return 0; // Couldn't evaluate!
3106 PHIVal = NextPHI;
3107 }
3108}
3109
Dan Gohman46bdfb02009-02-24 18:55:53 +00003110/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003111/// constant number of times (the condition evolves only from constants),
3112/// try to evaluate a few iterations of the loop until we get the exit
3113/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003114/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003115SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003116ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003117 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003118 if (PN == 0) return CouldNotCompute;
Chris Lattner7980fb92004-04-17 18:36:24 +00003119
3120 // Since the loop is canonicalized, the PHI node must have two entries. One
3121 // entry must be a constant (coming in from outside of the loop), and the
3122 // second must be derived from the same PHI.
3123 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3124 Constant *StartCST =
3125 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003126 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003127
3128 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3129 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003130 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003131
3132 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3133 // the loop symbolically to determine when the condition gets a value of
3134 // "ExitWhen".
3135 unsigned IterationNum = 0;
3136 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3137 for (Constant *PHIVal = StartCST;
3138 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003139 ConstantInt *CondVal =
3140 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003141
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003142 // Couldn't symbolically evaluate.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003143 if (!CondVal) return CouldNotCompute;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003144
Reid Spencere8019bb2007-03-01 07:25:48 +00003145 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003146 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00003147 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003148 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003149 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003150
Chris Lattner3221ad02004-04-17 22:58:41 +00003151 // Compute the value of the PHI node for the next iteration.
3152 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3153 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003154 return CouldNotCompute; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003155 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003156 }
3157
3158 // Too many iterations were needed to evaluate.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003159 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003160}
3161
Dan Gohman66a7e852009-05-08 20:38:54 +00003162/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3163/// at the specified scope in the program. The L value specifies a loop
3164/// nest to evaluate the expression at, where null is the top-level or a
3165/// specified loop is immediately inside of the loop.
3166///
3167/// This method can be used to compute the exit value for a variable defined
3168/// in a loop by querying what the value will hold in the parent loop.
3169///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003170/// In the case that a relevant loop exit value cannot be computed, the
3171/// original value V is returned.
Dan Gohman35738ac2009-05-04 22:30:44 +00003172SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003173 // FIXME: this should be turned into a virtual method on SCEV!
3174
Chris Lattner3221ad02004-04-17 22:58:41 +00003175 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003176
Nick Lewycky3e630762008-02-20 06:48:22 +00003177 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003178 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003179 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003180 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003181 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003182 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3183 if (PHINode *PN = dyn_cast<PHINode>(I))
3184 if (PN->getParent() == LI->getHeader()) {
3185 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003186 // to see if the loop that contains it has a known backedge-taken
3187 // count. If so, we may be able to force computation of the exit
3188 // value.
3189 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003190 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003191 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003192 // Okay, we know how many times the containing loop executes. If
3193 // this is a constant evolving PHI node, get the final value at
3194 // the specified iteration number.
3195 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003196 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003197 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003198 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003199 }
3200 }
3201
Reid Spencer09906f32006-12-04 21:33:23 +00003202 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003203 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003204 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003205 // result. This is particularly useful for computing loop exit values.
3206 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003207 // Check to see if we've folded this instruction at this loop before.
3208 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3209 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3210 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3211 if (!Pair.second)
3212 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3213
Chris Lattner3221ad02004-04-17 22:58:41 +00003214 std::vector<Constant*> Operands;
3215 Operands.reserve(I->getNumOperands());
3216 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3217 Value *Op = I->getOperand(i);
3218 if (Constant *C = dyn_cast<Constant>(Op)) {
3219 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003220 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003221 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003222 // non-integer and non-pointer, don't even try to analyze them
3223 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003224 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003225 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003226
Chris Lattner3221ad02004-04-17 22:58:41 +00003227 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00003228 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003229 Constant *C = SC->getValue();
3230 if (C->getType() != Op->getType())
3231 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3232 Op->getType(),
3233 false),
3234 C, Op->getType());
3235 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003236 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003237 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3238 if (C->getType() != Op->getType())
3239 C =
3240 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3241 Op->getType(),
3242 false),
3243 C, Op->getType());
3244 Operands.push_back(C);
3245 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003246 return V;
3247 } else {
3248 return V;
3249 }
3250 }
3251 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003252
3253 Constant *C;
3254 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3255 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3256 &Operands[0], Operands.size());
3257 else
3258 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3259 &Operands[0], Operands.size());
Dan Gohman6bce6432009-05-08 20:47:27 +00003260 Pair.first->second = C;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003261 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003262 }
3263 }
3264
3265 // This is some other type of SCEVUnknown, just return it.
3266 return V;
3267 }
3268
Dan Gohman622ed672009-05-04 22:02:23 +00003269 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003270 // Avoid performing the look-up in the common case where the specified
3271 // expression has no loop-variant portions.
3272 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3273 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3274 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003275 // Okay, at least one of these operands is loop variant but might be
3276 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmana82752c2009-06-14 22:47:23 +00003277 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003278 NewOps.push_back(OpAtScope);
3279
3280 for (++i; i != e; ++i) {
3281 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003282 NewOps.push_back(OpAtScope);
3283 }
3284 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003285 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003286 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003287 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003288 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003289 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003290 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003291 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003292 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003293 }
3294 }
3295 // If we got here, all operands are loop invariant.
3296 return Comm;
3297 }
3298
Dan Gohman622ed672009-05-04 22:02:23 +00003299 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003300 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003301 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003302 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3303 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003304 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003305 }
3306
3307 // If this is a loop recurrence for a loop that does not contain L, then we
3308 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003309 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003310 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3311 // To evaluate this recurrence, we need to know how many times the AddRec
3312 // loop iterates. Compute this now.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003313 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003314 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003315
Eli Friedmanb42a6262008-08-04 23:49:06 +00003316 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003317 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003318 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003319 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003320 }
3321
Dan Gohman622ed672009-05-04 22:02:23 +00003322 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003323 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003324 if (Op == Cast->getOperand())
3325 return Cast; // must be loop invariant
3326 return getZeroExtendExpr(Op, Cast->getType());
3327 }
3328
Dan Gohman622ed672009-05-04 22:02:23 +00003329 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003330 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003331 if (Op == Cast->getOperand())
3332 return Cast; // must be loop invariant
3333 return getSignExtendExpr(Op, Cast->getType());
3334 }
3335
Dan Gohman622ed672009-05-04 22:02:23 +00003336 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003337 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003338 if (Op == Cast->getOperand())
3339 return Cast; // must be loop invariant
3340 return getTruncateExpr(Op, Cast->getType());
3341 }
3342
3343 assert(0 && "Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003344 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003345}
3346
Dan Gohman66a7e852009-05-08 20:38:54 +00003347/// getSCEVAtScope - This is a convenience function which does
3348/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003349SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3350 return getSCEVAtScope(getSCEV(V), L);
3351}
3352
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003353/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3354/// following equation:
3355///
3356/// A * X = B (mod N)
3357///
3358/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3359/// A and B isn't important.
3360///
3361/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3362static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3363 ScalarEvolution &SE) {
3364 uint32_t BW = A.getBitWidth();
3365 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3366 assert(A != 0 && "A must be non-zero.");
3367
3368 // 1. D = gcd(A, N)
3369 //
3370 // The gcd of A and N may have only one prime factor: 2. The number of
3371 // trailing zeros in A is its multiplicity
3372 uint32_t Mult2 = A.countTrailingZeros();
3373 // D = 2^Mult2
3374
3375 // 2. Check if B is divisible by D.
3376 //
3377 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3378 // is not less than multiplicity of this prime factor for D.
3379 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003380 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003381
3382 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3383 // modulo (N / D).
3384 //
3385 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3386 // bit width during computations.
3387 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3388 APInt Mod(BW + 1, 0);
3389 Mod.set(BW - Mult2); // Mod = N / D
3390 APInt I = AD.multiplicativeInverse(Mod);
3391
3392 // 4. Compute the minimum unsigned root of the equation:
3393 // I * (B / D) mod (N / D)
3394 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3395
3396 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3397 // bits.
3398 return SE.getConstant(Result.trunc(BW));
3399}
Chris Lattner53e677a2004-04-02 20:23:17 +00003400
3401/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3402/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3403/// might be the same) or two SCEVCouldNotCompute objects.
3404///
3405static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00003406SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003407 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00003408 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3409 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3410 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003411
Chris Lattner53e677a2004-04-02 20:23:17 +00003412 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00003413 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003414 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003415 return std::make_pair(CNC, CNC);
3416 }
3417
Reid Spencere8019bb2007-03-01 07:25:48 +00003418 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00003419 const APInt &L = LC->getValue()->getValue();
3420 const APInt &M = MC->getValue()->getValue();
3421 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00003422 APInt Two(BitWidth, 2);
3423 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003424
Reid Spencere8019bb2007-03-01 07:25:48 +00003425 {
3426 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00003427 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00003428 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3429 // The B coefficient is M-N/2
3430 APInt B(M);
3431 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003432
Reid Spencere8019bb2007-03-01 07:25:48 +00003433 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00003434 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00003435
Reid Spencere8019bb2007-03-01 07:25:48 +00003436 // Compute the B^2-4ac term.
3437 APInt SqrtTerm(B);
3438 SqrtTerm *= B;
3439 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00003440
Reid Spencere8019bb2007-03-01 07:25:48 +00003441 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3442 // integer value or else APInt::sqrt() will assert.
3443 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003444
Reid Spencere8019bb2007-03-01 07:25:48 +00003445 // Compute the two solutions for the quadratic formula.
3446 // The divisions must be performed as signed divisions.
3447 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00003448 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003449 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003450 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003451 return std::make_pair(CNC, CNC);
3452 }
3453
Reid Spencere8019bb2007-03-01 07:25:48 +00003454 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3455 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003456
Dan Gohman246b2562007-10-22 18:31:58 +00003457 return std::make_pair(SE.getConstant(Solution1),
3458 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00003459 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00003460}
3461
3462/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003463/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman35738ac2009-05-04 22:30:44 +00003464SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003465 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00003466 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003467 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00003468 if (C->getValue()->isZero()) return C;
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003469 return CouldNotCompute; // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003470 }
3471
Dan Gohman35738ac2009-05-04 22:30:44 +00003472 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003473 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003474 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003475
3476 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003477 // If this is an affine expression, the execution count of this branch is
3478 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00003479 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003480 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00003481 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003482 // equivalent to:
3483 //
3484 // Step*N = -Start (mod 2^BW)
3485 //
3486 // where BW is the common bit width of Start and Step.
3487
Chris Lattner53e677a2004-04-02 20:23:17 +00003488 // Get the initial value for the loop.
3489 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003490 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003491
Dan Gohman622ed672009-05-04 22:02:23 +00003492 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003493 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00003494
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003495 // First, handle unitary steps.
3496 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003497 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003498 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3499 return Start; // N = Start (as unsigned)
3500
3501 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00003502 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003503 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003504 -StartC->getValue()->getValue(),
3505 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003506 }
Chris Lattner42a75512007-01-15 02:27:26 +00003507 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003508 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3509 // the quadratic equation to solve it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003510 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3511 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00003512 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3513 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003514 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003515#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003516 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3517 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003518#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00003519 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003520 if (ConstantInt *CB =
3521 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003522 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003523 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003524 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003525
Chris Lattner53e677a2004-04-02 20:23:17 +00003526 // We can only use this value if the chrec ends up with an exact zero
3527 // value at this index. When solving for "X*X != 5", for example, we
3528 // should not accept a root of 2.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003529 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00003530 if (Val->isZero())
3531 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00003532 }
3533 }
3534 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003535
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003536 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003537}
3538
3539/// HowFarToNonZero - Return the number of times a backedge checking the
3540/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003541/// CouldNotCompute
Dan Gohman35738ac2009-05-04 22:30:44 +00003542SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003543 // Loops that look like: while (X == 0) are very strange indeed. We don't
3544 // handle them yet except for the trivial case. This could be expanded in the
3545 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003546
Chris Lattner53e677a2004-04-02 20:23:17 +00003547 // If the value is a constant, check to see if it is known to be non-zero
3548 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00003549 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00003550 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003551 return getIntegerSCEV(0, C->getType());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003552 return CouldNotCompute; // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003553 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003554
Chris Lattner53e677a2004-04-02 20:23:17 +00003555 // We could implement others, but I really doubt anyone writes loops like
3556 // this, and if they did, they would already be constant folded.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003557 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003558}
3559
Dan Gohman859b4822009-05-18 15:36:09 +00003560/// getLoopPredecessor - If the given loop's header has exactly one unique
3561/// predecessor outside the loop, return it. Otherwise return null.
3562///
3563BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3564 BasicBlock *Header = L->getHeader();
3565 BasicBlock *Pred = 0;
3566 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3567 PI != E; ++PI)
3568 if (!L->contains(*PI)) {
3569 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3570 Pred = *PI;
3571 }
3572 return Pred;
3573}
3574
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003575/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3576/// (which may not be an immediate predecessor) which has exactly one
3577/// successor from which BB is reachable, or null if no such block is
3578/// found.
3579///
3580BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003581ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003582 // If the block has a unique predecessor, then there is no path from the
3583 // predecessor to the block that does not go through the direct edge
3584 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003585 if (BasicBlock *Pred = BB->getSinglePredecessor())
3586 return Pred;
3587
3588 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00003589 // If the header has a unique predecessor outside the loop, it must be
3590 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003591 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00003592 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003593
3594 return 0;
3595}
3596
Dan Gohmanc2390b12009-02-12 22:19:27 +00003597/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003598/// a conditional between LHS and RHS. This is used to help avoid max
3599/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003600bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003601 ICmpInst::Predicate Pred,
Dan Gohman35738ac2009-05-04 22:30:44 +00003602 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00003603 // Interpret a null as meaning no loop, where there is obviously no guard
3604 // (interprocedural conditions notwithstanding).
3605 if (!L) return false;
3606
Dan Gohman859b4822009-05-18 15:36:09 +00003607 BasicBlock *Predecessor = getLoopPredecessor(L);
3608 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003609
Dan Gohman859b4822009-05-18 15:36:09 +00003610 // Starting at the loop predecessor, climb up the predecessor chain, as long
3611 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003612 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00003613 for (; Predecessor;
3614 PredecessorDest = Predecessor,
3615 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00003616
3617 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00003618 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003619 if (!LoopEntryPredicate ||
3620 LoopEntryPredicate->isUnconditional())
3621 continue;
3622
3623 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3624 if (!ICI) continue;
3625
3626 // Now that we found a conditional branch that dominates the loop, check to
3627 // see if it is the comparison we are looking for.
3628 Value *PreCondLHS = ICI->getOperand(0);
3629 Value *PreCondRHS = ICI->getOperand(1);
3630 ICmpInst::Predicate Cond;
Dan Gohman859b4822009-05-18 15:36:09 +00003631 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohman38372182008-08-12 20:17:31 +00003632 Cond = ICI->getPredicate();
3633 else
3634 Cond = ICI->getInversePredicate();
3635
Dan Gohmanc2390b12009-02-12 22:19:27 +00003636 if (Cond == Pred)
3637 ; // An exact match.
3638 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3639 ; // The actual condition is beyond sufficient.
3640 else
3641 // Check a few special cases.
3642 switch (Cond) {
3643 case ICmpInst::ICMP_UGT:
3644 if (Pred == ICmpInst::ICMP_ULT) {
3645 std::swap(PreCondLHS, PreCondRHS);
3646 Cond = ICmpInst::ICMP_ULT;
3647 break;
3648 }
3649 continue;
3650 case ICmpInst::ICMP_SGT:
3651 if (Pred == ICmpInst::ICMP_SLT) {
3652 std::swap(PreCondLHS, PreCondRHS);
3653 Cond = ICmpInst::ICMP_SLT;
3654 break;
3655 }
3656 continue;
3657 case ICmpInst::ICMP_NE:
3658 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3659 // so check for this case by checking if the NE is comparing against
3660 // a minimum or maximum constant.
3661 if (!ICmpInst::isTrueWhenEqual(Pred))
3662 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3663 const APInt &A = CI->getValue();
3664 switch (Pred) {
3665 case ICmpInst::ICMP_SLT:
3666 if (A.isMaxSignedValue()) break;
3667 continue;
3668 case ICmpInst::ICMP_SGT:
3669 if (A.isMinSignedValue()) break;
3670 continue;
3671 case ICmpInst::ICMP_ULT:
3672 if (A.isMaxValue()) break;
3673 continue;
3674 case ICmpInst::ICMP_UGT:
3675 if (A.isMinValue()) break;
3676 continue;
3677 default:
3678 continue;
3679 }
3680 Cond = ICmpInst::ICMP_NE;
3681 // NE is symmetric but the original comparison may not be. Swap
3682 // the operands if necessary so that they match below.
3683 if (isa<SCEVConstant>(LHS))
3684 std::swap(PreCondLHS, PreCondRHS);
3685 break;
3686 }
3687 continue;
3688 default:
3689 // We weren't able to reconcile the condition.
3690 continue;
3691 }
Dan Gohman38372182008-08-12 20:17:31 +00003692
3693 if (!PreCondLHS->getType()->isInteger()) continue;
3694
3695 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3696 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3697 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003698 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3699 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohman38372182008-08-12 20:17:31 +00003700 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003701 }
3702
Dan Gohman38372182008-08-12 20:17:31 +00003703 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003704}
3705
Chris Lattnerdb25de42005-08-15 23:33:51 +00003706/// HowManyLessThans - Return the number of times a backedge containing the
3707/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003708/// CouldNotCompute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003709ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohman35738ac2009-05-04 22:30:44 +00003710HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3711 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003712 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003713 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003714
Dan Gohman35738ac2009-05-04 22:30:44 +00003715 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003716 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003717 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003718
3719 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003720 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00003721 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3722 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3723 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3724
3725 // TODO: handle non-constant strides.
3726 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3727 if (!CStep || CStep->isZero())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003728 return CouldNotCompute;
Dan Gohman70a1fe72009-05-18 15:22:39 +00003729 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003730 // With unit stride, the iteration never steps past the limit value.
3731 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3732 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3733 // Test whether a positive iteration iteration can step past the limit
3734 // value and past the maximum value for its type in a single step.
3735 if (isSigned) {
3736 APInt Max = APInt::getSignedMaxValue(BitWidth);
3737 if ((Max - CStep->getValue()->getValue())
3738 .slt(CLimit->getValue()->getValue()))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003739 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00003740 } else {
3741 APInt Max = APInt::getMaxValue(BitWidth);
3742 if ((Max - CStep->getValue()->getValue())
3743 .ult(CLimit->getValue()->getValue()))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003744 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00003745 }
3746 } else
3747 // TODO: handle non-constant limit values below.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003748 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00003749 } else
3750 // TODO: handle negative strides below.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003751 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003752
Dan Gohmana1af7572009-04-30 20:47:05 +00003753 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3754 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3755 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00003756 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003757
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003758 // First, we get the value of the LHS in the first iteration: n
3759 SCEVHandle Start = AddRec->getOperand(0);
3760
Dan Gohmana1af7572009-04-30 20:47:05 +00003761 // Determine the minimum constant start value.
3762 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3763 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3764 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003765
Dan Gohmana1af7572009-04-30 20:47:05 +00003766 // If we know that the condition is true in order to enter the loop,
3767 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00003768 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3769 // the division must round up.
Dan Gohmana1af7572009-04-30 20:47:05 +00003770 SCEVHandle End = RHS;
3771 if (!isLoopGuardedByCond(L,
3772 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3773 getMinusSCEV(Start, Step), RHS))
3774 End = isSigned ? getSMaxExpr(RHS, Start)
3775 : getUMaxExpr(RHS, Start);
3776
3777 // Determine the maximum constant end value.
3778 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3779 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3780 APInt::getMaxValue(BitWidth));
3781
3782 // Finally, we subtract these two values and divide, rounding up, to get
3783 // the number of times the backedge is executed.
3784 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3785 getAddExpr(Step, NegOne)),
3786 Step);
3787
3788 // The maximum backedge count is similar, except using the minimum start
3789 // value and the maximum end value.
3790 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3791 MinStart),
3792 getAddExpr(Step, NegOne)),
3793 Step);
3794
3795 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003796 }
3797
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003798 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003799}
3800
Chris Lattner53e677a2004-04-02 20:23:17 +00003801/// getNumIterationsInRange - Return the number of iterations of this loop that
3802/// produce values in the specified constant range. Another way of looking at
3803/// this is that it returns the first iteration number where the value is not in
3804/// the condition, thus computing the exit count. If the iteration count can't
3805/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003806SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3807 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003808 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003809 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003810
3811 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00003812 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003813 if (!SC->getValue()->isZero()) {
Dan Gohmana82752c2009-06-14 22:47:23 +00003814 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003815 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3816 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00003817 if (const SCEVAddRecExpr *ShiftedAddRec =
3818 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00003819 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003820 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003821 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003822 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003823 }
3824
3825 // The only time we can solve this is when we have all constant indices.
3826 // Otherwise, we cannot determine the overflow conditions.
3827 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3828 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003829 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003830
3831
3832 // Okay at this point we know that all elements of the chrec are constants and
3833 // that the start element is zero.
3834
3835 // First check to see if the range contains zero. If not, the first
3836 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003837 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00003838 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00003839 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003840
Chris Lattner53e677a2004-04-02 20:23:17 +00003841 if (isAffine()) {
3842 // If this is an affine expression then we have this situation:
3843 // Solve {0,+,A} in Range === Ax in Range
3844
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003845 // We know that zero is in the range. If A is positive then we know that
3846 // the upper value of the range must be the first possible exit value.
3847 // If A is negative then the lower of the range is the last possible loop
3848 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00003849 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003850 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3851 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003852
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003853 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003854 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003855 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003856
3857 // Evaluate at the exit value. If we really did fall out of the valid
3858 // range, then we computed our trip count, otherwise wrap around or other
3859 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003860 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003861 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003862 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003863
3864 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003865 assert(Range.contains(
3866 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003867 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003868 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003869 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003870 } else if (isQuadratic()) {
3871 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3872 // quadratic equation to solve it. To do this, we must frame our problem in
3873 // terms of figuring out when zero is crossed, instead of when
3874 // Range.getUpper() is crossed.
Dan Gohmana82752c2009-06-14 22:47:23 +00003875 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003876 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3877 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003878
3879 // Next, solve the constructed addrec
3880 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003881 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00003882 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3883 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003884 if (R1) {
3885 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003886 if (ConstantInt *CB =
3887 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003888 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003889 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003890 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003891
Chris Lattner53e677a2004-04-02 20:23:17 +00003892 // Make sure the root is not off by one. The returned iteration should
3893 // not be in the range, but the previous one should be. When solving
3894 // for "X*X < 5", for example, we should not return a root of 2.
3895 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003896 R1->getValue(),
3897 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003898 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003899 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003900 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003901
Dan Gohman246b2562007-10-22 18:31:58 +00003902 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003903 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003904 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003905 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003906 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003907
Chris Lattner53e677a2004-04-02 20:23:17 +00003908 // If R1 was not in the range, then it is a good return value. Make
3909 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003910 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003911 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003912 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003913 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003914 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003915 }
3916 }
3917 }
3918
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003919 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003920}
3921
3922
3923
3924//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00003925// SCEVCallbackVH Class Implementation
3926//===----------------------------------------------------------------------===//
3927
Dan Gohman1959b752009-05-19 19:22:47 +00003928void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman35738ac2009-05-04 22:30:44 +00003929 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3930 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3931 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003932 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3933 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003934 SE->Scalars.erase(getValPtr());
3935 // this now dangles!
3936}
3937
Dan Gohman1959b752009-05-19 19:22:47 +00003938void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003939 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3940
3941 // Forget all the expressions associated with users of the old value,
3942 // so that future queries will recompute the expressions using the new
3943 // value.
3944 SmallVector<User *, 16> Worklist;
3945 Value *Old = getValPtr();
3946 bool DeleteOld = false;
3947 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3948 UI != UE; ++UI)
3949 Worklist.push_back(*UI);
3950 while (!Worklist.empty()) {
3951 User *U = Worklist.pop_back_val();
3952 // Deleting the Old value will cause this to dangle. Postpone
3953 // that until everything else is done.
3954 if (U == Old) {
3955 DeleteOld = true;
3956 continue;
3957 }
3958 if (PHINode *PN = dyn_cast<PHINode>(U))
3959 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003960 if (Instruction *I = dyn_cast<Instruction>(U))
3961 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003962 if (SE->Scalars.erase(U))
3963 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3964 UI != UE; ++UI)
3965 Worklist.push_back(*UI);
3966 }
3967 if (DeleteOld) {
3968 if (PHINode *PN = dyn_cast<PHINode>(Old))
3969 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003970 if (Instruction *I = dyn_cast<Instruction>(Old))
3971 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003972 SE->Scalars.erase(Old);
3973 // this now dangles!
3974 }
3975 // this may dangle!
3976}
3977
Dan Gohman1959b752009-05-19 19:22:47 +00003978ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00003979 : CallbackVH(V), SE(se) {}
3980
3981//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00003982// ScalarEvolution Class Implementation
3983//===----------------------------------------------------------------------===//
3984
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003985ScalarEvolution::ScalarEvolution()
Owen Anderson4a7893b2009-06-18 22:25:12 +00003986 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute(0)) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003987}
3988
Chris Lattner53e677a2004-04-02 20:23:17 +00003989bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003990 this->F = &F;
3991 LI = &getAnalysis<LoopInfo>();
3992 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00003993 return false;
3994}
3995
3996void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003997 Scalars.clear();
3998 BackedgeTakenCounts.clear();
3999 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004000 ValuesAtScopes.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00004001}
4002
4003void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4004 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004005 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004006}
4007
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004008bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004009 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004010}
4011
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004012static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004013 const Loop *L) {
4014 // Print all inner loops first
4015 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4016 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004017
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004018 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004019
Devang Patelb7211a22007-08-21 00:31:24 +00004020 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004021 L->getExitBlocks(ExitBlocks);
4022 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004023 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004024
Dan Gohman46bdfb02009-02-24 18:55:53 +00004025 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4026 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004027 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004028 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004029 }
4030
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004031 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004032}
4033
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004034void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004035 // ScalarEvolution's implementaiton of the print method is to print
4036 // out SCEV values of all instructions that are interesting. Doing
4037 // this potentially causes it to create new SCEV objects though,
4038 // which technically conflicts with the const qualifier. This isn't
4039 // observable from outside the class though (the hasSCEV function
4040 // notwithstanding), so casting away the const isn't dangerous.
4041 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004042
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004043 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004044 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004045 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00004046 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00004047 OS << " --> ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004048 SCEVHandle SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004049 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004050
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004051 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00004052 OS << "\t\t" "Exits: ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004053 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00004054 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004055 OS << "<<Unknown>>";
4056 } else {
4057 OS << *ExitValue;
4058 }
4059 }
4060
Chris Lattner53e677a2004-04-02 20:23:17 +00004061 OS << "\n";
4062 }
4063
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004064 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4065 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4066 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004067}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004068
4069void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4070 raw_os_ostream OS(o);
4071 print(OS, M);
4072}