blob: 5cbb5fac8ac85c5b39397b9c37af6a60e55edc74 [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
Owen Anderson372b46c2009-06-22 21:39:50 +000017// can handle. These classes are reference counted, managed by the const SCEV*
Chris Lattner53e677a2004-04-02 20:23:17 +000018// 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 Lattner75de5ab2006-12-19 01:16:02 +000079#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000083#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman844731a2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman844731a2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000103char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
Chris Lattner53e677a2004-04-02 20:23:17 +0000112SCEV::~SCEV() {}
113void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000114 print(errs());
115 errs() << '\n';
116}
117
118void SCEV::print(std::ostream &o) const {
119 raw_os_ostream OS(o);
120 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000121}
122
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000123bool SCEV::isZero() const {
124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
125 return SC->getValue()->isZero();
126 return false;
127}
128
Dan Gohman70a1fe72009-05-18 15:22:39 +0000129bool SCEV::isOne() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isOne();
132 return false;
133}
Chris Lattner53e677a2004-04-02 20:23:17 +0000134
Owen Anderson753ad612009-06-22 21:57:23 +0000135SCEVCouldNotCompute::SCEVCouldNotCompute() :
136 SCEV(scCouldNotCompute) {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000137
138bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000140 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000141}
142
143const Type *SCEVCouldNotCompute::getType() const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000145 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000146}
147
148bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 return false;
151}
152
Owen Anderson372b46c2009-06-22 21:39:50 +0000153const SCEV* SCEVCouldNotCompute::
154replaceSymbolicValuesWithConcrete(const SCEV* Sym,
155 const SCEV* Conc,
Dan Gohman246b2562007-10-22 18:31:58 +0000156 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000157 return this;
158}
159
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000160void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000161 OS << "***COULDNOTCOMPUTE***";
162}
163
164bool SCEVCouldNotCompute::classof(const SCEV *S) {
165 return S->getSCEVType() == scCouldNotCompute;
166}
167
168
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000169// SCEVConstants - Only allow the creation of one SCEVConstant for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000170// particular value. Don't use a const SCEV* here, or else the object will
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171// never be deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000172
Owen Anderson372b46c2009-06-22 21:39:50 +0000173const SCEV* ScalarEvolution::getConstant(ConstantInt *V) {
Owen Anderson08367b62009-06-22 18:25:46 +0000174 SCEVConstant *&R = SCEVConstants[V];
Owen Anderson753ad612009-06-22 21:57:23 +0000175 if (R == 0) R = new SCEVConstant(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176 return R;
177}
Chris Lattner53e677a2004-04-02 20:23:17 +0000178
Owen Anderson372b46c2009-06-22 21:39:50 +0000179const SCEV* ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman246b2562007-10-22 18:31:58 +0000180 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000181}
182
Owen Anderson372b46c2009-06-22 21:39:50 +0000183const SCEV*
Dan Gohman6de29f82009-06-15 22:12:54 +0000184ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
185 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
186}
187
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000190void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191 WriteAsOperand(OS, V, false);
192}
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Dan Gohman84923602009-04-21 01:25:57 +0000194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Anderson753ad612009-06-22 21:57:23 +0000195 const SCEV* op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman84923602009-04-21 01:25:57 +0000197
198bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
199 return Op->dominates(BB, DT);
200}
201
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000202// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000203// particular input. Don't use a const SCEV* here, or else the object will
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000204// never be deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000205
Owen Anderson753ad612009-06-22 21:57:23 +0000206SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty)
207 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000208 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
209 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000211}
Chris Lattner53e677a2004-04-02 20:23:17 +0000212
Chris Lattner53e677a2004-04-02 20:23:17 +0000213
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000214void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000215 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216}
217
218// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000219// particular input. Don't use a const SCEV* here, or else the object will never
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221
Owen Anderson753ad612009-06-22 21:57:23 +0000222SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty)
223 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000224 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
225 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000226 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227}
228
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000229void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000230 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
Dan Gohmand19534a2007-06-15 14:38:12 +0000233// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000234// particular input. Don't use a const SCEV* here, or else the object will never
Dan Gohmand19534a2007-06-15 14:38:12 +0000235// be deleted!
Dan Gohmand19534a2007-06-15 14:38:12 +0000236
Owen Anderson753ad612009-06-22 21:57:23 +0000237SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty)
238 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000239 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
240 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000241 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000242}
243
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000244void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000245 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000246}
247
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000248// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000249// particular input. Don't use a const SCEV* here, or else the object will never
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000250// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000252void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000253 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
254 const char *OpStr = getOperationStr();
255 OS << "(" << *Operands[0];
256 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
257 OS << OpStr << *Operands[i];
258 OS << ")";
259}
260
Owen Anderson372b46c2009-06-22 21:39:50 +0000261const SCEV* SCEVCommutativeExpr::
262replaceSymbolicValuesWithConcrete(const SCEV* Sym,
263 const SCEV* Conc,
Dan Gohman246b2562007-10-22 18:31:58 +0000264 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000265 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000266 const SCEV* H =
Dan Gohman246b2562007-10-22 18:31:58 +0000267 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000268 if (H != getOperand(i)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000269 SmallVector<const SCEV*, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000270 NewOps.reserve(getNumOperands());
271 for (unsigned j = 0; j != i; ++j)
272 NewOps.push_back(getOperand(j));
273 NewOps.push_back(H);
274 for (++i; i != e; ++i)
275 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000276 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000277
278 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000279 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000280 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000281 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000282 else if (isa<SCEVSMaxExpr>(this))
283 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000284 else if (isa<SCEVUMaxExpr>(this))
285 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000286 else
287 assert(0 && "Unknown commutative expr!");
288 }
289 }
290 return this;
291}
292
Dan Gohmanecb403a2009-05-07 14:00:19 +0000293bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000294 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
295 if (!getOperand(i)->dominates(BB, DT))
296 return false;
297 }
298 return true;
299}
300
Chris Lattner4dc534c2005-02-13 04:37:18 +0000301
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000302// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Owen Anderson372b46c2009-06-22 21:39:50 +0000303// input. Don't use a const SCEV* here, or else the object will never be
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000304// deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000305
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000306bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
307 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
308}
309
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000310void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000311 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000312}
313
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000314const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000315 // In most cases the types of LHS and RHS will be the same, but in some
316 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
317 // depend on the type for correctness, but handling types carefully can
318 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
319 // a pointer type than the RHS, so use the RHS' type here.
320 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000321}
322
323// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000324// particular input. Don't use a const SCEV* here, or else the object will never
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000325// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000326
Owen Anderson372b46c2009-06-22 21:39:50 +0000327const SCEV* SCEVAddRecExpr::
328replaceSymbolicValuesWithConcrete(const SCEV* Sym,
329 const SCEV* Conc,
Dan Gohman246b2562007-10-22 18:31:58 +0000330 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000331 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000332 const SCEV* H =
Dan Gohman246b2562007-10-22 18:31:58 +0000333 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000334 if (H != getOperand(i)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000335 SmallVector<const SCEV*, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000336 NewOps.reserve(getNumOperands());
337 for (unsigned j = 0; j != i; ++j)
338 NewOps.push_back(getOperand(j));
339 NewOps.push_back(H);
340 for (++i; i != e; ++i)
341 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000342 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000343
Dan Gohman246b2562007-10-22 18:31:58 +0000344 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000345 }
346 }
347 return this;
348}
349
350
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000351bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
352 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000353 // contain L and if the start is invariant.
Dan Gohmana3035a62009-05-20 01:01:24 +0000354 // Add recurrences are never invariant in the function-body (null loop).
355 return QueryLoop &&
356 !QueryLoop->contains(L->getHeader()) &&
Chris Lattnerff2006a2005-08-16 00:37:01 +0000357 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000358}
359
360
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000361void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000362 OS << "{" << *Operands[0];
363 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
364 OS << ",+," << *Operands[i];
365 OS << "}<" << L->getHeader()->getName() + ">";
366}
Chris Lattner53e677a2004-04-02 20:23:17 +0000367
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000368// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
Owen Anderson372b46c2009-06-22 21:39:50 +0000369// value. Don't use a const SCEV* here, or else the object will never be
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000370// deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000371
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000372bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
373 // All non-instruction values are loop invariant. All instructions are loop
374 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000375 // Instructions are never considered invariant in the function body
376 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000377 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000378 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000379 return true;
380}
Chris Lattner53e677a2004-04-02 20:23:17 +0000381
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000382bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
383 if (Instruction *I = dyn_cast<Instruction>(getValue()))
384 return DT->dominates(I->getParent(), BB);
385 return true;
386}
387
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000388const Type *SCEVUnknown::getType() const {
389 return V->getType();
390}
Chris Lattner53e677a2004-04-02 20:23:17 +0000391
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000392void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000393 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000394}
395
Chris Lattner8d741b82004-06-20 06:23:15 +0000396//===----------------------------------------------------------------------===//
397// SCEV Utilities
398//===----------------------------------------------------------------------===//
399
400namespace {
401 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
402 /// than the complexity of the RHS. This comparator is used to canonicalize
403 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000404 class VISIBILITY_HIDDEN SCEVComplexityCompare {
405 LoopInfo *LI;
406 public:
407 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
408
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000409 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000410 // Primarily, sort the SCEVs by their getSCEVType().
411 if (LHS->getSCEVType() != RHS->getSCEVType())
412 return LHS->getSCEVType() < RHS->getSCEVType();
413
414 // Aside from the getSCEVType() ordering, the particular ordering
415 // isn't very important except that it's beneficial to be consistent,
416 // so that (a + b) and (b + a) don't end up as different expressions.
417
418 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
419 // not as complete as it could be.
420 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
421 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
422
Dan Gohman5be18e82009-05-19 02:15:55 +0000423 // Order pointer values after integer values. This helps SCEVExpander
424 // form GEPs.
425 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
426 return false;
427 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
428 return true;
429
Dan Gohman72861302009-05-07 14:39:04 +0000430 // Compare getValueID values.
431 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
432 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
433
434 // Sort arguments by their position.
435 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
436 const Argument *RA = cast<Argument>(RU->getValue());
437 return LA->getArgNo() < RA->getArgNo();
438 }
439
440 // For instructions, compare their loop depth, and their opcode.
441 // This is pretty loose.
442 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
443 Instruction *RV = cast<Instruction>(RU->getValue());
444
445 // Compare loop depths.
446 if (LI->getLoopDepth(LV->getParent()) !=
447 LI->getLoopDepth(RV->getParent()))
448 return LI->getLoopDepth(LV->getParent()) <
449 LI->getLoopDepth(RV->getParent());
450
451 // Compare opcodes.
452 if (LV->getOpcode() != RV->getOpcode())
453 return LV->getOpcode() < RV->getOpcode();
454
455 // Compare the number of operands.
456 if (LV->getNumOperands() != RV->getNumOperands())
457 return LV->getNumOperands() < RV->getNumOperands();
458 }
459
460 return false;
461 }
462
Dan Gohman4dfad292009-06-14 22:51:25 +0000463 // Compare constant values.
464 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
465 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
466 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
467 }
468
469 // Compare addrec loop depths.
470 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
471 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
472 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
473 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
474 }
Dan Gohman72861302009-05-07 14:39:04 +0000475
476 // Lexicographically compare n-ary expressions.
477 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
478 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
479 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
480 if (i >= RC->getNumOperands())
481 return false;
482 if (operator()(LC->getOperand(i), RC->getOperand(i)))
483 return true;
484 if (operator()(RC->getOperand(i), LC->getOperand(i)))
485 return false;
486 }
487 return LC->getNumOperands() < RC->getNumOperands();
488 }
489
Dan Gohmana6b35e22009-05-07 19:23:21 +0000490 // Lexicographically compare udiv expressions.
491 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
492 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
493 if (operator()(LC->getLHS(), RC->getLHS()))
494 return true;
495 if (operator()(RC->getLHS(), LC->getLHS()))
496 return false;
497 if (operator()(LC->getRHS(), RC->getRHS()))
498 return true;
499 if (operator()(RC->getRHS(), LC->getRHS()))
500 return false;
501 return false;
502 }
503
Dan Gohman72861302009-05-07 14:39:04 +0000504 // Compare cast expressions by operand.
505 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
506 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
507 return operator()(LC->getOperand(), RC->getOperand());
508 }
509
510 assert(0 && "Unknown SCEV kind!");
511 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000512 }
513 };
514}
515
516/// GroupByComplexity - Given a list of SCEV objects, order them by their
517/// complexity, and group objects of the same complexity together by value.
518/// When this routine is finished, we know that any duplicates in the vector are
519/// consecutive and that complexity is monotonically increasing.
520///
521/// Note that we go take special precautions to ensure that we get determinstic
522/// results from this routine. In other words, we don't want the results of
523/// this to depend on where the addresses of various SCEV objects happened to
524/// land in memory.
525///
Owen Anderson372b46c2009-06-22 21:39:50 +0000526static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000527 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000528 if (Ops.size() < 2) return; // Noop
529 if (Ops.size() == 2) {
530 // This is the common case, which also happens to be trivially simple.
531 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000532 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000533 std::swap(Ops[0], Ops[1]);
534 return;
535 }
536
537 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000538 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000539
540 // Now that we are sorted by complexity, group elements of the same
541 // complexity. Note that this is, at worst, N^2, but the vector is likely to
542 // be extremely short in practice. Note that we take this approach because we
543 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000544 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000545 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000546 unsigned Complexity = S->getSCEVType();
547
548 // If there are any objects of the same complexity and same value as this
549 // one, group them.
550 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
551 if (Ops[j] == S) { // Found a duplicate.
552 // Move it to immediately after i'th element.
553 std::swap(Ops[i+1], Ops[j]);
554 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000555 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000556 }
557 }
558 }
559}
560
Chris Lattner53e677a2004-04-02 20:23:17 +0000561
Chris Lattner53e677a2004-04-02 20:23:17 +0000562
563//===----------------------------------------------------------------------===//
564// Simple SCEV method implementations
565//===----------------------------------------------------------------------===//
566
Eli Friedmanb42a6262008-08-04 23:49:06 +0000567/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000568/// Assume, K > 0.
Owen Anderson372b46c2009-06-22 21:39:50 +0000569static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000570 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000571 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000572 // Handle the simplest case efficiently.
573 if (K == 1)
574 return SE.getTruncateOrZeroExtend(It, ResultTy);
575
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000576 // We are using the following formula for BC(It, K):
577 //
578 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
579 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000580 // Suppose, W is the bitwidth of the return value. We must be prepared for
581 // overflow. Hence, we must assure that the result of our computation is
582 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
583 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000584 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000585 // However, this code doesn't use exactly that formula; the formula it uses
586 // is something like the following, where T is the number of factors of 2 in
587 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
588 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000589 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000590 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000591 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000592 // This formula is trivially equivalent to the previous formula. However,
593 // this formula can be implemented much more efficiently. The trick is that
594 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
595 // arithmetic. To do exact division in modular arithmetic, all we have
596 // to do is multiply by the inverse. Therefore, this step can be done at
597 // width W.
598 //
599 // The next issue is how to safely do the division by 2^T. The way this
600 // is done is by doing the multiplication step at a width of at least W + T
601 // bits. This way, the bottom W+T bits of the product are accurate. Then,
602 // when we perform the division by 2^T (which is equivalent to a right shift
603 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
604 // truncated out after the division by 2^T.
605 //
606 // In comparison to just directly using the first formula, this technique
607 // is much more efficient; using the first formula requires W * K bits,
608 // but this formula less than W + K bits. Also, the first formula requires
609 // a division step, whereas this formula only requires multiplies and shifts.
610 //
611 // It doesn't matter whether the subtraction step is done in the calculation
612 // width or the input iteration count's width; if the subtraction overflows,
613 // the result must be zero anyway. We prefer here to do it in the width of
614 // the induction variable because it helps a lot for certain cases; CodeGen
615 // isn't smart enough to ignore the overflow, which leads to much less
616 // efficient code if the width of the subtraction is wider than the native
617 // register width.
618 //
619 // (It's possible to not widen at all by pulling out factors of 2 before
620 // the multiplication; for example, K=2 can be calculated as
621 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
622 // extra arithmetic, so it's not an obvious win, and it gets
623 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000624
Eli Friedmanb42a6262008-08-04 23:49:06 +0000625 // Protection from insane SCEVs; this bound is conservative,
626 // but it probably doesn't matter.
627 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000628 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000629
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000630 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000631
Eli Friedmanb42a6262008-08-04 23:49:06 +0000632 // Calculate K! / 2^T and T; we divide out the factors of two before
633 // multiplying for calculating K! / 2^T to avoid overflow.
634 // Other overflow doesn't matter because we only care about the bottom
635 // W bits of the result.
636 APInt OddFactorial(W, 1);
637 unsigned T = 1;
638 for (unsigned i = 3; i <= K; ++i) {
639 APInt Mult(W, i);
640 unsigned TwoFactors = Mult.countTrailingZeros();
641 T += TwoFactors;
642 Mult = Mult.lshr(TwoFactors);
643 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000644 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000645
Eli Friedmanb42a6262008-08-04 23:49:06 +0000646 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000647 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000648
649 // Calcuate 2^T, at width T+W.
650 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
651
652 // Calculate the multiplicative inverse of K! / 2^T;
653 // this multiplication factor will perform the exact division by
654 // K! / 2^T.
655 APInt Mod = APInt::getSignedMinValue(W+1);
656 APInt MultiplyFactor = OddFactorial.zext(W+1);
657 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
658 MultiplyFactor = MultiplyFactor.trunc(W);
659
660 // Calculate the product, at width T+W
661 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Owen Anderson372b46c2009-06-22 21:39:50 +0000662 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000663 for (unsigned i = 1; i != K; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000664 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000665 Dividend = SE.getMulExpr(Dividend,
666 SE.getTruncateOrZeroExtend(S, CalculationTy));
667 }
668
669 // Divide by 2^T
Owen Anderson372b46c2009-06-22 21:39:50 +0000670 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000671
672 // Truncate the result, and divide by K! / 2^T.
673
674 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
675 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000676}
677
Chris Lattner53e677a2004-04-02 20:23:17 +0000678/// evaluateAtIteration - Return the value of this chain of recurrences at
679/// the specified iteration number. We can evaluate this recurrence by
680/// multiplying each element in the chain by the binomial coefficient
681/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
682///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000683/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000684///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000685/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000686///
Owen Anderson372b46c2009-06-22 21:39:50 +0000687const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It,
Dan Gohman246b2562007-10-22 18:31:58 +0000688 ScalarEvolution &SE) const {
Owen Anderson372b46c2009-06-22 21:39:50 +0000689 const SCEV* Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000690 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000691 // The computation is correct in the face of overflow provided that the
692 // multiplication is performed _after_ the evaluation of the binomial
693 // coefficient.
Owen Anderson372b46c2009-06-22 21:39:50 +0000694 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000695 if (isa<SCEVCouldNotCompute>(Coeff))
696 return Coeff;
697
698 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000699 }
700 return Result;
701}
702
Chris Lattner53e677a2004-04-02 20:23:17 +0000703//===----------------------------------------------------------------------===//
704// SCEV Expression folder implementations
705//===----------------------------------------------------------------------===//
706
Owen Anderson372b46c2009-06-22 21:39:50 +0000707const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op,
Dan Gohman99243b32009-05-01 16:44:56 +0000708 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000709 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000710 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000711 assert(isSCEVable(Ty) &&
712 "This is not a conversion to a SCEVable type!");
713 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000714
Dan Gohman622ed672009-05-04 22:02:23 +0000715 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000716 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000717 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000718
Dan Gohman20900ca2009-04-22 16:20:48 +0000719 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000720 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000721 return getTruncateExpr(ST->getOperand(), Ty);
722
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000723 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000724 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000725 return getTruncateOrSignExtend(SS->getOperand(), Ty);
726
727 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000728 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000729 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
730
Dan Gohman6864db62009-06-18 16:24:47 +0000731 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000732 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000733 SmallVector<const SCEV*, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000734 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000735 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
736 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000737 }
738
Owen Anderson08367b62009-06-22 18:25:46 +0000739 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
Owen Anderson753ad612009-06-22 21:57:23 +0000740 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000741 return Result;
742}
743
Owen Anderson372b46c2009-06-22 21:39:50 +0000744const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op,
Dan Gohman8170a682009-04-16 19:25:55 +0000745 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000746 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000747 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000748 assert(isSCEVable(Ty) &&
749 "This is not a conversion to a SCEVable type!");
750 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000751
Dan Gohman622ed672009-05-04 22:02:23 +0000752 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000753 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000754 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
755 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
756 return getUnknown(C);
757 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000758
Dan Gohman20900ca2009-04-22 16:20:48 +0000759 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000760 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000761 return getZeroExtendExpr(SZ->getOperand(), Ty);
762
Dan Gohman01ecca22009-04-27 20:16:15 +0000763 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000764 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000765 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000766 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000767 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000768 if (AR->isAffine()) {
769 // Check whether the backedge-taken count is SCEVCouldNotCompute.
770 // Note that this serves two purposes: It filters out loops that are
771 // simply not analyzable, and it covers the case where this code is
772 // being called from within backedge-taken count analysis, such that
773 // attempting to ask for the backedge-taken count would likely result
774 // in infinite recursion. In the later case, the analysis code will
775 // cope with a conservative value, and it will take care to purge
776 // that value once it has finished.
Owen Anderson372b46c2009-06-22 21:39:50 +0000777 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmana1af7572009-04-30 20:47:05 +0000778 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000779 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000780 // overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000781 const SCEV* Start = AR->getStart();
782 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohman01ecca22009-04-27 20:16:15 +0000783
784 // Check whether the backedge-taken count can be losslessly casted to
785 // the addrec's type. The count is always unsigned.
Owen Anderson372b46c2009-06-22 21:39:50 +0000786 const SCEV* CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000787 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +0000788 const SCEV* RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000789 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
790 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000791 const Type *WideTy =
792 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000793 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000794 const SCEV* ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000795 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000796 getTruncateOrZeroExtend(Step, Start->getType()));
Owen Anderson372b46c2009-06-22 21:39:50 +0000797 const SCEV* Add = getAddExpr(Start, ZMul);
798 const SCEV* OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000799 getAddExpr(getZeroExtendExpr(Start, WideTy),
800 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
801 getZeroExtendExpr(Step, WideTy)));
802 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000803 // Return the expression with the addrec on the outside.
804 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
805 getZeroExtendExpr(Step, Ty),
806 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000807
808 // Similar to above, only this time treat the step value as signed.
809 // This covers loops that count down.
Owen Anderson372b46c2009-06-22 21:39:50 +0000810 const SCEV* SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000811 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000812 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000813 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000814 OperandExtendedAdd =
815 getAddExpr(getZeroExtendExpr(Start, WideTy),
816 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
817 getSignExtendExpr(Step, WideTy)));
818 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000819 // Return the expression with the addrec on the outside.
820 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
821 getSignExtendExpr(Step, Ty),
822 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000823 }
824 }
825 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000826
Owen Anderson08367b62009-06-22 18:25:46 +0000827 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
Owen Anderson753ad612009-06-22 21:57:23 +0000828 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000829 return Result;
830}
831
Owen Anderson372b46c2009-06-22 21:39:50 +0000832const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op,
Dan Gohman01ecca22009-04-27 20:16:15 +0000833 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000834 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000835 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000836 assert(isSCEVable(Ty) &&
837 "This is not a conversion to a SCEVable type!");
838 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000839
Dan Gohman622ed672009-05-04 22:02:23 +0000840 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000841 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000842 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
843 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
844 return getUnknown(C);
845 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000846
Dan Gohman20900ca2009-04-22 16:20:48 +0000847 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000848 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000849 return getSignExtendExpr(SS->getOperand(), Ty);
850
Dan Gohman01ecca22009-04-27 20:16:15 +0000851 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000852 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000853 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000854 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000855 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000856 if (AR->isAffine()) {
857 // Check whether the backedge-taken count is SCEVCouldNotCompute.
858 // Note that this serves two purposes: It filters out loops that are
859 // simply not analyzable, and it covers the case where this code is
860 // being called from within backedge-taken count analysis, such that
861 // attempting to ask for the backedge-taken count would likely result
862 // in infinite recursion. In the later case, the analysis code will
863 // cope with a conservative value, and it will take care to purge
864 // that value once it has finished.
Owen Anderson372b46c2009-06-22 21:39:50 +0000865 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmana1af7572009-04-30 20:47:05 +0000866 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000867 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000868 // overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000869 const SCEV* Start = AR->getStart();
870 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohman01ecca22009-04-27 20:16:15 +0000871
872 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000873 // the addrec's type. The count is always unsigned.
Owen Anderson372b46c2009-06-22 21:39:50 +0000874 const SCEV* CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000875 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +0000876 const SCEV* RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000877 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
878 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000879 const Type *WideTy =
880 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000881 // Check whether Start+Step*MaxBECount has no signed overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000882 const SCEV* SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000883 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000884 getTruncateOrSignExtend(Step, Start->getType()));
Owen Anderson372b46c2009-06-22 21:39:50 +0000885 const SCEV* Add = getAddExpr(Start, SMul);
886 const SCEV* OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000887 getAddExpr(getSignExtendExpr(Start, WideTy),
888 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
889 getSignExtendExpr(Step, WideTy)));
890 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000891 // Return the expression with the addrec on the outside.
892 return getAddRecExpr(getSignExtendExpr(Start, Ty),
893 getSignExtendExpr(Step, Ty),
894 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000895 }
896 }
897 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000898
Owen Anderson08367b62009-06-22 18:25:46 +0000899 SCEVSignExtendExpr *&Result = SCEVSignExtends[std::make_pair(Op, Ty)];
Owen Anderson753ad612009-06-22 21:57:23 +0000900 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
Dan Gohmand19534a2007-06-15 14:38:12 +0000901 return Result;
902}
903
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000904/// getAnyExtendExpr - Return a SCEV for the given operand extended with
905/// unspecified bits out to the given type.
906///
Owen Anderson372b46c2009-06-22 21:39:50 +0000907const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op,
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000908 const Type *Ty) {
909 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
910 "This is not an extending conversion!");
911 assert(isSCEVable(Ty) &&
912 "This is not a conversion to a SCEVable type!");
913 Ty = getEffectiveSCEVType(Ty);
914
915 // Sign-extend negative constants.
916 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
917 if (SC->getValue()->getValue().isNegative())
918 return getSignExtendExpr(Op, Ty);
919
920 // Peel off a truncate cast.
921 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000922 const SCEV* NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000923 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
924 return getAnyExtendExpr(NewOp, Ty);
925 return getTruncateOrNoop(NewOp, Ty);
926 }
927
928 // Next try a zext cast. If the cast is folded, use it.
Owen Anderson372b46c2009-06-22 21:39:50 +0000929 const SCEV* ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000930 if (!isa<SCEVZeroExtendExpr>(ZExt))
931 return ZExt;
932
933 // Next try a sext cast. If the cast is folded, use it.
Owen Anderson372b46c2009-06-22 21:39:50 +0000934 const SCEV* SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000935 if (!isa<SCEVSignExtendExpr>(SExt))
936 return SExt;
937
938 // If the expression is obviously signed, use the sext cast value.
939 if (isa<SCEVSMaxExpr>(Op))
940 return SExt;
941
942 // Absent any other information, use the zext cast value.
943 return ZExt;
944}
945
Dan Gohmanbd59d7b2009-06-14 22:58:51 +0000946/// CollectAddOperandsWithScales - Process the given Ops list, which is
947/// a list of operands to be added under the given scale, update the given
948/// map. This is a helper function for getAddRecExpr. As an example of
949/// what it does, given a sequence of operands that would form an add
950/// expression like this:
951///
952/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
953///
954/// where A and B are constants, update the map with these values:
955///
956/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
957///
958/// and add 13 + A*B*29 to AccumulatedConstant.
959/// This will allow getAddRecExpr to produce this:
960///
961/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
962///
963/// This form often exposes folding opportunities that are hidden in
964/// the original operand list.
965///
966/// Return true iff it appears that any interesting folding opportunities
967/// may be exposed. This helps getAddRecExpr short-circuit extra work in
968/// the common case where no interesting opportunities are present, and
969/// is also used as a check to avoid infinite recursion.
970///
971static bool
Owen Anderson372b46c2009-06-22 21:39:50 +0000972CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M,
973 SmallVector<const SCEV*, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +0000974 APInt &AccumulatedConstant,
Owen Anderson372b46c2009-06-22 21:39:50 +0000975 const SmallVectorImpl<const SCEV*> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +0000976 const APInt &Scale,
977 ScalarEvolution &SE) {
978 bool Interesting = false;
979
980 // Iterate over the add operands.
981 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
982 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
983 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
984 APInt NewScale =
985 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
986 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
987 // A multiplication of a constant with another add; recurse.
988 Interesting |=
989 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
990 cast<SCEVAddExpr>(Mul->getOperand(1))
991 ->getOperands(),
992 NewScale, SE);
993 } else {
994 // A multiplication of a constant with some other value. Update
995 // the map.
Owen Anderson372b46c2009-06-22 21:39:50 +0000996 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
997 const SCEV* Key = SE.getMulExpr(MulOps);
998 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohmanbd59d7b2009-06-14 22:58:51 +0000999 M.insert(std::make_pair(Key, APInt()));
1000 if (Pair.second) {
1001 Pair.first->second = NewScale;
1002 NewOps.push_back(Pair.first->first);
1003 } else {
1004 Pair.first->second += NewScale;
1005 // The map already had an entry for this value, which may indicate
1006 // a folding opportunity.
1007 Interesting = true;
1008 }
1009 }
1010 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1011 // Pull a buried constant out to the outside.
1012 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1013 Interesting = true;
1014 AccumulatedConstant += Scale * C->getValue()->getValue();
1015 } else {
1016 // An ordinary operand. Update the map.
Owen Anderson372b46c2009-06-22 21:39:50 +00001017 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001018 M.insert(std::make_pair(Ops[i], APInt()));
1019 if (Pair.second) {
1020 Pair.first->second = Scale;
1021 NewOps.push_back(Pair.first->first);
1022 } else {
1023 Pair.first->second += Scale;
1024 // The map already had an entry for this value, which may indicate
1025 // a folding opportunity.
1026 Interesting = true;
1027 }
1028 }
1029 }
1030
1031 return Interesting;
1032}
1033
1034namespace {
1035 struct APIntCompare {
1036 bool operator()(const APInt &LHS, const APInt &RHS) const {
1037 return LHS.ult(RHS);
1038 }
1039 };
1040}
1041
Dan Gohman6c0866c2009-05-24 23:45:28 +00001042/// getAddExpr - Get a canonical add expression, or something simpler if
1043/// possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001044const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001045 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001046 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001047#ifndef NDEBUG
1048 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1049 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1050 getEffectiveSCEVType(Ops[0]->getType()) &&
1051 "SCEVAddExpr operand types don't match!");
1052#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001053
1054 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001055 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001056
1057 // If there are any constants, fold them together.
1058 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001059 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001060 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001061 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001062 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001063 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001064 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1065 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001066 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001067 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001068 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001069 }
1070
1071 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001072 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001073 Ops.erase(Ops.begin());
1074 --Idx;
1075 }
1076 }
1077
Chris Lattner627018b2004-04-07 16:16:11 +00001078 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001079
Chris Lattner53e677a2004-04-02 20:23:17 +00001080 // Okay, check to see if the same value occurs in the operand list twice. If
1081 // so, merge them together into an multiply expression. Since we sorted the
1082 // list, these values are required to be adjacent.
1083 const Type *Ty = Ops[0]->getType();
1084 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1085 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1086 // Found a match, merge the two values into a multiply, and add any
1087 // remaining values to the result.
Owen Anderson372b46c2009-06-22 21:39:50 +00001088 const SCEV* Two = getIntegerSCEV(2, Ty);
1089 const SCEV* Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001090 if (Ops.size() == 2)
1091 return Mul;
1092 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1093 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001094 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001095 }
1096
Dan Gohman728c7f32009-05-08 21:03:19 +00001097 // Check for truncates. If all the operands are truncated from the same
1098 // type, see if factoring out the truncate would permit the result to be
1099 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1100 // if the contents of the resulting outer trunc fold to something simple.
1101 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1102 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1103 const Type *DstType = Trunc->getType();
1104 const Type *SrcType = Trunc->getOperand()->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00001105 SmallVector<const SCEV*, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001106 bool Ok = true;
1107 // Check all the operands to see if they can be represented in the
1108 // source type of the truncate.
1109 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1110 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1111 if (T->getOperand()->getType() != SrcType) {
1112 Ok = false;
1113 break;
1114 }
1115 LargeOps.push_back(T->getOperand());
1116 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1117 // This could be either sign or zero extension, but sign extension
1118 // is much more likely to be foldable here.
1119 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1120 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001121 SmallVector<const SCEV*, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001122 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1123 if (const SCEVTruncateExpr *T =
1124 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1125 if (T->getOperand()->getType() != SrcType) {
1126 Ok = false;
1127 break;
1128 }
1129 LargeMulOps.push_back(T->getOperand());
1130 } else if (const SCEVConstant *C =
1131 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1132 // This could be either sign or zero extension, but sign extension
1133 // is much more likely to be foldable here.
1134 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1135 } else {
1136 Ok = false;
1137 break;
1138 }
1139 }
1140 if (Ok)
1141 LargeOps.push_back(getMulExpr(LargeMulOps));
1142 } else {
1143 Ok = false;
1144 break;
1145 }
1146 }
1147 if (Ok) {
1148 // Evaluate the expression in the larger type.
Owen Anderson372b46c2009-06-22 21:39:50 +00001149 const SCEV* Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001150 // If it folds to something simple, use it. Otherwise, don't.
1151 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1152 return getTruncateExpr(Fold, DstType);
1153 }
1154 }
1155
1156 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001157 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1158 ++Idx;
1159
1160 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001161 if (Idx < Ops.size()) {
1162 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001163 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001164 // If we have an add, expand the add operands onto the end of the operands
1165 // list.
1166 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1167 Ops.erase(Ops.begin()+Idx);
1168 DeletedAdd = true;
1169 }
1170
1171 // If we deleted at least one add, we added operands to the end of the list,
1172 // and they are not necessarily sorted. Recurse to resort and resimplify
1173 // any operands we just aquired.
1174 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001175 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001176 }
1177
1178 // Skip over the add expression until we get to a multiply.
1179 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1180 ++Idx;
1181
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001182 // Check to see if there are any folding opportunities present with
1183 // operands multiplied by constant values.
1184 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1185 uint64_t BitWidth = getTypeSizeInBits(Ty);
Owen Anderson372b46c2009-06-22 21:39:50 +00001186 DenseMap<const SCEV*, APInt> M;
1187 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001188 APInt AccumulatedConstant(BitWidth, 0);
1189 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1190 Ops, APInt(BitWidth, 1), *this)) {
1191 // Some interesting folding opportunity is present, so its worthwhile to
1192 // re-generate the operands list. Group the operands by constant scale,
1193 // to avoid multiplying by the same constant scale multiple times.
Owen Anderson372b46c2009-06-22 21:39:50 +00001194 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1195 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001196 E = NewOps.end(); I != E; ++I)
1197 MulOpLists[M.find(*I)->second].push_back(*I);
1198 // Re-generate the operands list.
1199 Ops.clear();
1200 if (AccumulatedConstant != 0)
1201 Ops.push_back(getConstant(AccumulatedConstant));
Owen Anderson372b46c2009-06-22 21:39:50 +00001202 for (std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare>::iterator I =
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001203 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1204 if (I->first != 0)
1205 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1206 if (Ops.empty())
1207 return getIntegerSCEV(0, Ty);
1208 if (Ops.size() == 1)
1209 return Ops[0];
1210 return getAddExpr(Ops);
1211 }
1212 }
1213
Chris Lattner53e677a2004-04-02 20:23:17 +00001214 // If we are adding something to a multiply expression, make sure the
1215 // something is not already an operand of the multiply. If so, merge it into
1216 // the multiply.
1217 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001218 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001219 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001220 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001221 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001222 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001223 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Owen Anderson372b46c2009-06-22 21:39:50 +00001224 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001225 if (Mul->getNumOperands() != 2) {
1226 // If the multiply has more than two operands, we must get the
1227 // Y*Z term.
Owen Anderson372b46c2009-06-22 21:39:50 +00001228 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001229 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001230 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001231 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001232 const SCEV* One = getIntegerSCEV(1, Ty);
1233 const SCEV* AddOne = getAddExpr(InnerMul, One);
1234 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001235 if (Ops.size() == 2) return OuterMul;
1236 if (AddOp < Idx) {
1237 Ops.erase(Ops.begin()+AddOp);
1238 Ops.erase(Ops.begin()+Idx-1);
1239 } else {
1240 Ops.erase(Ops.begin()+Idx);
1241 Ops.erase(Ops.begin()+AddOp-1);
1242 }
1243 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001244 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001245 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001246
Chris Lattner53e677a2004-04-02 20:23:17 +00001247 // Check this multiply against other multiplies being added together.
1248 for (unsigned OtherMulIdx = Idx+1;
1249 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1250 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001251 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001252 // If MulOp occurs in OtherMul, we can fold the two multiplies
1253 // together.
1254 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1255 OMulOp != e; ++OMulOp)
1256 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1257 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Owen Anderson372b46c2009-06-22 21:39:50 +00001258 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001259 if (Mul->getNumOperands() != 2) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001260 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001261 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001262 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001263 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001264 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001265 if (OtherMul->getNumOperands() != 2) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001266 SmallVector<const SCEV*, 4> MulOps(OtherMul->op_begin(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001267 OtherMul->op_end());
1268 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001269 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001270 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001271 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1272 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001273 if (Ops.size() == 2) return OuterMul;
1274 Ops.erase(Ops.begin()+Idx);
1275 Ops.erase(Ops.begin()+OtherMulIdx-1);
1276 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001277 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001278 }
1279 }
1280 }
1281 }
1282
1283 // If there are any add recurrences in the operands list, see if any other
1284 // added values are loop invariant. If so, we can fold them into the
1285 // recurrence.
1286 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1287 ++Idx;
1288
1289 // Scan over all recurrences, trying to fold loop invariants into them.
1290 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1291 // Scan all of the other operands to this add and add them to the vector if
1292 // they are loop invariant w.r.t. the recurrence.
Owen Anderson372b46c2009-06-22 21:39:50 +00001293 SmallVector<const SCEV*, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001294 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001295 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1296 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1297 LIOps.push_back(Ops[i]);
1298 Ops.erase(Ops.begin()+i);
1299 --i; --e;
1300 }
1301
1302 // If we found some loop invariants, fold them into the recurrence.
1303 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001304 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001305 LIOps.push_back(AddRec->getStart());
1306
Owen Anderson372b46c2009-06-22 21:39:50 +00001307 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001308 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001309 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001310
Owen Anderson372b46c2009-06-22 21:39:50 +00001311 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001312 // If all of the other operands were loop invariant, we are done.
1313 if (Ops.size() == 1) return NewRec;
1314
1315 // Otherwise, add the folded AddRec by the non-liv parts.
1316 for (unsigned i = 0;; ++i)
1317 if (Ops[i] == AddRec) {
1318 Ops[i] = NewRec;
1319 break;
1320 }
Dan Gohman246b2562007-10-22 18:31:58 +00001321 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001322 }
1323
1324 // Okay, if there weren't any loop invariants to be folded, check to see if
1325 // there are multiple AddRec's with the same loop induction variable being
1326 // added together. If so, we can fold them.
1327 for (unsigned OtherIdx = Idx+1;
1328 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1329 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001330 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001331 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1332 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Owen Anderson372b46c2009-06-22 21:39:50 +00001333 SmallVector<const SCEV*, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001334 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1335 if (i >= NewOps.size()) {
1336 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1337 OtherAddRec->op_end());
1338 break;
1339 }
Dan Gohman246b2562007-10-22 18:31:58 +00001340 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001341 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001342 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001343
1344 if (Ops.size() == 2) return NewAddRec;
1345
1346 Ops.erase(Ops.begin()+Idx);
1347 Ops.erase(Ops.begin()+OtherIdx-1);
1348 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001349 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001350 }
1351 }
1352
1353 // Otherwise couldn't fold anything into this recurrence. Move onto the
1354 // next one.
1355 }
1356
1357 // Okay, it looks like we really DO need an add expr. Check to see if we
1358 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001359 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001360 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
Chris Lattnerb3364092006-10-04 21:49:37 +00001361 SCEVOps)];
Owen Anderson753ad612009-06-22 21:57:23 +00001362 if (Result == 0) Result = new SCEVAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001363 return Result;
1364}
1365
1366
Dan Gohman6c0866c2009-05-24 23:45:28 +00001367/// getMulExpr - Get a canonical multiply expression, or something simpler if
1368/// possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001369const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001370 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001371#ifndef NDEBUG
1372 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1373 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1374 getEffectiveSCEVType(Ops[0]->getType()) &&
1375 "SCEVMulExpr operand types don't match!");
1376#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001377
1378 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001379 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001380
1381 // If there are any constants, fold them together.
1382 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001383 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001384
1385 // C1*(C2+V) -> C1*C2 + C1*V
1386 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001387 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001388 if (Add->getNumOperands() == 2 &&
1389 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001390 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1391 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001392
1393
1394 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001395 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001397 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1398 RHSC->getValue()->getValue());
1399 Ops[0] = getConstant(Fold);
1400 Ops.erase(Ops.begin()+1); // Erase the folded element
1401 if (Ops.size() == 1) return Ops[0];
1402 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001403 }
1404
1405 // If we are left with a constant one being multiplied, strip it off.
1406 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1407 Ops.erase(Ops.begin());
1408 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001409 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001410 // If we have a multiply of zero, it will always be zero.
1411 return Ops[0];
1412 }
1413 }
1414
1415 // Skip over the add expression until we get to a multiply.
1416 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1417 ++Idx;
1418
1419 if (Ops.size() == 1)
1420 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001421
Chris Lattner53e677a2004-04-02 20:23:17 +00001422 // If there are mul operands inline them all into this expression.
1423 if (Idx < Ops.size()) {
1424 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001425 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001426 // If we have an mul, expand the mul operands onto the end of the operands
1427 // list.
1428 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1429 Ops.erase(Ops.begin()+Idx);
1430 DeletedMul = true;
1431 }
1432
1433 // If we deleted at least one mul, we added operands to the end of the list,
1434 // and they are not necessarily sorted. Recurse to resort and resimplify
1435 // any operands we just aquired.
1436 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001437 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001438 }
1439
1440 // If there are any add recurrences in the operands list, see if any other
1441 // added values are loop invariant. If so, we can fold them into the
1442 // recurrence.
1443 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1444 ++Idx;
1445
1446 // Scan over all recurrences, trying to fold loop invariants into them.
1447 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1448 // Scan all of the other operands to this mul and add them to the vector if
1449 // they are loop invariant w.r.t. the recurrence.
Owen Anderson372b46c2009-06-22 21:39:50 +00001450 SmallVector<const SCEV*, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001451 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001452 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1453 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1454 LIOps.push_back(Ops[i]);
1455 Ops.erase(Ops.begin()+i);
1456 --i; --e;
1457 }
1458
1459 // If we found some loop invariants, fold them into the recurrence.
1460 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001461 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Owen Anderson372b46c2009-06-22 21:39:50 +00001462 SmallVector<const SCEV*, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001463 NewOps.reserve(AddRec->getNumOperands());
1464 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001465 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001466 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001467 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 } else {
1469 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001470 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001471 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001472 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001473 }
1474 }
1475
Owen Anderson372b46c2009-06-22 21:39:50 +00001476 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001477
1478 // If all of the other operands were loop invariant, we are done.
1479 if (Ops.size() == 1) return NewRec;
1480
1481 // Otherwise, multiply the folded AddRec by the non-liv parts.
1482 for (unsigned i = 0;; ++i)
1483 if (Ops[i] == AddRec) {
1484 Ops[i] = NewRec;
1485 break;
1486 }
Dan Gohman246b2562007-10-22 18:31:58 +00001487 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001488 }
1489
1490 // Okay, if there weren't any loop invariants to be folded, check to see if
1491 // there are multiple AddRec's with the same loop induction variable being
1492 // multiplied together. If so, we can fold them.
1493 for (unsigned OtherIdx = Idx+1;
1494 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1495 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001496 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001497 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1498 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001499 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Owen Anderson372b46c2009-06-22 21:39:50 +00001500 const SCEV* NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001501 G->getStart());
Owen Anderson372b46c2009-06-22 21:39:50 +00001502 const SCEV* B = F->getStepRecurrence(*this);
1503 const SCEV* D = G->getStepRecurrence(*this);
1504 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001505 getMulExpr(G, B),
1506 getMulExpr(B, D));
Owen Anderson372b46c2009-06-22 21:39:50 +00001507 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001508 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001509 if (Ops.size() == 2) return NewAddRec;
1510
1511 Ops.erase(Ops.begin()+Idx);
1512 Ops.erase(Ops.begin()+OtherIdx-1);
1513 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001514 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001515 }
1516 }
1517
1518 // Otherwise couldn't fold anything into this recurrence. Move onto the
1519 // next one.
1520 }
1521
1522 // Okay, it looks like we really DO need an mul expr. Check to see if we
1523 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001524 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001525 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
Chris Lattnerb3364092006-10-04 21:49:37 +00001526 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001527 if (Result == 0)
Owen Anderson753ad612009-06-22 21:57:23 +00001528 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001529 return Result;
1530}
1531
Dan Gohman6c0866c2009-05-24 23:45:28 +00001532/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1533/// possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001534const SCEV* ScalarEvolution::getUDivExpr(const SCEV* LHS,
1535 const SCEV* RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001536 assert(getEffectiveSCEVType(LHS->getType()) ==
1537 getEffectiveSCEVType(RHS->getType()) &&
1538 "SCEVUDivExpr operand types don't match!");
1539
Dan Gohman622ed672009-05-04 22:02:23 +00001540 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001541 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001542 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001543 if (RHSC->isZero())
1544 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001545
Dan Gohman185cf032009-05-08 20:18:49 +00001546 // Determine if the division can be folded into the operands of
1547 // its operands.
1548 // TODO: Generalize this to non-constants by using known-bits information.
1549 const Type *Ty = LHS->getType();
1550 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1551 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1552 // For non-power-of-two values, effectively round the value up to the
1553 // nearest power of two.
1554 if (!RHSC->getValue()->getValue().isPowerOf2())
1555 ++MaxShiftAmt;
1556 const IntegerType *ExtTy =
1557 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1558 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1559 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1560 if (const SCEVConstant *Step =
1561 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1562 if (!Step->getValue()->getValue()
1563 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001564 getZeroExtendExpr(AR, ExtTy) ==
1565 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1566 getZeroExtendExpr(Step, ExtTy),
1567 AR->getLoop())) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001568 SmallVector<const SCEV*, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001569 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1570 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1571 return getAddRecExpr(Operands, AR->getLoop());
1572 }
1573 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001574 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001575 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001576 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1577 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1578 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001579 // Find an operand that's safely divisible.
1580 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001581 const SCEV* Op = M->getOperand(i);
1582 const SCEV* Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001583 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001584 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1585 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001586 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001587 Operands[i] = Div;
1588 return getMulExpr(Operands);
1589 }
1590 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001591 }
Dan Gohman185cf032009-05-08 20:18:49 +00001592 // (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 +00001593 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001594 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001595 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1596 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1597 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1598 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001599 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001600 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001601 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1602 break;
1603 Operands.push_back(Op);
1604 }
1605 if (Operands.size() == A->getNumOperands())
1606 return getAddExpr(Operands);
1607 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001608 }
Dan Gohman185cf032009-05-08 20:18:49 +00001609
1610 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001611 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001612 Constant *LHSCV = LHSC->getValue();
1613 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001614 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001615 }
1616 }
1617
Owen Anderson08367b62009-06-22 18:25:46 +00001618 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
Owen Anderson753ad612009-06-22 21:57:23 +00001619 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 return Result;
1621}
1622
1623
Dan Gohman6c0866c2009-05-24 23:45:28 +00001624/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1625/// Simplify the expression as much as possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001626const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1627 const SCEV* Step, const Loop *L) {
1628 SmallVector<const SCEV*, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001629 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001630 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001631 if (StepChrec->getLoop() == L) {
1632 Operands.insert(Operands.end(), StepChrec->op_begin(),
1633 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001634 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001635 }
1636
1637 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001638 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001639}
1640
Dan Gohman6c0866c2009-05-24 23:45:28 +00001641/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1642/// Simplify the expression as much as possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001643const SCEV* ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001644 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001645 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001646#ifndef NDEBUG
1647 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1648 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1649 getEffectiveSCEVType(Operands[0]->getType()) &&
1650 "SCEVAddRecExpr operand types don't match!");
1651#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001652
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001653 if (Operands.back()->isZero()) {
1654 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001655 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001656 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001657
Dan Gohmand9cc7492008-08-08 18:33:12 +00001658 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001659 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001660 const Loop* NestedLoop = NestedAR->getLoop();
1661 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001662 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001663 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001664 Operands[0] = NestedAR->getStart();
1665 NestedOperands[0] = getAddRecExpr(Operands, L);
1666 return getAddRecExpr(NestedOperands, NestedLoop);
1667 }
1668 }
1669
Dan Gohman35738ac2009-05-04 22:30:44 +00001670 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001671 SCEVAddRecExpr *&Result = SCEVAddRecExprs[std::make_pair(L, SCEVOps)];
Owen Anderson753ad612009-06-22 21:57:23 +00001672 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001673 return Result;
1674}
1675
Owen Anderson372b46c2009-06-22 21:39:50 +00001676const SCEV* ScalarEvolution::getSMaxExpr(const SCEV* LHS,
1677 const SCEV* RHS) {
1678 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001679 Ops.push_back(LHS);
1680 Ops.push_back(RHS);
1681 return getSMaxExpr(Ops);
1682}
1683
Owen Anderson372b46c2009-06-22 21:39:50 +00001684const SCEV*
1685ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001686 assert(!Ops.empty() && "Cannot get empty smax!");
1687 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001688#ifndef NDEBUG
1689 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1690 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1691 getEffectiveSCEVType(Ops[0]->getType()) &&
1692 "SCEVSMaxExpr operand types don't match!");
1693#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001694
1695 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001696 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001697
1698 // If there are any constants, fold them together.
1699 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001700 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001701 ++Idx;
1702 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001703 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001704 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001705 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001706 APIntOps::smax(LHSC->getValue()->getValue(),
1707 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001708 Ops[0] = getConstant(Fold);
1709 Ops.erase(Ops.begin()+1); // Erase the folded element
1710 if (Ops.size() == 1) return Ops[0];
1711 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001712 }
1713
1714 // If we are left with a constant -inf, strip it off.
1715 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1716 Ops.erase(Ops.begin());
1717 --Idx;
1718 }
1719 }
1720
1721 if (Ops.size() == 1) return Ops[0];
1722
1723 // Find the first SMax
1724 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1725 ++Idx;
1726
1727 // Check to see if one of the operands is an SMax. If so, expand its operands
1728 // onto our operand list, and recurse to simplify.
1729 if (Idx < Ops.size()) {
1730 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001731 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001732 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1733 Ops.erase(Ops.begin()+Idx);
1734 DeletedSMax = true;
1735 }
1736
1737 if (DeletedSMax)
1738 return getSMaxExpr(Ops);
1739 }
1740
1741 // Okay, check to see if the same value occurs in the operand list twice. If
1742 // so, delete one. Since we sorted the list, these values are required to
1743 // be adjacent.
1744 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1745 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1746 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1747 --i; --e;
1748 }
1749
1750 if (Ops.size() == 1) return Ops[0];
1751
1752 assert(!Ops.empty() && "Reduced smax down to nothing!");
1753
Nick Lewycky3e630762008-02-20 06:48:22 +00001754 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001755 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001756 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001757 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scSMaxExpr,
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001758 SCEVOps)];
Owen Anderson753ad612009-06-22 21:57:23 +00001759 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001760 return Result;
1761}
1762
Owen Anderson372b46c2009-06-22 21:39:50 +00001763const SCEV* ScalarEvolution::getUMaxExpr(const SCEV* LHS,
1764 const SCEV* RHS) {
1765 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001766 Ops.push_back(LHS);
1767 Ops.push_back(RHS);
1768 return getUMaxExpr(Ops);
1769}
1770
Owen Anderson372b46c2009-06-22 21:39:50 +00001771const SCEV*
1772ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001773 assert(!Ops.empty() && "Cannot get empty umax!");
1774 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001775#ifndef NDEBUG
1776 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1777 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1778 getEffectiveSCEVType(Ops[0]->getType()) &&
1779 "SCEVUMaxExpr operand types don't match!");
1780#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001781
1782 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001783 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001784
1785 // If there are any constants, fold them together.
1786 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001787 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001788 ++Idx;
1789 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001790 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001791 // We found two constants, fold them together!
1792 ConstantInt *Fold = ConstantInt::get(
1793 APIntOps::umax(LHSC->getValue()->getValue(),
1794 RHSC->getValue()->getValue()));
1795 Ops[0] = getConstant(Fold);
1796 Ops.erase(Ops.begin()+1); // Erase the folded element
1797 if (Ops.size() == 1) return Ops[0];
1798 LHSC = cast<SCEVConstant>(Ops[0]);
1799 }
1800
1801 // If we are left with a constant zero, strip it off.
1802 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1803 Ops.erase(Ops.begin());
1804 --Idx;
1805 }
1806 }
1807
1808 if (Ops.size() == 1) return Ops[0];
1809
1810 // Find the first UMax
1811 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1812 ++Idx;
1813
1814 // Check to see if one of the operands is a UMax. If so, expand its operands
1815 // onto our operand list, and recurse to simplify.
1816 if (Idx < Ops.size()) {
1817 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001818 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001819 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1820 Ops.erase(Ops.begin()+Idx);
1821 DeletedUMax = true;
1822 }
1823
1824 if (DeletedUMax)
1825 return getUMaxExpr(Ops);
1826 }
1827
1828 // Okay, check to see if the same value occurs in the operand list twice. If
1829 // so, delete one. Since we sorted the list, these values are required to
1830 // be adjacent.
1831 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1832 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1833 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1834 --i; --e;
1835 }
1836
1837 if (Ops.size() == 1) return Ops[0];
1838
1839 assert(!Ops.empty() && "Reduced umax down to nothing!");
1840
1841 // Okay, it looks like we really DO need a umax expr. Check to see if we
1842 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001843 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001844 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scUMaxExpr,
Nick Lewycky3e630762008-02-20 06:48:22 +00001845 SCEVOps)];
Owen Anderson753ad612009-06-22 21:57:23 +00001846 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
Nick Lewycky3e630762008-02-20 06:48:22 +00001847 return Result;
1848}
1849
Owen Anderson372b46c2009-06-22 21:39:50 +00001850const SCEV* ScalarEvolution::getSMinExpr(const SCEV* LHS,
1851 const SCEV* RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001852 // ~smax(~x, ~y) == smin(x, y).
1853 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1854}
1855
Owen Anderson372b46c2009-06-22 21:39:50 +00001856const SCEV* ScalarEvolution::getUMinExpr(const SCEV* LHS,
1857 const SCEV* RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001858 // ~umax(~x, ~y) == umin(x, y)
1859 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1860}
1861
Owen Anderson372b46c2009-06-22 21:39:50 +00001862const SCEV* ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001863 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001864 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001865 if (isa<ConstantPointerNull>(V))
1866 return getIntegerSCEV(0, V->getType());
Owen Anderson08367b62009-06-22 18:25:46 +00001867 SCEVUnknown *&Result = SCEVUnknowns[V];
Owen Anderson753ad612009-06-22 21:57:23 +00001868 if (Result == 0) Result = new SCEVUnknown(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001869 return Result;
1870}
1871
Chris Lattner53e677a2004-04-02 20:23:17 +00001872//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001873// Basic SCEV Analysis and PHI Idiom Recognition Code
1874//
1875
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001876/// isSCEVable - Test if values of the given type are analyzable within
1877/// the SCEV framework. This primarily includes integer types, and it
1878/// can optionally include pointer types if the ScalarEvolution class
1879/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001880bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001881 // Integers are always SCEVable.
1882 if (Ty->isInteger())
1883 return true;
1884
1885 // Pointers are SCEVable if TargetData information is available
1886 // to provide pointer size information.
1887 if (isa<PointerType>(Ty))
1888 return TD != NULL;
1889
1890 // Otherwise it's not SCEVable.
1891 return false;
1892}
1893
1894/// getTypeSizeInBits - Return the size in bits of the specified type,
1895/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001896uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001897 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1898
1899 // If we have a TargetData, use it!
1900 if (TD)
1901 return TD->getTypeSizeInBits(Ty);
1902
1903 // Otherwise, we support only integer types.
1904 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1905 return Ty->getPrimitiveSizeInBits();
1906}
1907
1908/// getEffectiveSCEVType - Return a type with the same bitwidth as
1909/// the given type and which represents how SCEV will treat the given
1910/// type, for which isSCEVable must return true. For pointer types,
1911/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001912const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001913 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1914
1915 if (Ty->isInteger())
1916 return Ty;
1917
1918 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1919 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001920}
Chris Lattner53e677a2004-04-02 20:23:17 +00001921
Owen Anderson372b46c2009-06-22 21:39:50 +00001922const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00001923 return CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001924}
1925
Dan Gohman92fa56e2009-05-04 22:20:30 +00001926/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00001927/// computed.
1928bool ScalarEvolution::hasSCEV(Value *V) const {
1929 return Scalars.count(V);
1930}
1931
Chris Lattner53e677a2004-04-02 20:23:17 +00001932/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1933/// expression and create a new one.
Owen Anderson372b46c2009-06-22 21:39:50 +00001934const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001935 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001936
Owen Anderson372b46c2009-06-22 21:39:50 +00001937 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001938 if (I != Scalars.end()) return I->second;
Owen Anderson372b46c2009-06-22 21:39:50 +00001939 const SCEV* S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00001940 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00001941 return S;
1942}
1943
Dan Gohman2d1be872009-04-16 03:18:22 +00001944/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1945/// specified signed integer value and return a SCEV for the constant.
Owen Anderson372b46c2009-06-22 21:39:50 +00001946const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001947 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001948 Constant *C;
1949 if (Val == 0)
1950 C = Constant::getNullValue(Ty);
1951 else if (Ty->isFloatingPoint())
1952 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1953 APFloat::IEEEdouble, Val));
1954 else
1955 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001956 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001957}
1958
1959/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1960///
Owen Anderson372b46c2009-06-22 21:39:50 +00001961const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001962 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001963 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001964
1965 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001966 Ty = getEffectiveSCEVType(Ty);
1967 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001968}
1969
1970/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Anderson372b46c2009-06-22 21:39:50 +00001971const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001972 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001973 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001974
1975 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001976 Ty = getEffectiveSCEVType(Ty);
Owen Anderson372b46c2009-06-22 21:39:50 +00001977 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001978 return getMinusSCEV(AllOnes, V);
1979}
1980
1981/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1982///
Owen Anderson372b46c2009-06-22 21:39:50 +00001983const SCEV* ScalarEvolution::getMinusSCEV(const SCEV* LHS,
1984 const SCEV* RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001985 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001986 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001987}
1988
1989/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1990/// input value to the specified type. If the type must be extended, it is zero
1991/// extended.
Owen Anderson372b46c2009-06-22 21:39:50 +00001992const SCEV*
1993ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001994 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001995 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001996 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1997 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001998 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001999 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002000 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002001 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002002 return getTruncateExpr(V, Ty);
2003 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002004}
2005
2006/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2007/// input value to the specified type. If the type must be extended, it is sign
2008/// extended.
Owen Anderson372b46c2009-06-22 21:39:50 +00002009const SCEV*
2010ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002011 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002012 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002013 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2014 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002015 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002016 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002017 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002018 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002019 return getTruncateExpr(V, Ty);
2020 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002021}
2022
Dan Gohman467c4302009-05-13 03:46:30 +00002023/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2024/// input value to the specified type. If the type must be extended, it is zero
2025/// extended. The conversion must not be narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002026const SCEV*
2027ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002028 const Type *SrcTy = V->getType();
2029 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2030 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2031 "Cannot noop or zero extend with non-integer arguments!");
2032 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2033 "getNoopOrZeroExtend cannot truncate!");
2034 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2035 return V; // No conversion
2036 return getZeroExtendExpr(V, Ty);
2037}
2038
2039/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2040/// input value to the specified type. If the type must be extended, it is sign
2041/// extended. The conversion must not be narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002042const SCEV*
2043ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002044 const Type *SrcTy = V->getType();
2045 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2046 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2047 "Cannot noop or sign extend with non-integer arguments!");
2048 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2049 "getNoopOrSignExtend cannot truncate!");
2050 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2051 return V; // No conversion
2052 return getSignExtendExpr(V, Ty);
2053}
2054
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002055/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2056/// the input value to the specified type. If the type must be extended,
2057/// it is extended with unspecified bits. The conversion must not be
2058/// narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002059const SCEV*
2060ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002061 const Type *SrcTy = V->getType();
2062 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2063 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2064 "Cannot noop or any extend with non-integer arguments!");
2065 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2066 "getNoopOrAnyExtend cannot truncate!");
2067 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2068 return V; // No conversion
2069 return getAnyExtendExpr(V, Ty);
2070}
2071
Dan Gohman467c4302009-05-13 03:46:30 +00002072/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2073/// input value to the specified type. The conversion must not be widening.
Owen Anderson372b46c2009-06-22 21:39:50 +00002074const SCEV*
2075ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002076 const Type *SrcTy = V->getType();
2077 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2078 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2079 "Cannot truncate or noop with non-integer arguments!");
2080 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2081 "getTruncateOrNoop cannot extend!");
2082 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2083 return V; // No conversion
2084 return getTruncateExpr(V, Ty);
2085}
2086
Dan Gohmana334aa72009-06-22 00:31:57 +00002087/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2088/// the types using zero-extension, and then perform a umax operation
2089/// with them.
Owen Anderson372b46c2009-06-22 21:39:50 +00002090const SCEV* ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV* LHS,
2091 const SCEV* RHS) {
2092 const SCEV* PromotedLHS = LHS;
2093 const SCEV* PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002094
2095 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2096 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2097 else
2098 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2099
2100 return getUMaxExpr(PromotedLHS, PromotedRHS);
2101}
2102
Dan Gohmanc9759e82009-06-22 15:03:27 +00002103/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2104/// the types using zero-extension, and then perform a umin operation
2105/// with them.
Owen Anderson372b46c2009-06-22 21:39:50 +00002106const SCEV* ScalarEvolution::getUMinFromMismatchedTypes(const SCEV* LHS,
2107 const SCEV* RHS) {
2108 const SCEV* PromotedLHS = LHS;
2109 const SCEV* PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002110
2111 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2112 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2113 else
2114 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2115
2116 return getUMinExpr(PromotedLHS, PromotedRHS);
2117}
2118
Chris Lattner4dc534c2005-02-13 04:37:18 +00002119/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2120/// the specified instruction and replaces any references to the symbolic value
2121/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002122void ScalarEvolution::
Owen Anderson372b46c2009-06-22 21:39:50 +00002123ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEV* SymName,
2124 const SCEV* NewVal) {
2125 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohman35738ac2009-05-04 22:30:44 +00002126 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002127 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002128
Owen Anderson372b46c2009-06-22 21:39:50 +00002129 const SCEV* NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002130 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002131 if (NV == SI->second) return; // No change.
2132
2133 SI->second = NV; // Update the scalars map!
2134
2135 // Any instruction values that use this instruction might also need to be
2136 // updated!
2137 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2138 UI != E; ++UI)
2139 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2140}
Chris Lattner53e677a2004-04-02 20:23:17 +00002141
2142/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2143/// a loop header, making it a potential recurrence, or it doesn't.
2144///
Owen Anderson372b46c2009-06-22 21:39:50 +00002145const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002146 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002147 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002148 if (L->getHeader() == PN->getParent()) {
2149 // If it lives in the loop header, it has two incoming values, one
2150 // from outside the loop, and one from inside.
2151 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2152 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002153
Chris Lattner53e677a2004-04-02 20:23:17 +00002154 // While we are analyzing this PHI node, handle its value symbolically.
Owen Anderson372b46c2009-06-22 21:39:50 +00002155 const SCEV* SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002156 assert(Scalars.find(PN) == Scalars.end() &&
2157 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002158 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002159
2160 // Using this symbolic name for the PHI, analyze the value coming around
2161 // the back-edge.
Owen Anderson372b46c2009-06-22 21:39:50 +00002162 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Chris Lattner53e677a2004-04-02 20:23:17 +00002163
2164 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2165 // has a special value for the first iteration of the loop.
2166
2167 // If the value coming around the backedge is an add with the symbolic
2168 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002169 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002170 // If there is a single occurrence of the symbolic value, replace it
2171 // with a recurrence.
2172 unsigned FoundIndex = Add->getNumOperands();
2173 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2174 if (Add->getOperand(i) == SymbolicName)
2175 if (FoundIndex == e) {
2176 FoundIndex = i;
2177 break;
2178 }
2179
2180 if (FoundIndex != Add->getNumOperands()) {
2181 // Create an add with everything but the specified operand.
Owen Anderson372b46c2009-06-22 21:39:50 +00002182 SmallVector<const SCEV*, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002183 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2184 if (i != FoundIndex)
2185 Ops.push_back(Add->getOperand(i));
Owen Anderson372b46c2009-06-22 21:39:50 +00002186 const SCEV* Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002187
2188 // This is not a valid addrec if the step amount is varying each
2189 // loop iteration, but is not itself an addrec in this loop.
2190 if (Accum->isLoopInvariant(L) ||
2191 (isa<SCEVAddRecExpr>(Accum) &&
2192 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002193 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2194 const SCEV* PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002195
2196 // Okay, for the entire analysis of this edge we assumed the PHI
2197 // to be symbolic. We now need to go back and update all of the
2198 // entries for the scalars that use the PHI (except for the PHI
2199 // itself) to use the new analyzed value instead of the "symbolic"
2200 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002201 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002202 return PHISCEV;
2203 }
2204 }
Dan Gohman622ed672009-05-04 22:02:23 +00002205 } else if (const SCEVAddRecExpr *AddRec =
2206 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002207 // Otherwise, this could be a loop like this:
2208 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2209 // In this case, j = {1,+,1} and BEValue is j.
2210 // Because the other in-value of i (0) fits the evolution of BEValue
2211 // i really is an addrec evolution.
2212 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002213 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002214
2215 // If StartVal = j.start - j.stride, we can use StartVal as the
2216 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002217 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002218 AddRec->getOperand(1))) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002219 const SCEV* PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002220 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002221
2222 // Okay, for the entire analysis of this edge we assumed the PHI
2223 // to be symbolic. We now need to go back and update all of the
2224 // entries for the scalars that use the PHI (except for the PHI
2225 // itself) to use the new analyzed value instead of the "symbolic"
2226 // value.
2227 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2228 return PHISCEV;
2229 }
2230 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002231 }
2232
2233 return SymbolicName;
2234 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002235
Chris Lattner53e677a2004-04-02 20:23:17 +00002236 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002237 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002238}
2239
Dan Gohman26466c02009-05-08 20:26:55 +00002240/// createNodeForGEP - Expand GEP instructions into add and multiply
2241/// operations. This allows them to be analyzed by regular SCEV code.
2242///
Owen Anderson372b46c2009-06-22 21:39:50 +00002243const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002244
2245 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002246 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002247 // Don't attempt to analyze GEPs over unsized objects.
2248 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2249 return getUnknown(GEP);
Owen Anderson372b46c2009-06-22 21:39:50 +00002250 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002251 gep_type_iterator GTI = gep_type_begin(GEP);
2252 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2253 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002254 I != E; ++I) {
2255 Value *Index = *I;
2256 // Compute the (potentially symbolic) offset in bytes for this index.
2257 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2258 // For a struct, add the member offset.
2259 const StructLayout &SL = *TD->getStructLayout(STy);
2260 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2261 uint64_t Offset = SL.getElementOffset(FieldNo);
2262 TotalOffset = getAddExpr(TotalOffset,
2263 getIntegerSCEV(Offset, IntPtrTy));
2264 } else {
2265 // For an array, add the element offset, explicitly scaled.
Owen Anderson372b46c2009-06-22 21:39:50 +00002266 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002267 if (!isa<PointerType>(LocalOffset->getType()))
2268 // Getelementptr indicies are signed.
2269 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2270 IntPtrTy);
2271 LocalOffset =
2272 getMulExpr(LocalOffset,
Duncan Sands777d2302009-05-09 07:06:46 +00002273 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman26466c02009-05-08 20:26:55 +00002274 IntPtrTy));
2275 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2276 }
2277 }
2278 return getAddExpr(getSCEV(Base), TotalOffset);
2279}
2280
Nick Lewycky83bb0052007-11-22 07:59:40 +00002281/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2282/// guaranteed to end in (at every loop iteration). It is, at the same time,
2283/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2284/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002285uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002286ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002287 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002288 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002289
Dan Gohman622ed672009-05-04 22:02:23 +00002290 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002291 return std::min(GetMinTrailingZeros(T->getOperand()),
2292 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002293
Dan Gohman622ed672009-05-04 22:02:23 +00002294 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002295 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2296 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2297 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002298 }
2299
Dan Gohman622ed672009-05-04 22:02:23 +00002300 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002301 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2302 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2303 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002304 }
2305
Dan Gohman622ed672009-05-04 22:02:23 +00002306 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002307 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002308 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002309 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002310 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002311 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002312 }
2313
Dan Gohman622ed672009-05-04 22:02:23 +00002314 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002315 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002316 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2317 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002318 for (unsigned i = 1, e = M->getNumOperands();
2319 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002320 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002321 BitWidth);
2322 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002323 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002324
Dan Gohman622ed672009-05-04 22:02:23 +00002325 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002326 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002327 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002328 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002329 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002330 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002331 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002332
Dan Gohman622ed672009-05-04 22:02:23 +00002333 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002334 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002335 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002336 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002337 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002338 return MinOpRes;
2339 }
2340
Dan Gohman622ed672009-05-04 22:02:23 +00002341 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002342 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002343 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002344 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002345 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002346 return MinOpRes;
2347 }
2348
Dan Gohman2c364ad2009-06-19 23:29:04 +00002349 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2350 // For a SCEVUnknown, ask ValueTracking.
2351 unsigned BitWidth = getTypeSizeInBits(U->getType());
2352 APInt Mask = APInt::getAllOnesValue(BitWidth);
2353 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2354 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2355 return Zeros.countTrailingOnes();
2356 }
2357
2358 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002359 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002360}
Chris Lattner53e677a2004-04-02 20:23:17 +00002361
Dan Gohman2c364ad2009-06-19 23:29:04 +00002362uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002363ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002364 // TODO: Handle other SCEV expression types here.
2365
2366 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2367 return C->getValue()->getValue().countLeadingZeros();
2368
2369 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2370 // A zero-extension cast adds zero bits.
2371 return GetMinLeadingZeros(C->getOperand()) +
2372 (getTypeSizeInBits(C->getType()) -
2373 getTypeSizeInBits(C->getOperand()->getType()));
2374 }
2375
2376 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2377 // For a SCEVUnknown, ask ValueTracking.
2378 unsigned BitWidth = getTypeSizeInBits(U->getType());
2379 APInt Mask = APInt::getAllOnesValue(BitWidth);
2380 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2381 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2382 return Zeros.countLeadingOnes();
2383 }
2384
2385 return 1;
2386}
2387
2388uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002389ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002390 // TODO: Handle other SCEV expression types here.
2391
2392 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2393 const APInt &A = C->getValue()->getValue();
2394 return A.isNegative() ? A.countLeadingOnes() :
2395 A.countLeadingZeros();
2396 }
2397
2398 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2399 // A sign-extension cast adds sign bits.
2400 return GetMinSignBits(C->getOperand()) +
2401 (getTypeSizeInBits(C->getType()) -
2402 getTypeSizeInBits(C->getOperand()->getType()));
2403 }
2404
2405 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2406 // For a SCEVUnknown, ask ValueTracking.
2407 return ComputeNumSignBits(U->getValue(), TD);
2408 }
2409
2410 return 1;
2411}
2412
Chris Lattner53e677a2004-04-02 20:23:17 +00002413/// createSCEV - We know that there is no SCEV for the specified value.
2414/// Analyze the expression.
2415///
Owen Anderson372b46c2009-06-22 21:39:50 +00002416const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002417 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002418 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002419
Dan Gohman6c459a22008-06-22 19:56:46 +00002420 unsigned Opcode = Instruction::UserOp1;
2421 if (Instruction *I = dyn_cast<Instruction>(V))
2422 Opcode = I->getOpcode();
2423 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2424 Opcode = CE->getOpcode();
2425 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002426 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002427
Dan Gohman6c459a22008-06-22 19:56:46 +00002428 User *U = cast<User>(V);
2429 switch (Opcode) {
2430 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002431 return getAddExpr(getSCEV(U->getOperand(0)),
2432 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002433 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002434 return getMulExpr(getSCEV(U->getOperand(0)),
2435 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002436 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002437 return getUDivExpr(getSCEV(U->getOperand(0)),
2438 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002439 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002440 return getMinusSCEV(getSCEV(U->getOperand(0)),
2441 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002442 case Instruction::And:
2443 // For an expression like x&255 that merely masks off the high bits,
2444 // use zext(trunc(x)) as the SCEV expression.
2445 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002446 if (CI->isNullValue())
2447 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002448 if (CI->isAllOnesValue())
2449 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002450 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002451
2452 // Instcombine's ShrinkDemandedConstant may strip bits out of
2453 // constants, obscuring what would otherwise be a low-bits mask.
2454 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2455 // knew about to reconstruct a low-bits mask value.
2456 unsigned LZ = A.countLeadingZeros();
2457 unsigned BitWidth = A.getBitWidth();
2458 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2459 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2460 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2461
2462 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2463
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002464 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002465 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002466 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002467 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002468 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002469 }
2470 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002471
Dan Gohman6c459a22008-06-22 19:56:46 +00002472 case Instruction::Or:
2473 // If the RHS of the Or is a constant, we may have something like:
2474 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2475 // optimizations will transparently handle this case.
2476 //
2477 // In order for this transformation to be safe, the LHS must be of the
2478 // form X*(2^n) and the Or constant must be less than 2^n.
2479 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002480 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002481 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002482 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002483 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002484 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002485 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002486 break;
2487 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002488 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002489 // If the RHS of the xor is a signbit, then this is just an add.
2490 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002491 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002492 return getAddExpr(getSCEV(U->getOperand(0)),
2493 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002494
2495 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002496 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002497 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002498
2499 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2500 // This is a variant of the check for xor with -1, and it handles
2501 // the case where instcombine has trimmed non-demanded bits out
2502 // of an xor with -1.
2503 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2504 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2505 if (BO->getOpcode() == Instruction::And &&
2506 LCI->getValue() == CI->getValue())
2507 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002508 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002509 const Type *UTy = U->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00002510 const SCEV* Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002511 const Type *Z0Ty = Z0->getType();
2512 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2513
2514 // If C is a low-bits mask, the zero extend is zerving to
2515 // mask off the high bits. Complement the operand and
2516 // re-apply the zext.
2517 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2518 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2519
2520 // If C is a single bit, it may be in the sign-bit position
2521 // before the zero-extend. In this case, represent the xor
2522 // using an add, which is equivalent, and re-apply the zext.
2523 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2524 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2525 Trunc.isSignBit())
2526 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2527 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002528 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002529 }
2530 break;
2531
2532 case Instruction::Shl:
2533 // Turn shift left of a constant amount into a multiply.
2534 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2535 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2536 Constant *X = ConstantInt::get(
2537 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002538 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002539 }
2540 break;
2541
Nick Lewycky01eaf802008-07-07 06:15:49 +00002542 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002543 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002544 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2545 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2546 Constant *X = ConstantInt::get(
2547 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002548 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002549 }
2550 break;
2551
Dan Gohman4ee29af2009-04-21 02:26:00 +00002552 case Instruction::AShr:
2553 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2554 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2555 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2556 if (L->getOpcode() == Instruction::Shl &&
2557 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002558 unsigned BitWidth = getTypeSizeInBits(U->getType());
2559 uint64_t Amt = BitWidth - CI->getZExtValue();
2560 if (Amt == BitWidth)
2561 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2562 if (Amt > BitWidth)
2563 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002564 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002565 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002566 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002567 U->getType());
2568 }
2569 break;
2570
Dan Gohman6c459a22008-06-22 19:56:46 +00002571 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002572 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002573
2574 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002575 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002576
2577 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002578 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002579
2580 case Instruction::BitCast:
2581 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002582 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002583 return getSCEV(U->getOperand(0));
2584 break;
2585
Dan Gohman2d1be872009-04-16 03:18:22 +00002586 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002587 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002588 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002589 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002590
2591 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002592 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002593 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2594 U->getType());
2595
Dan Gohman26466c02009-05-08 20:26:55 +00002596 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002597 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002598 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002599
Dan Gohman6c459a22008-06-22 19:56:46 +00002600 case Instruction::PHI:
2601 return createNodeForPHI(cast<PHINode>(U));
2602
2603 case Instruction::Select:
2604 // This could be a smax or umax that was lowered earlier.
2605 // Try to recover it.
2606 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2607 Value *LHS = ICI->getOperand(0);
2608 Value *RHS = ICI->getOperand(1);
2609 switch (ICI->getPredicate()) {
2610 case ICmpInst::ICMP_SLT:
2611 case ICmpInst::ICMP_SLE:
2612 std::swap(LHS, RHS);
2613 // fall through
2614 case ICmpInst::ICMP_SGT:
2615 case ICmpInst::ICMP_SGE:
2616 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002617 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002618 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002619 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002620 break;
2621 case ICmpInst::ICMP_ULT:
2622 case ICmpInst::ICMP_ULE:
2623 std::swap(LHS, RHS);
2624 // fall through
2625 case ICmpInst::ICMP_UGT:
2626 case ICmpInst::ICMP_UGE:
2627 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002628 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002629 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002630 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002631 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002632 case ICmpInst::ICMP_NE:
2633 // n != 0 ? n : 1 -> umax(n, 1)
2634 if (LHS == U->getOperand(1) &&
2635 isa<ConstantInt>(U->getOperand(2)) &&
2636 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2637 isa<ConstantInt>(RHS) &&
2638 cast<ConstantInt>(RHS)->isZero())
2639 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2640 break;
2641 case ICmpInst::ICMP_EQ:
2642 // n == 0 ? 1 : n -> umax(n, 1)
2643 if (LHS == U->getOperand(2) &&
2644 isa<ConstantInt>(U->getOperand(1)) &&
2645 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2646 isa<ConstantInt>(RHS) &&
2647 cast<ConstantInt>(RHS)->isZero())
2648 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2649 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002650 default:
2651 break;
2652 }
2653 }
2654
2655 default: // We cannot analyze this expression.
2656 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002657 }
2658
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002659 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002660}
2661
2662
2663
2664//===----------------------------------------------------------------------===//
2665// Iteration Count Computation Code
2666//
2667
Dan Gohman46bdfb02009-02-24 18:55:53 +00002668/// getBackedgeTakenCount - If the specified loop has a predictable
2669/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2670/// object. The backedge-taken count is the number of times the loop header
2671/// will be branched to from within the loop. This is one less than the
2672/// trip count of the loop, since it doesn't count the first iteration,
2673/// when the header is branched to from outside the loop.
2674///
2675/// Note that it is not valid to call this method on a loop without a
2676/// loop-invariant backedge-taken count (see
2677/// hasLoopInvariantBackedgeTakenCount).
2678///
Owen Anderson372b46c2009-06-22 21:39:50 +00002679const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002680 return getBackedgeTakenInfo(L).Exact;
2681}
2682
2683/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2684/// return the least SCEV value that is known never to be less than the
2685/// actual backedge taken count.
Owen Anderson372b46c2009-06-22 21:39:50 +00002686const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002687 return getBackedgeTakenInfo(L).Max;
2688}
2689
2690const ScalarEvolution::BackedgeTakenInfo &
2691ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002692 // Initially insert a CouldNotCompute for this loop. If the insertion
2693 // succeeds, procede to actually compute a backedge-taken count and
2694 // update the value. The temporary CouldNotCompute value tells SCEV
2695 // code elsewhere that it shouldn't attempt to request a new
2696 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002697 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002698 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2699 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002700 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002701 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002702 assert(ItCount.Exact->isLoopInvariant(L) &&
2703 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002704 "Computed trip count isn't loop invariant for loop!");
2705 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002706
Dan Gohman01ecca22009-04-27 20:16:15 +00002707 // Update the value in the map.
2708 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00002709 } else {
2710 if (ItCount.Max != CouldNotCompute)
2711 // Update the value in the map.
2712 Pair.first->second = ItCount;
2713 if (isa<PHINode>(L->getHeader()->begin()))
2714 // Only count loops that have phi nodes as not being computable.
2715 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00002716 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002717
2718 // Now that we know more about the trip count for this loop, forget any
2719 // existing SCEV values for PHI nodes in this loop since they are only
2720 // conservative estimates made without the benefit
2721 // of trip count information.
2722 if (ItCount.hasAnyInfo())
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002723 forgetLoopPHIs(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002724 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002725 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002726}
2727
Dan Gohman46bdfb02009-02-24 18:55:53 +00002728/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002729/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002730/// ScalarEvolution's ability to compute a trip count, or if the loop
2731/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002732void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002733 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002734 forgetLoopPHIs(L);
2735}
2736
2737/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2738/// PHI nodes in the given loop. This is used when the trip count of
2739/// the loop may have changed.
2740void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002741 BasicBlock *Header = L->getHeader();
2742
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002743 // Push all Loop-header PHIs onto the Worklist stack, except those
2744 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2745 // a PHI either means that it has an unrecognized structure, or it's
2746 // a PHI that's in the progress of being computed by createNodeForPHI.
2747 // In the former case, additional loop trip count information isn't
2748 // going to change anything. In the later case, createNodeForPHI will
2749 // perform the necessary updates on its own when it gets to that point.
Dan Gohman35738ac2009-05-04 22:30:44 +00002750 SmallVector<Instruction *, 16> Worklist;
2751 for (BasicBlock::iterator I = Header->begin();
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002752 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002753 std::map<SCEVCallbackVH, const SCEV*>::iterator It = Scalars.find((Value*)I);
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002754 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2755 Worklist.push_back(PN);
2756 }
Dan Gohman35738ac2009-05-04 22:30:44 +00002757
2758 while (!Worklist.empty()) {
2759 Instruction *I = Worklist.pop_back_val();
2760 if (Scalars.erase(I))
2761 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2762 UI != UE; ++UI)
2763 Worklist.push_back(cast<Instruction>(UI));
2764 }
Dan Gohman60f8a632009-02-17 20:49:49 +00002765}
2766
Dan Gohman46bdfb02009-02-24 18:55:53 +00002767/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2768/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002769ScalarEvolution::BackedgeTakenInfo
2770ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00002771 SmallVector<BasicBlock*, 8> ExitingBlocks;
2772 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00002773
Dan Gohmana334aa72009-06-22 00:31:57 +00002774 // Examine all exits and pick the most conservative values.
Owen Anderson372b46c2009-06-22 21:39:50 +00002775 const SCEV* BECount = CouldNotCompute;
2776 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohmana334aa72009-06-22 00:31:57 +00002777 bool CouldNotComputeBECount = false;
2778 bool CouldNotComputeMaxBECount = false;
2779 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2780 BackedgeTakenInfo NewBTI =
2781 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00002782
Dan Gohmana334aa72009-06-22 00:31:57 +00002783 if (NewBTI.Exact == CouldNotCompute) {
2784 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00002785 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00002786 CouldNotComputeBECount = true;
2787 BECount = CouldNotCompute;
2788 } else if (!CouldNotComputeBECount) {
2789 if (BECount == CouldNotCompute)
2790 BECount = NewBTI.Exact;
2791 else {
2792 // TODO: More analysis could be done here. For example, a
2793 // loop with a short-circuiting && operator has an exact count
2794 // of the min of both sides.
2795 CouldNotComputeBECount = true;
2796 BECount = CouldNotCompute;
2797 }
2798 }
2799 if (NewBTI.Max == CouldNotCompute) {
2800 // We couldn't compute an maximum value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00002801 // we won't be able to compute an maximum value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00002802 CouldNotComputeMaxBECount = true;
2803 MaxBECount = CouldNotCompute;
2804 } else if (!CouldNotComputeMaxBECount) {
2805 if (MaxBECount == CouldNotCompute)
2806 MaxBECount = NewBTI.Max;
2807 else
2808 MaxBECount = getUMaxFromMismatchedTypes(MaxBECount, NewBTI.Max);
2809 }
2810 }
2811
2812 return BackedgeTakenInfo(BECount, MaxBECount);
2813}
2814
2815/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2816/// of the specified loop will execute if it exits via the specified block.
2817ScalarEvolution::BackedgeTakenInfo
2818ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2819 BasicBlock *ExitingBlock) {
2820
2821 // Okay, we've chosen an exiting block. See what condition causes us to
2822 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00002823 //
2824 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002825 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002826 if (ExitBr == 0) return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00002827 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002828
2829 // At this point, we know we have a conditional branch that determines whether
2830 // the loop is exited. However, we don't know if the branch is executed each
2831 // time through the loop. If not, then the execution count of the branch will
2832 // not be equal to the trip count of the loop.
2833 //
2834 // Currently we check for this by checking to see if the Exit branch goes to
2835 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002836 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00002837 // loop header. This is common for un-rotated loops.
2838 //
2839 // If both of those tests fail, walk up the unique predecessor chain to the
2840 // header, stopping if there is an edge that doesn't exit the loop. If the
2841 // header is reached, the execution count of the branch will be equal to the
2842 // trip count of the loop.
2843 //
2844 // More extensive analysis could be done to handle more cases here.
2845 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00002846 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002847 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00002848 ExitBr->getParent() != L->getHeader()) {
2849 // The simple checks failed, try climbing the unique predecessor chain
2850 // up to the header.
2851 bool Ok = false;
2852 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
2853 BasicBlock *Pred = BB->getUniquePredecessor();
2854 if (!Pred)
2855 return CouldNotCompute;
2856 TerminatorInst *PredTerm = Pred->getTerminator();
2857 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
2858 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
2859 if (PredSucc == BB)
2860 continue;
2861 // If the predecessor has a successor that isn't BB and isn't
2862 // outside the loop, assume the worst.
2863 if (L->contains(PredSucc))
2864 return CouldNotCompute;
2865 }
2866 if (Pred == L->getHeader()) {
2867 Ok = true;
2868 break;
2869 }
2870 BB = Pred;
2871 }
2872 if (!Ok)
2873 return CouldNotCompute;
2874 }
2875
2876 // Procede to the next level to examine the exit condition expression.
2877 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
2878 ExitBr->getSuccessor(0),
2879 ExitBr->getSuccessor(1));
2880}
2881
2882/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
2883/// backedge of the specified loop will execute if its exit condition
2884/// were a conditional branch of ExitCond, TBB, and FBB.
2885ScalarEvolution::BackedgeTakenInfo
2886ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
2887 Value *ExitCond,
2888 BasicBlock *TBB,
2889 BasicBlock *FBB) {
2890 // Check if the controlling expression for this loop is an and or or. In
2891 // such cases, an exact backedge-taken count may be infeasible, but a
2892 // maximum count may still be feasible.
2893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
2894 if (BO->getOpcode() == Instruction::And) {
2895 // Recurse on the operands of the and.
2896 BackedgeTakenInfo BTI0 =
2897 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2898 BackedgeTakenInfo BTI1 =
2899 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Anderson372b46c2009-06-22 21:39:50 +00002900 const SCEV* BECount = CouldNotCompute;
2901 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohmana334aa72009-06-22 00:31:57 +00002902 if (L->contains(TBB)) {
2903 // Both conditions must be true for the loop to continue executing.
2904 // Choose the less conservative count.
Dan Gohman91380b72009-06-22 23:28:56 +00002905 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2906 BECount = CouldNotCompute;
Dan Gohman60e9b072009-06-22 15:09:28 +00002907 else
2908 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00002909 if (BTI0.Max == CouldNotCompute)
2910 MaxBECount = BTI1.Max;
2911 else if (BTI1.Max == CouldNotCompute)
2912 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00002913 else
2914 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00002915 } else {
2916 // Both conditions must be true for the loop to exit.
2917 assert(L->contains(FBB) && "Loop block has no successor in loop!");
2918 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2919 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2920 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2921 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2922 }
2923
2924 return BackedgeTakenInfo(BECount, MaxBECount);
2925 }
2926 if (BO->getOpcode() == Instruction::Or) {
2927 // Recurse on the operands of the or.
2928 BackedgeTakenInfo BTI0 =
2929 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2930 BackedgeTakenInfo BTI1 =
2931 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Anderson372b46c2009-06-22 21:39:50 +00002932 const SCEV* BECount = CouldNotCompute;
2933 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohmana334aa72009-06-22 00:31:57 +00002934 if (L->contains(FBB)) {
2935 // Both conditions must be false for the loop to continue executing.
2936 // Choose the less conservative count.
Dan Gohman91380b72009-06-22 23:28:56 +00002937 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2938 BECount = CouldNotCompute;
Dan Gohman60e9b072009-06-22 15:09:28 +00002939 else
2940 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00002941 if (BTI0.Max == CouldNotCompute)
2942 MaxBECount = BTI1.Max;
2943 else if (BTI1.Max == CouldNotCompute)
2944 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00002945 else
2946 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00002947 } else {
2948 // Both conditions must be false for the loop to exit.
2949 assert(L->contains(TBB) && "Loop block has no successor in loop!");
2950 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2951 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2952 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2953 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2954 }
2955
2956 return BackedgeTakenInfo(BECount, MaxBECount);
2957 }
2958 }
2959
2960 // With an icmp, it may be feasible to compute an exact backedge-taken count.
2961 // Procede to the next level to examine the icmp.
2962 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
2963 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002964
Eli Friedman361e54d2009-05-09 12:32:42 +00002965 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00002966 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
2967}
2968
2969/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
2970/// backedge of the specified loop will execute if its exit condition
2971/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
2972ScalarEvolution::BackedgeTakenInfo
2973ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
2974 ICmpInst *ExitCond,
2975 BasicBlock *TBB,
2976 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002977
Reid Spencere4d87aa2006-12-23 06:05:41 +00002978 // If the condition was exit on true, convert the condition to exit on false
2979 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00002980 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00002981 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002982 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002983 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002984
2985 // Handle common loops like: for (X = "string"; *X; ++X)
2986 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2987 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002988 const SCEV* ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002989 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00002990 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
2991 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
2992 return BackedgeTakenInfo(ItCnt,
2993 isa<SCEVConstant>(ItCnt) ? ItCnt :
2994 getConstant(APInt::getMaxValue(BitWidth)-1));
2995 }
Chris Lattner673e02b2004-10-12 01:49:27 +00002996 }
2997
Owen Anderson372b46c2009-06-22 21:39:50 +00002998 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
2999 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003000
3001 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003002 LHS = getSCEVAtScope(LHS, L);
3003 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003004
Reid Spencere4d87aa2006-12-23 06:05:41 +00003005 // At this point, we would like to compute how many iterations of the
3006 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003007 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3008 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003009 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003010 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003011 }
3012
Chris Lattner53e677a2004-04-02 20:23:17 +00003013 // If we have a comparison of a chrec against a constant, try to use value
3014 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003015 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3016 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003017 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003018 // Form the constant range.
3019 ConstantRange CompRange(
3020 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003021
Owen Anderson372b46c2009-06-22 21:39:50 +00003022 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003023 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003024 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003025
Chris Lattner53e677a2004-04-02 20:23:17 +00003026 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003027 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003028 // Convert to: while (X-Y != 0)
Owen Anderson372b46c2009-06-22 21:39:50 +00003029 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003030 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003031 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003032 }
3033 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003034 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Anderson372b46c2009-06-22 21:39:50 +00003035 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003036 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003037 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003038 }
3039 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003040 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3041 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003042 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003043 }
3044 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003045 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3046 getNotSCEV(RHS), L, true);
3047 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003048 break;
3049 }
3050 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003051 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3052 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003053 break;
3054 }
3055 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003056 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3057 getNotSCEV(RHS), L, false);
3058 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003059 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003060 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003061 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003062#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003063 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003064 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003065 errs() << "[unsigned] ";
3066 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00003067 << Instruction::getOpcodeName(Instruction::ICmp)
3068 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003069#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003070 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003071 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003072 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003073 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003074}
3075
Chris Lattner673e02b2004-10-12 01:49:27 +00003076static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003077EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3078 ScalarEvolution &SE) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003079 const SCEV* InVal = SE.getConstant(C);
3080 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003081 assert(isa<SCEVConstant>(Val) &&
3082 "Evaluation of SCEV at constant didn't fold correctly?");
3083 return cast<SCEVConstant>(Val)->getValue();
3084}
3085
3086/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3087/// and a GEP expression (missing the pointer index) indexing into it, return
3088/// the addressed element of the initializer or null if the index expression is
3089/// invalid.
3090static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003091GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003092 const std::vector<ConstantInt*> &Indices) {
3093 Constant *Init = GV->getInitializer();
3094 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003095 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003096 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3097 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3098 Init = cast<Constant>(CS->getOperand(Idx));
3099 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3100 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3101 Init = cast<Constant>(CA->getOperand(Idx));
3102 } else if (isa<ConstantAggregateZero>(Init)) {
3103 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3104 assert(Idx < STy->getNumElements() && "Bad struct index!");
3105 Init = Constant::getNullValue(STy->getElementType(Idx));
3106 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3107 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3108 Init = Constant::getNullValue(ATy->getElementType());
3109 } else {
3110 assert(0 && "Unknown constant aggregate type!");
3111 }
3112 return 0;
3113 } else {
3114 return 0; // Unknown initializer type
3115 }
3116 }
3117 return Init;
3118}
3119
Dan Gohman46bdfb02009-02-24 18:55:53 +00003120/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3121/// 'icmp op load X, cst', try to see if we can compute the backedge
3122/// execution count.
Owen Anderson372b46c2009-06-22 21:39:50 +00003123const SCEV* ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003124ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
3125 const Loop *L,
3126 ICmpInst::Predicate predicate) {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003127 if (LI->isVolatile()) return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003128
3129 // Check to see if the loaded pointer is a getelementptr of a global.
3130 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003131 if (!GEP) return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003132
3133 // Make sure that it is really a constant global we are gepping, with an
3134 // initializer, and make sure the first IDX is really 0.
3135 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3136 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3137 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3138 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003139 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003140
3141 // Okay, we allow one non-constant index into the GEP instruction.
3142 Value *VarIdx = 0;
3143 std::vector<ConstantInt*> Indexes;
3144 unsigned VarIdxNum = 0;
3145 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3146 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3147 Indexes.push_back(CI);
3148 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003149 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003150 VarIdx = GEP->getOperand(i);
3151 VarIdxNum = i-2;
3152 Indexes.push_back(0);
3153 }
3154
3155 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3156 // Check to see if X is a loop variant variable value now.
Owen Anderson372b46c2009-06-22 21:39:50 +00003157 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003158 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003159
3160 // We can only recognize very limited forms of loop index expressions, in
3161 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003162 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003163 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3164 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3165 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003166 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003167
3168 unsigned MaxSteps = MaxBruteForceIterations;
3169 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003170 ConstantInt *ItCst =
Dan Gohman6de29f82009-06-15 22:12:54 +00003171 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003172 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003173
3174 // Form the GEP offset.
3175 Indexes[VarIdxNum] = Val;
3176
3177 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3178 if (Result == 0) break; // Cannot compute!
3179
3180 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003181 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003182 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003183 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003184#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003185 errs() << "\n***\n*** Computed loop count " << *ItCst
3186 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3187 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003188#endif
3189 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003190 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003191 }
3192 }
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003193 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003194}
3195
3196
Chris Lattner3221ad02004-04-17 22:58:41 +00003197/// CanConstantFold - Return true if we can constant fold an instruction of the
3198/// specified type, assuming that all operands were constants.
3199static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003200 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003201 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3202 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003203
Chris Lattner3221ad02004-04-17 22:58:41 +00003204 if (const CallInst *CI = dyn_cast<CallInst>(I))
3205 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003206 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003207 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003208}
3209
Chris Lattner3221ad02004-04-17 22:58:41 +00003210/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3211/// in the loop that V is derived from. We allow arbitrary operations along the
3212/// way, but the operands of an operation must either be constants or a value
3213/// derived from a constant PHI. If this expression does not fit with these
3214/// constraints, return null.
3215static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3216 // If this is not an instruction, or if this is an instruction outside of the
3217 // loop, it can't be derived from a loop PHI.
3218 Instruction *I = dyn_cast<Instruction>(V);
3219 if (I == 0 || !L->contains(I->getParent())) return 0;
3220
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003221 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003222 if (L->getHeader() == I->getParent())
3223 return PN;
3224 else
3225 // We don't currently keep track of the control flow needed to evaluate
3226 // PHIs, so we cannot handle PHIs inside of loops.
3227 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003228 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003229
3230 // If we won't be able to constant fold this expression even if the operands
3231 // are constants, return early.
3232 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003233
Chris Lattner3221ad02004-04-17 22:58:41 +00003234 // Otherwise, we can evaluate this instruction if all of its operands are
3235 // constant or derived from a PHI node themselves.
3236 PHINode *PHI = 0;
3237 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3238 if (!(isa<Constant>(I->getOperand(Op)) ||
3239 isa<GlobalValue>(I->getOperand(Op)))) {
3240 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3241 if (P == 0) return 0; // Not evolving from PHI
3242 if (PHI == 0)
3243 PHI = P;
3244 else if (PHI != P)
3245 return 0; // Evolving from multiple different PHIs.
3246 }
3247
3248 // This is a expression evolving from a constant PHI!
3249 return PHI;
3250}
3251
3252/// EvaluateExpression - Given an expression that passes the
3253/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3254/// in the loop has the value PHIVal. If we can't fold this expression for some
3255/// reason, return null.
3256static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3257 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003258 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003259 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003260 Instruction *I = cast<Instruction>(V);
3261
3262 std::vector<Constant*> Operands;
3263 Operands.resize(I->getNumOperands());
3264
3265 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3266 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3267 if (Operands[i] == 0) return 0;
3268 }
3269
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003270 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3271 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3272 &Operands[0], Operands.size());
3273 else
3274 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3275 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00003276}
3277
3278/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3279/// in the header of its containing loop, we know the loop executes a
3280/// constant number of times, and the PHI node is just a recurrence
3281/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003282Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003283getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00003284 std::map<PHINode*, Constant*>::iterator I =
3285 ConstantEvolutionLoopExitValue.find(PN);
3286 if (I != ConstantEvolutionLoopExitValue.end())
3287 return I->second;
3288
Dan Gohman46bdfb02009-02-24 18:55:53 +00003289 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003290 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3291
3292 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3293
3294 // Since the loop is canonicalized, the PHI node must have two entries. One
3295 // entry must be a constant (coming in from outside of the loop), and the
3296 // second must be derived from the same PHI.
3297 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3298 Constant *StartCST =
3299 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3300 if (StartCST == 0)
3301 return RetVal = 0; // Must be a constant.
3302
3303 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3304 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3305 if (PN2 != PN)
3306 return RetVal = 0; // Not derived from same PHI.
3307
3308 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003309 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003310 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003311
Dan Gohman46bdfb02009-02-24 18:55:53 +00003312 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003313 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003314 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3315 if (IterationNum == NumIterations)
3316 return RetVal = PHIVal; // Got exit value!
3317
3318 // Compute the value of the PHI node for the next iteration.
3319 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3320 if (NextPHI == PHIVal)
3321 return RetVal = NextPHI; // Stopped evolving!
3322 if (NextPHI == 0)
3323 return 0; // Couldn't evaluate!
3324 PHIVal = NextPHI;
3325 }
3326}
3327
Dan Gohman46bdfb02009-02-24 18:55:53 +00003328/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003329/// constant number of times (the condition evolves only from constants),
3330/// try to evaluate a few iterations of the loop until we get the exit
3331/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003332/// evaluate the trip count of the loop, return CouldNotCompute.
Owen Anderson372b46c2009-06-22 21:39:50 +00003333const SCEV* ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003334ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003335 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003336 if (PN == 0) return CouldNotCompute;
Chris Lattner7980fb92004-04-17 18:36:24 +00003337
3338 // Since the loop is canonicalized, the PHI node must have two entries. One
3339 // entry must be a constant (coming in from outside of the loop), and the
3340 // second must be derived from the same PHI.
3341 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3342 Constant *StartCST =
3343 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003344 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003345
3346 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3347 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003348 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003349
3350 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3351 // the loop symbolically to determine when the condition gets a value of
3352 // "ExitWhen".
3353 unsigned IterationNum = 0;
3354 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3355 for (Constant *PHIVal = StartCST;
3356 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003357 ConstantInt *CondVal =
3358 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003359
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003360 // Couldn't symbolically evaluate.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003361 if (!CondVal) return CouldNotCompute;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003362
Reid Spencere8019bb2007-03-01 07:25:48 +00003363 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003364 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00003365 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003366 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003367 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003368
Chris Lattner3221ad02004-04-17 22:58:41 +00003369 // Compute the value of the PHI node for the next iteration.
3370 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3371 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003372 return CouldNotCompute; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003373 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003374 }
3375
3376 // Too many iterations were needed to evaluate.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003377 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003378}
3379
Dan Gohman66a7e852009-05-08 20:38:54 +00003380/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3381/// at the specified scope in the program. The L value specifies a loop
3382/// nest to evaluate the expression at, where null is the top-level or a
3383/// specified loop is immediately inside of the loop.
3384///
3385/// This method can be used to compute the exit value for a variable defined
3386/// in a loop by querying what the value will hold in the parent loop.
3387///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003388/// In the case that a relevant loop exit value cannot be computed, the
3389/// original value V is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00003390const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003391 // FIXME: this should be turned into a virtual method on SCEV!
3392
Chris Lattner3221ad02004-04-17 22:58:41 +00003393 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003394
Nick Lewycky3e630762008-02-20 06:48:22 +00003395 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003396 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003397 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003398 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003399 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003400 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3401 if (PHINode *PN = dyn_cast<PHINode>(I))
3402 if (PN->getParent() == LI->getHeader()) {
3403 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003404 // to see if the loop that contains it has a known backedge-taken
3405 // count. If so, we may be able to force computation of the exit
3406 // value.
Owen Anderson372b46c2009-06-22 21:39:50 +00003407 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003408 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003409 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003410 // Okay, we know how many times the containing loop executes. If
3411 // this is a constant evolving PHI node, get the final value at
3412 // the specified iteration number.
3413 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003414 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003415 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003416 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003417 }
3418 }
3419
Reid Spencer09906f32006-12-04 21:33:23 +00003420 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003421 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003422 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003423 // result. This is particularly useful for computing loop exit values.
3424 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003425 // Check to see if we've folded this instruction at this loop before.
3426 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3427 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3428 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3429 if (!Pair.second)
3430 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3431
Chris Lattner3221ad02004-04-17 22:58:41 +00003432 std::vector<Constant*> Operands;
3433 Operands.reserve(I->getNumOperands());
3434 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3435 Value *Op = I->getOperand(i);
3436 if (Constant *C = dyn_cast<Constant>(Op)) {
3437 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003438 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003439 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003440 // non-integer and non-pointer, don't even try to analyze them
3441 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003442 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003443 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003444
Owen Anderson372b46c2009-06-22 21:39:50 +00003445 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00003446 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003447 Constant *C = SC->getValue();
3448 if (C->getType() != Op->getType())
3449 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3450 Op->getType(),
3451 false),
3452 C, Op->getType());
3453 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003454 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003455 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3456 if (C->getType() != Op->getType())
3457 C =
3458 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3459 Op->getType(),
3460 false),
3461 C, Op->getType());
3462 Operands.push_back(C);
3463 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003464 return V;
3465 } else {
3466 return V;
3467 }
3468 }
3469 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003470
3471 Constant *C;
3472 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3473 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3474 &Operands[0], Operands.size());
3475 else
3476 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3477 &Operands[0], Operands.size());
Dan Gohman6bce6432009-05-08 20:47:27 +00003478 Pair.first->second = C;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003479 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003480 }
3481 }
3482
3483 // This is some other type of SCEVUnknown, just return it.
3484 return V;
3485 }
3486
Dan Gohman622ed672009-05-04 22:02:23 +00003487 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003488 // Avoid performing the look-up in the common case where the specified
3489 // expression has no loop-variant portions.
3490 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003491 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003492 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003493 // Okay, at least one of these operands is loop variant but might be
3494 // foldable. Build a new instance of the folded commutative expression.
Owen Anderson372b46c2009-06-22 21:39:50 +00003495 SmallVector<const SCEV*, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003496 NewOps.push_back(OpAtScope);
3497
3498 for (++i; i != e; ++i) {
3499 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003500 NewOps.push_back(OpAtScope);
3501 }
3502 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003503 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003504 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003505 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003506 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003507 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003508 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003509 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003510 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003511 }
3512 }
3513 // If we got here, all operands are loop invariant.
3514 return Comm;
3515 }
3516
Dan Gohman622ed672009-05-04 22:02:23 +00003517 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003518 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3519 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003520 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3521 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003522 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003523 }
3524
3525 // If this is a loop recurrence for a loop that does not contain L, then we
3526 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003527 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003528 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3529 // To evaluate this recurrence, we need to know how many times the AddRec
3530 // loop iterates. Compute this now.
Owen Anderson372b46c2009-06-22 21:39:50 +00003531 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003532 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003533
Eli Friedmanb42a6262008-08-04 23:49:06 +00003534 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003535 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003536 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003537 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003538 }
3539
Dan Gohman622ed672009-05-04 22:02:23 +00003540 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003541 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003542 if (Op == Cast->getOperand())
3543 return Cast; // must be loop invariant
3544 return getZeroExtendExpr(Op, Cast->getType());
3545 }
3546
Dan Gohman622ed672009-05-04 22:02:23 +00003547 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003548 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003549 if (Op == Cast->getOperand())
3550 return Cast; // must be loop invariant
3551 return getSignExtendExpr(Op, Cast->getType());
3552 }
3553
Dan Gohman622ed672009-05-04 22:02:23 +00003554 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003555 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003556 if (Op == Cast->getOperand())
3557 return Cast; // must be loop invariant
3558 return getTruncateExpr(Op, Cast->getType());
3559 }
3560
3561 assert(0 && "Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003562 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003563}
3564
Dan Gohman66a7e852009-05-08 20:38:54 +00003565/// getSCEVAtScope - This is a convenience function which does
3566/// getSCEVAtScope(getSCEV(V), L).
Owen Anderson372b46c2009-06-22 21:39:50 +00003567const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003568 return getSCEVAtScope(getSCEV(V), L);
3569}
3570
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003571/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3572/// following equation:
3573///
3574/// A * X = B (mod N)
3575///
3576/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3577/// A and B isn't important.
3578///
3579/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00003580static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003581 ScalarEvolution &SE) {
3582 uint32_t BW = A.getBitWidth();
3583 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3584 assert(A != 0 && "A must be non-zero.");
3585
3586 // 1. D = gcd(A, N)
3587 //
3588 // The gcd of A and N may have only one prime factor: 2. The number of
3589 // trailing zeros in A is its multiplicity
3590 uint32_t Mult2 = A.countTrailingZeros();
3591 // D = 2^Mult2
3592
3593 // 2. Check if B is divisible by D.
3594 //
3595 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3596 // is not less than multiplicity of this prime factor for D.
3597 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003598 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003599
3600 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3601 // modulo (N / D).
3602 //
3603 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3604 // bit width during computations.
3605 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3606 APInt Mod(BW + 1, 0);
3607 Mod.set(BW - Mult2); // Mod = N / D
3608 APInt I = AD.multiplicativeInverse(Mod);
3609
3610 // 4. Compute the minimum unsigned root of the equation:
3611 // I * (B / D) mod (N / D)
3612 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3613
3614 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3615 // bits.
3616 return SE.getConstant(Result.trunc(BW));
3617}
Chris Lattner53e677a2004-04-02 20:23:17 +00003618
3619/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3620/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3621/// might be the same) or two SCEVCouldNotCompute objects.
3622///
Owen Anderson372b46c2009-06-22 21:39:50 +00003623static std::pair<const SCEV*,const SCEV*>
Dan Gohman246b2562007-10-22 18:31:58 +00003624SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003625 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00003626 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3627 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3628 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003629
Chris Lattner53e677a2004-04-02 20:23:17 +00003630 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00003631 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003632 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003633 return std::make_pair(CNC, CNC);
3634 }
3635
Reid Spencere8019bb2007-03-01 07:25:48 +00003636 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00003637 const APInt &L = LC->getValue()->getValue();
3638 const APInt &M = MC->getValue()->getValue();
3639 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00003640 APInt Two(BitWidth, 2);
3641 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003642
Reid Spencere8019bb2007-03-01 07:25:48 +00003643 {
3644 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00003645 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00003646 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3647 // The B coefficient is M-N/2
3648 APInt B(M);
3649 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003650
Reid Spencere8019bb2007-03-01 07:25:48 +00003651 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00003652 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00003653
Reid Spencere8019bb2007-03-01 07:25:48 +00003654 // Compute the B^2-4ac term.
3655 APInt SqrtTerm(B);
3656 SqrtTerm *= B;
3657 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00003658
Reid Spencere8019bb2007-03-01 07:25:48 +00003659 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3660 // integer value or else APInt::sqrt() will assert.
3661 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003662
Reid Spencere8019bb2007-03-01 07:25:48 +00003663 // Compute the two solutions for the quadratic formula.
3664 // The divisions must be performed as signed divisions.
3665 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00003666 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003667 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003668 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003669 return std::make_pair(CNC, CNC);
3670 }
3671
Reid Spencere8019bb2007-03-01 07:25:48 +00003672 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3673 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003674
Dan Gohman246b2562007-10-22 18:31:58 +00003675 return std::make_pair(SE.getConstant(Solution1),
3676 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00003677 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00003678}
3679
3680/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003681/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Anderson372b46c2009-06-22 21:39:50 +00003682const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003683 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00003684 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003685 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00003686 if (C->getValue()->isZero()) return C;
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003687 return CouldNotCompute; // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003688 }
3689
Dan Gohman35738ac2009-05-04 22:30:44 +00003690 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003691 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003692 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003693
3694 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003695 // If this is an affine expression, the execution count of this branch is
3696 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00003697 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003698 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00003699 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003700 // equivalent to:
3701 //
3702 // Step*N = -Start (mod 2^BW)
3703 //
3704 // where BW is the common bit width of Start and Step.
3705
Chris Lattner53e677a2004-04-02 20:23:17 +00003706 // Get the initial value for the loop.
Owen Anderson372b46c2009-06-22 21:39:50 +00003707 const SCEV* Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3708 const SCEV* Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003709
Dan Gohman622ed672009-05-04 22:02:23 +00003710 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003711 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00003712
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003713 // First, handle unitary steps.
3714 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003715 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003716 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3717 return Start; // N = Start (as unsigned)
3718
3719 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00003720 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003721 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003722 -StartC->getValue()->getValue(),
3723 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003724 }
Chris Lattner42a75512007-01-15 02:27:26 +00003725 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003726 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3727 // the quadratic equation to solve it.
Owen Anderson372b46c2009-06-22 21:39:50 +00003728 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003729 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00003730 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3731 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003732 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003733#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003734 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3735 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003736#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00003737 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003738 if (ConstantInt *CB =
3739 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003740 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003741 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003742 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003743
Chris Lattner53e677a2004-04-02 20:23:17 +00003744 // We can only use this value if the chrec ends up with an exact zero
3745 // value at this index. When solving for "X*X != 5", for example, we
3746 // should not accept a root of 2.
Owen Anderson372b46c2009-06-22 21:39:50 +00003747 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00003748 if (Val->isZero())
3749 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00003750 }
3751 }
3752 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003753
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003754 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003755}
3756
3757/// HowFarToNonZero - Return the number of times a backedge checking the
3758/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003759/// CouldNotCompute
Owen Anderson372b46c2009-06-22 21:39:50 +00003760const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003761 // Loops that look like: while (X == 0) are very strange indeed. We don't
3762 // handle them yet except for the trivial case. This could be expanded in the
3763 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003764
Chris Lattner53e677a2004-04-02 20:23:17 +00003765 // If the value is a constant, check to see if it is known to be non-zero
3766 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00003767 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00003768 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003769 return getIntegerSCEV(0, C->getType());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003770 return CouldNotCompute; // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003771 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003772
Chris Lattner53e677a2004-04-02 20:23:17 +00003773 // We could implement others, but I really doubt anyone writes loops like
3774 // this, and if they did, they would already be constant folded.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003775 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003776}
3777
Dan Gohman859b4822009-05-18 15:36:09 +00003778/// getLoopPredecessor - If the given loop's header has exactly one unique
3779/// predecessor outside the loop, return it. Otherwise return null.
3780///
3781BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3782 BasicBlock *Header = L->getHeader();
3783 BasicBlock *Pred = 0;
3784 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3785 PI != E; ++PI)
3786 if (!L->contains(*PI)) {
3787 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3788 Pred = *PI;
3789 }
3790 return Pred;
3791}
3792
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003793/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3794/// (which may not be an immediate predecessor) which has exactly one
3795/// successor from which BB is reachable, or null if no such block is
3796/// found.
3797///
3798BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003799ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003800 // If the block has a unique predecessor, then there is no path from the
3801 // predecessor to the block that does not go through the direct edge
3802 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003803 if (BasicBlock *Pred = BB->getSinglePredecessor())
3804 return Pred;
3805
3806 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00003807 // If the header has a unique predecessor outside the loop, it must be
3808 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003809 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00003810 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003811
3812 return 0;
3813}
3814
Dan Gohman763bad12009-06-20 00:35:32 +00003815/// HasSameValue - SCEV structural equivalence is usually sufficient for
3816/// testing whether two expressions are equal, however for the purposes of
3817/// looking for a condition guarding a loop, it can be useful to be a little
3818/// more general, since a front-end may have replicated the controlling
3819/// expression.
3820///
Owen Anderson372b46c2009-06-22 21:39:50 +00003821static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohman763bad12009-06-20 00:35:32 +00003822 // Quick check to see if they are the same SCEV.
3823 if (A == B) return true;
3824
3825 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3826 // two different instructions with the same value. Check for this case.
3827 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3828 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3829 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3830 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3831 if (AI->isIdenticalTo(BI))
3832 return true;
3833
3834 // Otherwise assume they may have a different value.
3835 return false;
3836}
3837
Dan Gohmanc2390b12009-02-12 22:19:27 +00003838/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003839/// a conditional between LHS and RHS. This is used to help avoid max
3840/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003841bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003842 ICmpInst::Predicate Pred,
Dan Gohman35738ac2009-05-04 22:30:44 +00003843 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00003844 // Interpret a null as meaning no loop, where there is obviously no guard
3845 // (interprocedural conditions notwithstanding).
3846 if (!L) return false;
3847
Dan Gohman859b4822009-05-18 15:36:09 +00003848 BasicBlock *Predecessor = getLoopPredecessor(L);
3849 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003850
Dan Gohman859b4822009-05-18 15:36:09 +00003851 // Starting at the loop predecessor, climb up the predecessor chain, as long
3852 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003853 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00003854 for (; Predecessor;
3855 PredecessorDest = Predecessor,
3856 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00003857
3858 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00003859 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003860 if (!LoopEntryPredicate ||
3861 LoopEntryPredicate->isUnconditional())
3862 continue;
3863
3864 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3865 if (!ICI) continue;
3866
3867 // Now that we found a conditional branch that dominates the loop, check to
3868 // see if it is the comparison we are looking for.
3869 Value *PreCondLHS = ICI->getOperand(0);
3870 Value *PreCondRHS = ICI->getOperand(1);
3871 ICmpInst::Predicate Cond;
Dan Gohman859b4822009-05-18 15:36:09 +00003872 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohman38372182008-08-12 20:17:31 +00003873 Cond = ICI->getPredicate();
3874 else
3875 Cond = ICI->getInversePredicate();
3876
Dan Gohmanc2390b12009-02-12 22:19:27 +00003877 if (Cond == Pred)
3878 ; // An exact match.
3879 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3880 ; // The actual condition is beyond sufficient.
3881 else
3882 // Check a few special cases.
3883 switch (Cond) {
3884 case ICmpInst::ICMP_UGT:
3885 if (Pred == ICmpInst::ICMP_ULT) {
3886 std::swap(PreCondLHS, PreCondRHS);
3887 Cond = ICmpInst::ICMP_ULT;
3888 break;
3889 }
3890 continue;
3891 case ICmpInst::ICMP_SGT:
3892 if (Pred == ICmpInst::ICMP_SLT) {
3893 std::swap(PreCondLHS, PreCondRHS);
3894 Cond = ICmpInst::ICMP_SLT;
3895 break;
3896 }
3897 continue;
3898 case ICmpInst::ICMP_NE:
3899 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3900 // so check for this case by checking if the NE is comparing against
3901 // a minimum or maximum constant.
3902 if (!ICmpInst::isTrueWhenEqual(Pred))
3903 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3904 const APInt &A = CI->getValue();
3905 switch (Pred) {
3906 case ICmpInst::ICMP_SLT:
3907 if (A.isMaxSignedValue()) break;
3908 continue;
3909 case ICmpInst::ICMP_SGT:
3910 if (A.isMinSignedValue()) break;
3911 continue;
3912 case ICmpInst::ICMP_ULT:
3913 if (A.isMaxValue()) break;
3914 continue;
3915 case ICmpInst::ICMP_UGT:
3916 if (A.isMinValue()) break;
3917 continue;
3918 default:
3919 continue;
3920 }
3921 Cond = ICmpInst::ICMP_NE;
3922 // NE is symmetric but the original comparison may not be. Swap
3923 // the operands if necessary so that they match below.
3924 if (isa<SCEVConstant>(LHS))
3925 std::swap(PreCondLHS, PreCondRHS);
3926 break;
3927 }
3928 continue;
3929 default:
3930 // We weren't able to reconcile the condition.
3931 continue;
3932 }
Dan Gohman38372182008-08-12 20:17:31 +00003933
3934 if (!PreCondLHS->getType()->isInteger()) continue;
3935
Owen Anderson372b46c2009-06-22 21:39:50 +00003936 const SCEV* PreCondLHSSCEV = getSCEV(PreCondLHS);
3937 const SCEV* PreCondRHSSCEV = getSCEV(PreCondRHS);
Dan Gohman763bad12009-06-20 00:35:32 +00003938 if ((HasSameValue(LHS, PreCondLHSSCEV) &&
3939 HasSameValue(RHS, PreCondRHSSCEV)) ||
3940 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
3941 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV))))
Dan Gohman38372182008-08-12 20:17:31 +00003942 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003943 }
3944
Dan Gohman38372182008-08-12 20:17:31 +00003945 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003946}
3947
Dan Gohman51f53b72009-06-21 23:46:38 +00003948/// getBECount - Subtract the end and start values and divide by the step,
3949/// rounding up, to get the number of times the backedge is executed. Return
3950/// CouldNotCompute if an intermediate computation overflows.
Owen Anderson372b46c2009-06-22 21:39:50 +00003951const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
3952 const SCEV* End,
3953 const SCEV* Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00003954 const Type *Ty = Start->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00003955 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
3956 const SCEV* Diff = getMinusSCEV(End, Start);
3957 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00003958
3959 // Add an adjustment to the difference between End and Start so that
3960 // the division will effectively round up.
Owen Anderson372b46c2009-06-22 21:39:50 +00003961 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00003962
3963 // Check Add for unsigned overflow.
3964 // TODO: More sophisticated things could be done here.
3965 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
Owen Anderson372b46c2009-06-22 21:39:50 +00003966 const SCEV* OperandExtendedAdd =
Dan Gohman51f53b72009-06-21 23:46:38 +00003967 getAddExpr(getZeroExtendExpr(Diff, WideTy),
3968 getZeroExtendExpr(RoundUp, WideTy));
3969 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
3970 return CouldNotCompute;
3971
3972 return getUDivExpr(Add, Step);
3973}
3974
Chris Lattnerdb25de42005-08-15 23:33:51 +00003975/// HowManyLessThans - Return the number of times a backedge containing the
3976/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003977/// CouldNotCompute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003978ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohman35738ac2009-05-04 22:30:44 +00003979HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3980 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003981 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003982 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003983
Dan Gohman35738ac2009-05-04 22:30:44 +00003984 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003985 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003986 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003987
3988 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003989 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00003990 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +00003991 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00003992
3993 // TODO: handle non-constant strides.
3994 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3995 if (!CStep || CStep->isZero())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003996 return CouldNotCompute;
Dan Gohman70a1fe72009-05-18 15:22:39 +00003997 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003998 // With unit stride, the iteration never steps past the limit value.
3999 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4000 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4001 // Test whether a positive iteration iteration can step past the limit
4002 // value and past the maximum value for its type in a single step.
4003 if (isSigned) {
4004 APInt Max = APInt::getSignedMaxValue(BitWidth);
4005 if ((Max - CStep->getValue()->getValue())
4006 .slt(CLimit->getValue()->getValue()))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004007 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004008 } else {
4009 APInt Max = APInt::getMaxValue(BitWidth);
4010 if ((Max - CStep->getValue()->getValue())
4011 .ult(CLimit->getValue()->getValue()))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004012 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004013 }
4014 } else
4015 // TODO: handle non-constant limit values below.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004016 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004017 } else
4018 // TODO: handle negative strides below.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004019 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004020
Dan Gohmana1af7572009-04-30 20:47:05 +00004021 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4022 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4023 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004024 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004025
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004026 // First, we get the value of the LHS in the first iteration: n
Owen Anderson372b46c2009-06-22 21:39:50 +00004027 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004028
Dan Gohmana1af7572009-04-30 20:47:05 +00004029 // Determine the minimum constant start value.
Owen Anderson372b46c2009-06-22 21:39:50 +00004030 const SCEV* MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmana1af7572009-04-30 20:47:05 +00004031 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4032 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004033
Dan Gohmana1af7572009-04-30 20:47:05 +00004034 // If we know that the condition is true in order to enter the loop,
4035 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004036 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4037 // the division must round up.
Owen Anderson372b46c2009-06-22 21:39:50 +00004038 const SCEV* End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004039 if (!isLoopGuardedByCond(L,
4040 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4041 getMinusSCEV(Start, Step), RHS))
4042 End = isSigned ? getSMaxExpr(RHS, Start)
4043 : getUMaxExpr(RHS, Start);
4044
4045 // Determine the maximum constant end value.
Owen Anderson372b46c2009-06-22 21:39:50 +00004046 const SCEV* MaxEnd =
Dan Gohman3964acc2009-06-20 00:32:22 +00004047 isa<SCEVConstant>(End) ? End :
4048 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4049 .ashr(GetMinSignBits(End) - 1) :
4050 APInt::getMaxValue(BitWidth)
4051 .lshr(GetMinLeadingZeros(End)));
Dan Gohmana1af7572009-04-30 20:47:05 +00004052
4053 // Finally, we subtract these two values and divide, rounding up, to get
4054 // the number of times the backedge is executed.
Owen Anderson372b46c2009-06-22 21:39:50 +00004055 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004056
4057 // The maximum backedge count is similar, except using the minimum start
4058 // value and the maximum end value.
Owen Anderson372b46c2009-06-22 21:39:50 +00004059 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmana1af7572009-04-30 20:47:05 +00004060
4061 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004062 }
4063
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004064 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004065}
4066
Chris Lattner53e677a2004-04-02 20:23:17 +00004067/// getNumIterationsInRange - Return the number of iterations of this loop that
4068/// produce values in the specified constant range. Another way of looking at
4069/// this is that it returns the first iteration number where the value is not in
4070/// the condition, thus computing the exit count. If the iteration count can't
4071/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00004072const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman246b2562007-10-22 18:31:58 +00004073 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004074 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004075 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004076
4077 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004078 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004079 if (!SC->getValue()->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00004080 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004081 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +00004082 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004083 if (const SCEVAddRecExpr *ShiftedAddRec =
4084 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004085 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004086 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004087 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004088 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004089 }
4090
4091 // The only time we can solve this is when we have all constant indices.
4092 // Otherwise, we cannot determine the overflow conditions.
4093 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4094 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004095 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004096
4097
4098 // Okay at this point we know that all elements of the chrec are constants and
4099 // that the start element is zero.
4100
4101 // First check to see if the range contains zero. If not, the first
4102 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004103 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004104 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004105 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004106
Chris Lattner53e677a2004-04-02 20:23:17 +00004107 if (isAffine()) {
4108 // If this is an affine expression then we have this situation:
4109 // Solve {0,+,A} in Range === Ax in Range
4110
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004111 // We know that zero is in the range. If A is positive then we know that
4112 // the upper value of the range must be the first possible exit value.
4113 // If A is negative then the lower of the range is the last possible loop
4114 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004115 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004116 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4117 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004118
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004119 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004120 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00004121 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004122
4123 // Evaluate at the exit value. If we really did fall out of the valid
4124 // range, then we computed our trip count, otherwise wrap around or other
4125 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004126 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004127 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004128 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004129
4130 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004131 assert(Range.contains(
4132 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004133 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004134 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004135 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004136 } else if (isQuadratic()) {
4137 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4138 // quadratic equation to solve it. To do this, we must frame our problem in
4139 // terms of figuring out when zero is crossed, instead of when
4140 // Range.getUpper() is crossed.
Owen Anderson372b46c2009-06-22 21:39:50 +00004141 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004142 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Anderson372b46c2009-06-22 21:39:50 +00004143 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004144
4145 // Next, solve the constructed addrec
Owen Anderson372b46c2009-06-22 21:39:50 +00004146 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004147 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004148 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4149 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004150 if (R1) {
4151 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004152 if (ConstantInt *CB =
4153 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004155 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004156 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004157
Chris Lattner53e677a2004-04-02 20:23:17 +00004158 // Make sure the root is not off by one. The returned iteration should
4159 // not be in the range, but the previous one should be. When solving
4160 // for "X*X < 5", for example, we should not return a root of 2.
4161 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004162 R1->getValue(),
4163 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004164 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004165 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00004166 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004167
Dan Gohman246b2562007-10-22 18:31:58 +00004168 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004169 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004170 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004171 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004172 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004173
Chris Lattner53e677a2004-04-02 20:23:17 +00004174 // If R1 was not in the range, then it is a good return value. Make
4175 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00004176 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004177 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004178 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004179 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004180 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004181 }
4182 }
4183 }
4184
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004185 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004186}
4187
4188
4189
4190//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004191// SCEVCallbackVH Class Implementation
4192//===----------------------------------------------------------------------===//
4193
Dan Gohman1959b752009-05-19 19:22:47 +00004194void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman35738ac2009-05-04 22:30:44 +00004195 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4196 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4197 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004198 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4199 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004200 SE->Scalars.erase(getValPtr());
4201 // this now dangles!
4202}
4203
Dan Gohman1959b752009-05-19 19:22:47 +00004204void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004205 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4206
4207 // Forget all the expressions associated with users of the old value,
4208 // so that future queries will recompute the expressions using the new
4209 // value.
4210 SmallVector<User *, 16> Worklist;
4211 Value *Old = getValPtr();
4212 bool DeleteOld = false;
4213 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4214 UI != UE; ++UI)
4215 Worklist.push_back(*UI);
4216 while (!Worklist.empty()) {
4217 User *U = Worklist.pop_back_val();
4218 // Deleting the Old value will cause this to dangle. Postpone
4219 // that until everything else is done.
4220 if (U == Old) {
4221 DeleteOld = true;
4222 continue;
4223 }
4224 if (PHINode *PN = dyn_cast<PHINode>(U))
4225 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004226 if (Instruction *I = dyn_cast<Instruction>(U))
4227 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004228 if (SE->Scalars.erase(U))
4229 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4230 UI != UE; ++UI)
4231 Worklist.push_back(*UI);
4232 }
4233 if (DeleteOld) {
4234 if (PHINode *PN = dyn_cast<PHINode>(Old))
4235 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004236 if (Instruction *I = dyn_cast<Instruction>(Old))
4237 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004238 SE->Scalars.erase(Old);
4239 // this now dangles!
4240 }
4241 // this may dangle!
4242}
4243
Dan Gohman1959b752009-05-19 19:22:47 +00004244ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004245 : CallbackVH(V), SE(se) {}
4246
4247//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004248// ScalarEvolution Class Implementation
4249//===----------------------------------------------------------------------===//
4250
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004251ScalarEvolution::ScalarEvolution()
Owen Anderson753ad612009-06-22 21:57:23 +00004252 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004253}
4254
Chris Lattner53e677a2004-04-02 20:23:17 +00004255bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004256 this->F = &F;
4257 LI = &getAnalysis<LoopInfo>();
4258 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004259 return false;
4260}
4261
4262void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004263 Scalars.clear();
4264 BackedgeTakenCounts.clear();
4265 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004266 ValuesAtScopes.clear();
Owen Anderson08367b62009-06-22 18:25:46 +00004267
4268 for (std::map<ConstantInt*, SCEVConstant*>::iterator
4269 I = SCEVConstants.begin(), E = SCEVConstants.end(); I != E; ++I)
4270 delete I->second;
4271 for (std::map<std::pair<const SCEV*, const Type*>,
4272 SCEVTruncateExpr*>::iterator I = SCEVTruncates.begin(),
4273 E = SCEVTruncates.end(); I != E; ++I)
4274 delete I->second;
4275 for (std::map<std::pair<const SCEV*, const Type*>,
4276 SCEVZeroExtendExpr*>::iterator I = SCEVZeroExtends.begin(),
4277 E = SCEVZeroExtends.end(); I != E; ++I)
4278 delete I->second;
4279 for (std::map<std::pair<unsigned, std::vector<const SCEV*> >,
4280 SCEVCommutativeExpr*>::iterator I = SCEVCommExprs.begin(),
4281 E = SCEVCommExprs.end(); I != E; ++I)
4282 delete I->second;
4283 for (std::map<std::pair<const SCEV*, const SCEV*>, SCEVUDivExpr*>::iterator
4284 I = SCEVUDivs.begin(), E = SCEVUDivs.end(); I != E; ++I)
4285 delete I->second;
4286 for (std::map<std::pair<const SCEV*, const Type*>,
4287 SCEVSignExtendExpr*>::iterator I = SCEVSignExtends.begin(),
4288 E = SCEVSignExtends.end(); I != E; ++I)
4289 delete I->second;
4290 for (std::map<std::pair<const Loop *, std::vector<const SCEV*> >,
4291 SCEVAddRecExpr*>::iterator I = SCEVAddRecExprs.begin(),
4292 E = SCEVAddRecExprs.end(); I != E; ++I)
4293 delete I->second;
4294 for (std::map<Value*, SCEVUnknown*>::iterator I = SCEVUnknowns.begin(),
4295 E = SCEVUnknowns.end(); I != E; ++I)
4296 delete I->second;
4297
4298 SCEVConstants.clear();
4299 SCEVTruncates.clear();
4300 SCEVZeroExtends.clear();
4301 SCEVCommExprs.clear();
4302 SCEVUDivs.clear();
4303 SCEVSignExtends.clear();
4304 SCEVAddRecExprs.clear();
4305 SCEVUnknowns.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00004306}
4307
4308void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4309 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004310 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004311}
4312
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004313bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004314 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004315}
4316
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004317static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004318 const Loop *L) {
4319 // Print all inner loops first
4320 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4321 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004322
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004323 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004324
Devang Patelb7211a22007-08-21 00:31:24 +00004325 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004326 L->getExitBlocks(ExitBlocks);
4327 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004328 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004329
Dan Gohman46bdfb02009-02-24 18:55:53 +00004330 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4331 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004332 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004333 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004334 }
4335
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004336 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004337}
4338
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004339void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004340 // ScalarEvolution's implementaiton of the print method is to print
4341 // out SCEV values of all instructions that are interesting. Doing
4342 // this potentially causes it to create new SCEV objects though,
4343 // which technically conflicts with the const qualifier. This isn't
4344 // observable from outside the class though (the hasSCEV function
4345 // notwithstanding), so casting away the const isn't dangerous.
4346 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004347
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004348 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004349 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004350 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00004351 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00004352 OS << " --> ";
Owen Anderson372b46c2009-06-22 21:39:50 +00004353 const SCEV* SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004354 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004355
Dan Gohman0c689c52009-06-19 17:49:54 +00004356 const Loop *L = LI->getLoopFor((*I).getParent());
4357
Owen Anderson372b46c2009-06-22 21:39:50 +00004358 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00004359 if (AtUse != SV) {
4360 OS << " --> ";
4361 AtUse->print(OS);
4362 }
4363
4364 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00004365 OS << "\t\t" "Exits: ";
Owen Anderson372b46c2009-06-22 21:39:50 +00004366 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00004367 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004368 OS << "<<Unknown>>";
4369 } else {
4370 OS << *ExitValue;
4371 }
4372 }
4373
Chris Lattner53e677a2004-04-02 20:23:17 +00004374 OS << "\n";
4375 }
4376
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004377 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4378 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4379 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004380}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004381
4382void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4383 raw_os_ostream OS(o);
4384 print(OS, M);
4385}