blob: 1803c3c7b5dff222f3cccc795fe4dfafe2bf0361 [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
Dan Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000078#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Owen Andersond13db2c2010-07-21 22:09:45 +0000106INITIALIZE_PASS(ScalarEvolution, "scalar-evolution",
107 "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000121 print(dbgs());
122 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman3bf63762010-06-18 19:54:20 +0000144 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3bf63762010-06-18 19:54:20 +0000180 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000181 UniqueSCEVs.InsertNode(S, IP);
182 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183}
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Dan Gohman0bba49c2009-07-07 17:06:11 +0000185const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000186 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000187}
188
Dan Gohman0bba49c2009-07-07 17:06:11 +0000189const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000190ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000191 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
192 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000193}
194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000197void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Dan Gohman3bf63762010-06-18 19:54:20 +0000201SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000204
Dan Gohman84923602009-04-21 01:25:57 +0000205bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
207}
208
Dan Gohman6e70e312009-09-27 15:26:03 +0000209bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->properlyDominates(BB, DT);
211}
212
Dan Gohman3bf63762010-06-18 19:54:20 +0000213SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000215 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000216 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
217 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
Dan Gohman3bf63762010-06-18 19:54:20 +0000225SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000227 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000228 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
229 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000233void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000234 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235}
236
Dan Gohman3bf63762010-06-18 19:54:20 +0000237SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000239 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000240 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
241 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000242 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000243}
244
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000245void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000246 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000247}
248
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000249void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000250 const char *OpStr = getOperationStr();
Dan Gohmana5145c82010-04-16 15:03:25 +0000251 OS << "(";
252 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
253 OS << **I;
Oscar Fuentesee56c422010-08-02 06:00:15 +0000254 if (llvm::next(I) != E)
Dan Gohmana5145c82010-04-16 15:03:25 +0000255 OS << OpStr;
256 }
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000257 OS << ")";
258}
259
Dan Gohmanecb403a2009-05-07 14:00:19 +0000260bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000261 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
262 if (!getOperand(i)->dominates(BB, DT))
263 return false;
264 }
265 return true;
266}
267
Dan Gohman6e70e312009-09-27 15:26:03 +0000268bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
269 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
270 if (!getOperand(i)->properlyDominates(BB, DT))
271 return false;
272 }
273 return true;
274}
275
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000276bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
277 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
278}
279
Dan Gohman6e70e312009-09-27 15:26:03 +0000280bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
281 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
282}
283
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000284void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000285 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000286}
287
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000288const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000289 // In most cases the types of LHS and RHS will be the same, but in some
290 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
291 // depend on the type for correctness, but handling types carefully can
292 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
293 // a pointer type than the RHS, so use the RHS' type here.
294 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000295}
296
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000298 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000299 if (!QueryLoop)
300 return false;
301
302 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000303 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000304 return false;
305
306 // This recurrence is variant w.r.t. QueryLoop if any of its operands
307 // are variant.
308 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
309 if (!getOperand(i)->isLoopInvariant(QueryLoop))
310 return false;
311
312 // Otherwise it's loop-invariant.
313 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000314}
315
Dan Gohman39125d82010-02-13 00:19:39 +0000316bool
317SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
318 return DT->dominates(L->getHeader(), BB) &&
319 SCEVNAryExpr::dominates(BB, DT);
320}
321
322bool
323SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
324 // This uses a "dominates" query instead of "properly dominates" query because
325 // the instruction which produces the addrec's value is a PHI, and a PHI
326 // effectively properly dominates its entire containing block.
327 return DT->dominates(L->getHeader(), BB) &&
328 SCEVNAryExpr::properlyDominates(BB, DT);
329}
330
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000331void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000332 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000333 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000335 OS << "}<";
336 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
337 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338}
Chris Lattner53e677a2004-04-02 20:23:17 +0000339
Dan Gohmanab37f502010-08-02 23:49:30 +0000340void SCEVUnknown::deleted() {
341 // Clear this SCEVUnknown from ValuesAtScopes.
342 SE->ValuesAtScopes.erase(this);
343
344 // Remove this SCEVUnknown from the uniquing map.
345 SE->UniqueSCEVs.RemoveNode(this);
346
347 // Release the value.
348 setValPtr(0);
349}
350
351void SCEVUnknown::allUsesReplacedWith(Value *New) {
352 // Clear this SCEVUnknown from ValuesAtScopes.
353 SE->ValuesAtScopes.erase(this);
354
355 // Remove this SCEVUnknown from the uniquing map.
356 SE->UniqueSCEVs.RemoveNode(this);
357
358 // Update this SCEVUnknown to point to the new value. This is needed
359 // because there may still be outstanding SCEVs which still point to
360 // this SCEVUnknown.
361 setValPtr(New);
362}
363
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000364bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
365 // All non-instruction values are loop invariant. All instructions are loop
366 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000367 // Instructions are never considered invariant in the function body
368 // (null loop) because they are defined within the "loop".
Dan Gohmanab37f502010-08-02 23:49:30 +0000369 if (Instruction *I = dyn_cast<Instruction>(getValue()))
Dan Gohman92329c72009-12-18 01:24:09 +0000370 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000371 return true;
372}
Chris Lattner53e677a2004-04-02 20:23:17 +0000373
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000374bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
375 if (Instruction *I = dyn_cast<Instruction>(getValue()))
376 return DT->dominates(I->getParent(), BB);
377 return true;
378}
379
Dan Gohman6e70e312009-09-27 15:26:03 +0000380bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
381 if (Instruction *I = dyn_cast<Instruction>(getValue()))
382 return DT->properlyDominates(I->getParent(), BB);
383 return true;
384}
385
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000386const Type *SCEVUnknown::getType() const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000387 return getValue()->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000388}
Chris Lattner53e677a2004-04-02 20:23:17 +0000389
Dan Gohman0f5efe52010-01-28 02:15:55 +0000390bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000391 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000392 if (VCE->getOpcode() == Instruction::PtrToInt)
393 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000394 if (CE->getOpcode() == Instruction::GetElementPtr &&
395 CE->getOperand(0)->isNullValue() &&
396 CE->getNumOperands() == 2)
397 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
398 if (CI->isOne()) {
399 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
400 ->getElementType();
401 return true;
402 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000403
404 return false;
405}
406
407bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000408 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000409 if (VCE->getOpcode() == Instruction::PtrToInt)
410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000411 if (CE->getOpcode() == Instruction::GetElementPtr &&
412 CE->getOperand(0)->isNullValue()) {
413 const Type *Ty =
414 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
415 if (const StructType *STy = dyn_cast<StructType>(Ty))
416 if (!STy->isPacked() &&
417 CE->getNumOperands() == 3 &&
418 CE->getOperand(1)->isNullValue()) {
419 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
420 if (CI->isOne() &&
421 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000422 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000423 AllocTy = STy->getElementType(1);
424 return true;
425 }
426 }
427 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000428
429 return false;
430}
431
Dan Gohman4f8eea82010-02-01 18:27:38 +0000432bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000433 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000434 if (VCE->getOpcode() == Instruction::PtrToInt)
435 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
436 if (CE->getOpcode() == Instruction::GetElementPtr &&
437 CE->getNumOperands() == 3 &&
438 CE->getOperand(0)->isNullValue() &&
439 CE->getOperand(1)->isNullValue()) {
440 const Type *Ty =
441 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
442 // Ignore vector types here so that ScalarEvolutionExpander doesn't
443 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000444 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000445 CTy = Ty;
446 FieldNo = CE->getOperand(2);
447 return true;
448 }
449 }
450
451 return false;
452}
453
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000454void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000455 const Type *AllocTy;
456 if (isSizeOf(AllocTy)) {
457 OS << "sizeof(" << *AllocTy << ")";
458 return;
459 }
460 if (isAlignOf(AllocTy)) {
461 OS << "alignof(" << *AllocTy << ")";
462 return;
463 }
464
Dan Gohman4f8eea82010-02-01 18:27:38 +0000465 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000466 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000467 if (isOffsetOf(CTy, FieldNo)) {
468 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000469 WriteAsOperand(OS, FieldNo, false);
470 OS << ")";
471 return;
472 }
473
474 // Otherwise just print it normally.
Dan Gohmanab37f502010-08-02 23:49:30 +0000475 WriteAsOperand(OS, getValue(), false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000476}
477
Chris Lattner8d741b82004-06-20 06:23:15 +0000478//===----------------------------------------------------------------------===//
479// SCEV Utilities
480//===----------------------------------------------------------------------===//
481
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000482static bool CompareTypes(const Type *A, const Type *B) {
483 if (A->getTypeID() != B->getTypeID())
484 return A->getTypeID() < B->getTypeID();
485 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
486 const IntegerType *BI = cast<IntegerType>(B);
487 return AI->getBitWidth() < BI->getBitWidth();
488 }
489 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
490 const PointerType *BI = cast<PointerType>(B);
491 return CompareTypes(AI->getElementType(), BI->getElementType());
492 }
493 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
494 const ArrayType *BI = cast<ArrayType>(B);
495 if (AI->getNumElements() != BI->getNumElements())
496 return AI->getNumElements() < BI->getNumElements();
497 return CompareTypes(AI->getElementType(), BI->getElementType());
498 }
499 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
500 const VectorType *BI = cast<VectorType>(B);
501 if (AI->getNumElements() != BI->getNumElements())
502 return AI->getNumElements() < BI->getNumElements();
503 return CompareTypes(AI->getElementType(), BI->getElementType());
504 }
505 if (const StructType *AI = dyn_cast<StructType>(A)) {
506 const StructType *BI = cast<StructType>(B);
507 if (AI->getNumElements() != BI->getNumElements())
508 return AI->getNumElements() < BI->getNumElements();
509 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
510 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
511 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
512 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
513 }
514 return false;
515}
516
Chris Lattner8d741b82004-06-20 06:23:15 +0000517namespace {
518 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
519 /// than the complexity of the RHS. This comparator is used to canonicalize
520 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000521 class SCEVComplexityCompare {
Dan Gohmane72079a2010-07-23 21:18:55 +0000522 const LoopInfo *LI;
Dan Gohman72861302009-05-07 14:39:04 +0000523 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000524 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000525
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000526 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000527 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
528 if (LHS == RHS)
529 return false;
530
Dan Gohman72861302009-05-07 14:39:04 +0000531 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000532 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
533 if (LType != RType)
534 return LType < RType;
Dan Gohman72861302009-05-07 14:39:04 +0000535
Dan Gohman3bf63762010-06-18 19:54:20 +0000536 // Aside from the getSCEVType() ordering, the particular ordering
537 // isn't very important except that it's beneficial to be consistent,
538 // so that (a + b) and (b + a) don't end up as different expressions.
539
540 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
541 // not as complete as it could be.
542 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
543 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
544
545 // Order pointer values after integer values. This helps SCEVExpander
546 // form GEPs.
Dan Gohman304a7a62010-07-23 21:20:52 +0000547 bool LIsPointer = LU->getType()->isPointerTy(),
548 RIsPointer = RU->getType()->isPointerTy();
549 if (LIsPointer != RIsPointer)
550 return RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000551
552 // Compare getValueID values.
Dan Gohman304a7a62010-07-23 21:20:52 +0000553 unsigned LID = LU->getValue()->getValueID(),
554 RID = RU->getValue()->getValueID();
555 if (LID != RID)
556 return LID < RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000557
558 // Sort arguments by their position.
559 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
560 const Argument *RA = cast<Argument>(RU->getValue());
561 return LA->getArgNo() < RA->getArgNo();
562 }
563
564 // For instructions, compare their loop depth, and their opcode.
565 // This is pretty loose.
Dan Gohman304a7a62010-07-23 21:20:52 +0000566 if (const Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
567 const Instruction *RV = cast<Instruction>(RU->getValue());
Dan Gohman3bf63762010-06-18 19:54:20 +0000568
569 // Compare loop depths.
Dan Gohman304a7a62010-07-23 21:20:52 +0000570 unsigned LDepth = LI->getLoopDepth(LV->getParent()),
571 RDepth = LI->getLoopDepth(RV->getParent());
572 if (LDepth != RDepth)
573 return LDepth < RDepth;
Dan Gohman3bf63762010-06-18 19:54:20 +0000574
575 // Compare the number of operands.
Dan Gohman304a7a62010-07-23 21:20:52 +0000576 unsigned LNumOps = LV->getNumOperands(),
577 RNumOps = RV->getNumOperands();
578 if (LNumOps != RNumOps)
579 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000580 }
581
582 return false;
583 }
584
585 // Compare constant values.
586 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
587 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000588 const ConstantInt *LCC = LC->getValue();
589 const ConstantInt *RCC = RC->getValue();
590 unsigned LBitWidth = LCC->getBitWidth(), RBitWidth = RCC->getBitWidth();
591 if (LBitWidth != RBitWidth)
592 return LBitWidth < RBitWidth;
593 return LCC->getValue().ult(RCC->getValue());
Dan Gohman3bf63762010-06-18 19:54:20 +0000594 }
595
596 // Compare addrec loop depths.
597 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
598 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000599 unsigned LDepth = LA->getLoop()->getLoopDepth(),
600 RDepth = RA->getLoop()->getLoopDepth();
601 if (LDepth != RDepth)
602 return LDepth < RDepth;
Dan Gohman3bf63762010-06-18 19:54:20 +0000603 }
604
605 // Lexicographically compare n-ary expressions.
606 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
607 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000608 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
609 for (unsigned i = 0; i != LNumOps; ++i) {
610 if (i >= RNumOps)
Dan Gohman3bf63762010-06-18 19:54:20 +0000611 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000612 const SCEV *LOp = LC->getOperand(i), *ROp = RC->getOperand(i);
613 if (operator()(LOp, ROp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000614 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000615 if (operator()(ROp, LOp))
Dan Gohman3bf63762010-06-18 19:54:20 +0000616 return false;
617 }
Dan Gohman304a7a62010-07-23 21:20:52 +0000618 return LNumOps < RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000619 }
620
621 // Lexicographically compare udiv expressions.
622 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
623 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman304a7a62010-07-23 21:20:52 +0000624 const SCEV *LL = LC->getLHS(), *LR = LC->getRHS(),
625 *RL = RC->getLHS(), *RR = RC->getRHS();
626 if (operator()(LL, RL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000627 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000628 if (operator()(RL, LL))
Dan Gohman3bf63762010-06-18 19:54:20 +0000629 return false;
Dan Gohman304a7a62010-07-23 21:20:52 +0000630 if (operator()(LR, RR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000631 return true;
Dan Gohman304a7a62010-07-23 21:20:52 +0000632 if (operator()(RR, LR))
Dan Gohman3bf63762010-06-18 19:54:20 +0000633 return false;
634 return false;
635 }
636
637 // Compare cast expressions by operand.
638 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
639 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
640 return operator()(LC->getOperand(), RC->getOperand());
641 }
642
643 llvm_unreachable("Unknown SCEV kind!");
644 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000645 }
646 };
647}
648
649/// GroupByComplexity - Given a list of SCEV objects, order them by their
650/// complexity, and group objects of the same complexity together by value.
651/// When this routine is finished, we know that any duplicates in the vector are
652/// consecutive and that complexity is monotonically increasing.
653///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000654/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000655/// results from this routine. In other words, we don't want the results of
656/// this to depend on where the addresses of various SCEV objects happened to
657/// land in memory.
658///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000659static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000660 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000661 if (Ops.size() < 2) return; // Noop
662 if (Ops.size() == 2) {
663 // This is the common case, which also happens to be trivially simple.
664 // Special case it.
Dan Gohman3bf63762010-06-18 19:54:20 +0000665 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000666 std::swap(Ops[0], Ops[1]);
667 return;
668 }
669
Dan Gohman3bf63762010-06-18 19:54:20 +0000670 // Do the rough sort by complexity.
671 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
672
673 // Now that we are sorted by complexity, group elements of the same
674 // complexity. Note that this is, at worst, N^2, but the vector is likely to
675 // be extremely short in practice. Note that we take this approach because we
676 // do not want to depend on the addresses of the objects we are grouping.
677 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
678 const SCEV *S = Ops[i];
679 unsigned Complexity = S->getSCEVType();
680
681 // If there are any objects of the same complexity and same value as this
682 // one, group them.
683 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
684 if (Ops[j] == S) { // Found a duplicate.
685 // Move it to immediately after i'th element.
686 std::swap(Ops[i+1], Ops[j]);
687 ++i; // no need to rescan it.
688 if (i == e-2) return; // Done!
689 }
690 }
691 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000692}
693
Chris Lattner53e677a2004-04-02 20:23:17 +0000694
Chris Lattner53e677a2004-04-02 20:23:17 +0000695
696//===----------------------------------------------------------------------===//
697// Simple SCEV method implementations
698//===----------------------------------------------------------------------===//
699
Eli Friedmanb42a6262008-08-04 23:49:06 +0000700/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000701/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000702static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000703 ScalarEvolution &SE,
704 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000705 // Handle the simplest case efficiently.
706 if (K == 1)
707 return SE.getTruncateOrZeroExtend(It, ResultTy);
708
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000709 // We are using the following formula for BC(It, K):
710 //
711 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
712 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000713 // Suppose, W is the bitwidth of the return value. We must be prepared for
714 // overflow. Hence, we must assure that the result of our computation is
715 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
716 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000717 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000718 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000719 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000720 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
721 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000722 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000723 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000724 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000725 // This formula is trivially equivalent to the previous formula. However,
726 // this formula can be implemented much more efficiently. The trick is that
727 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
728 // arithmetic. To do exact division in modular arithmetic, all we have
729 // to do is multiply by the inverse. Therefore, this step can be done at
730 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000731 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000732 // The next issue is how to safely do the division by 2^T. The way this
733 // is done is by doing the multiplication step at a width of at least W + T
734 // bits. This way, the bottom W+T bits of the product are accurate. Then,
735 // when we perform the division by 2^T (which is equivalent to a right shift
736 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
737 // truncated out after the division by 2^T.
738 //
739 // In comparison to just directly using the first formula, this technique
740 // is much more efficient; using the first formula requires W * K bits,
741 // but this formula less than W + K bits. Also, the first formula requires
742 // a division step, whereas this formula only requires multiplies and shifts.
743 //
744 // It doesn't matter whether the subtraction step is done in the calculation
745 // width or the input iteration count's width; if the subtraction overflows,
746 // the result must be zero anyway. We prefer here to do it in the width of
747 // the induction variable because it helps a lot for certain cases; CodeGen
748 // isn't smart enough to ignore the overflow, which leads to much less
749 // efficient code if the width of the subtraction is wider than the native
750 // register width.
751 //
752 // (It's possible to not widen at all by pulling out factors of 2 before
753 // the multiplication; for example, K=2 can be calculated as
754 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
755 // extra arithmetic, so it's not an obvious win, and it gets
756 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000757
Eli Friedmanb42a6262008-08-04 23:49:06 +0000758 // Protection from insane SCEVs; this bound is conservative,
759 // but it probably doesn't matter.
760 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000761 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000762
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000763 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000764
Eli Friedmanb42a6262008-08-04 23:49:06 +0000765 // Calculate K! / 2^T and T; we divide out the factors of two before
766 // multiplying for calculating K! / 2^T to avoid overflow.
767 // Other overflow doesn't matter because we only care about the bottom
768 // W bits of the result.
769 APInt OddFactorial(W, 1);
770 unsigned T = 1;
771 for (unsigned i = 3; i <= K; ++i) {
772 APInt Mult(W, i);
773 unsigned TwoFactors = Mult.countTrailingZeros();
774 T += TwoFactors;
775 Mult = Mult.lshr(TwoFactors);
776 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000777 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000778
Eli Friedmanb42a6262008-08-04 23:49:06 +0000779 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000780 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000781
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000782 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000783 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
784
785 // Calculate the multiplicative inverse of K! / 2^T;
786 // this multiplication factor will perform the exact division by
787 // K! / 2^T.
788 APInt Mod = APInt::getSignedMinValue(W+1);
789 APInt MultiplyFactor = OddFactorial.zext(W+1);
790 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
791 MultiplyFactor = MultiplyFactor.trunc(W);
792
793 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000794 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
795 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000796 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000797 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000798 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000799 Dividend = SE.getMulExpr(Dividend,
800 SE.getTruncateOrZeroExtend(S, CalculationTy));
801 }
802
803 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000804 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000805
806 // Truncate the result, and divide by K! / 2^T.
807
808 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
809 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000810}
811
Chris Lattner53e677a2004-04-02 20:23:17 +0000812/// evaluateAtIteration - Return the value of this chain of recurrences at
813/// the specified iteration number. We can evaluate this recurrence by
814/// multiplying each element in the chain by the binomial coefficient
815/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
816///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000817/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000818///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000819/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000820///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000821const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000822 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000823 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000824 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000825 // The computation is correct in the face of overflow provided that the
826 // multiplication is performed _after_ the evaluation of the binomial
827 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000828 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000829 if (isa<SCEVCouldNotCompute>(Coeff))
830 return Coeff;
831
832 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000833 }
834 return Result;
835}
836
Chris Lattner53e677a2004-04-02 20:23:17 +0000837//===----------------------------------------------------------------------===//
838// SCEV Expression folder implementations
839//===----------------------------------------------------------------------===//
840
Dan Gohman0bba49c2009-07-07 17:06:11 +0000841const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000842 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000843 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000844 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000845 assert(isSCEVable(Ty) &&
846 "This is not a conversion to a SCEVable type!");
847 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000848
Dan Gohmanc050fd92009-07-13 20:50:19 +0000849 FoldingSetNodeID ID;
850 ID.AddInteger(scTruncate);
851 ID.AddPointer(Op);
852 ID.AddPointer(Ty);
853 void *IP = 0;
854 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
855
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000856 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000857 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000858 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000859 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
860 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000861
Dan Gohman20900ca2009-04-22 16:20:48 +0000862 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000863 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000864 return getTruncateExpr(ST->getOperand(), Ty);
865
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000866 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000867 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000868 return getTruncateOrSignExtend(SS->getOperand(), Ty);
869
870 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000871 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000872 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
873
Dan Gohman6864db62009-06-18 16:24:47 +0000874 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000875 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000876 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000877 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000878 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
879 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000880 }
881
Dan Gohmanf53462d2010-07-15 20:02:11 +0000882 // As a special case, fold trunc(undef) to undef. We don't want to
883 // know too much about SCEVUnknowns, but this special case is handy
884 // and harmless.
885 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
886 if (isa<UndefValue>(U->getValue()))
887 return getSCEV(UndefValue::get(Ty));
888
Dan Gohman420ab912010-06-25 18:47:08 +0000889 // The cast wasn't folded; create an explicit cast node. We can reuse
890 // the existing insert position since if we get here, we won't have
891 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000892 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
893 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000894 UniqueSCEVs.InsertNode(S, IP);
895 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000896}
897
Dan Gohman0bba49c2009-07-07 17:06:11 +0000898const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000899 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000900 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000901 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000902 assert(isSCEVable(Ty) &&
903 "This is not a conversion to a SCEVable type!");
904 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000905
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000906 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000907 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
908 return getConstant(
909 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
910 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000911
Dan Gohman20900ca2009-04-22 16:20:48 +0000912 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000913 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000914 return getZeroExtendExpr(SZ->getOperand(), Ty);
915
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000916 // Before doing any expensive analysis, check to see if we've already
917 // computed a SCEV for this Op and Ty.
918 FoldingSetNodeID ID;
919 ID.AddInteger(scZeroExtend);
920 ID.AddPointer(Op);
921 ID.AddPointer(Ty);
922 void *IP = 0;
923 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
924
Dan Gohman01ecca22009-04-27 20:16:15 +0000925 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000926 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000927 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000928 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000929 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000930 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000931 const SCEV *Start = AR->getStart();
932 const SCEV *Step = AR->getStepRecurrence(*this);
933 unsigned BitWidth = getTypeSizeInBits(AR->getType());
934 const Loop *L = AR->getLoop();
935
Dan Gohmaneb490a72009-07-25 01:22:26 +0000936 // If we have special knowledge that this addrec won't overflow,
937 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000938 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000939 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
940 getZeroExtendExpr(Step, Ty),
941 L);
942
Dan Gohman01ecca22009-04-27 20:16:15 +0000943 // Check whether the backedge-taken count is SCEVCouldNotCompute.
944 // Note that this serves two purposes: It filters out loops that are
945 // simply not analyzable, and it covers the case where this code is
946 // being called from within backedge-taken count analysis, such that
947 // attempting to ask for the backedge-taken count would likely result
948 // in infinite recursion. In the later case, the analysis code will
949 // cope with a conservative value, and it will take care to purge
950 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000951 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000952 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000953 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000954 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000955
956 // Check whether the backedge-taken count can be losslessly casted to
957 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000958 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000959 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000960 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000961 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
962 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000963 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000964 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000965 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000966 const SCEV *Add = getAddExpr(Start, ZMul);
967 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000968 getAddExpr(getZeroExtendExpr(Start, WideTy),
969 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
970 getZeroExtendExpr(Step, WideTy)));
971 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000972 // Return the expression with the addrec on the outside.
973 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
974 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000975 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000976
977 // Similar to above, only this time treat the step value as signed.
978 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000979 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000980 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000981 OperandExtendedAdd =
982 getAddExpr(getZeroExtendExpr(Start, WideTy),
983 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
984 getSignExtendExpr(Step, WideTy)));
985 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000986 // Return the expression with the addrec on the outside.
987 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
988 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000989 L);
990 }
991
992 // If the backedge is guarded by a comparison with the pre-inc value
993 // the addrec is safe. Also, if the entry is guarded by a comparison
994 // with the start value and the backedge is guarded by a comparison
995 // with the post-inc value, the addrec is safe.
996 if (isKnownPositive(Step)) {
997 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
998 getUnsignedRange(Step).getUnsignedMax());
999 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001000 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001001 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
1002 AR->getPostIncExpr(*this), N)))
1003 // Return the expression with the addrec on the outside.
1004 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1005 getZeroExtendExpr(Step, Ty),
1006 L);
1007 } else if (isKnownNegative(Step)) {
1008 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1009 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +00001010 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1011 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001012 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
1013 AR->getPostIncExpr(*this), N)))
1014 // Return the expression with the addrec on the outside.
1015 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1016 getSignExtendExpr(Step, Ty),
1017 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001018 }
1019 }
1020 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001021
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001022 // The cast wasn't folded; create an explicit cast node.
1023 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001024 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001025 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1026 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001027 UniqueSCEVs.InsertNode(S, IP);
1028 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001029}
1030
Dan Gohman0bba49c2009-07-07 17:06:11 +00001031const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00001032 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001033 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001034 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +00001035 assert(isSCEVable(Ty) &&
1036 "This is not a conversion to a SCEVable type!");
1037 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +00001038
Dan Gohmanc39f44b2009-06-30 20:13:32 +00001039 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +00001040 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1041 return getConstant(
1042 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
1043 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +00001044
Dan Gohman20900ca2009-04-22 16:20:48 +00001045 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +00001046 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +00001047 return getSignExtendExpr(SS->getOperand(), Ty);
1048
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001049 // Before doing any expensive analysis, check to see if we've already
1050 // computed a SCEV for this Op and Ty.
1051 FoldingSetNodeID ID;
1052 ID.AddInteger(scSignExtend);
1053 ID.AddPointer(Op);
1054 ID.AddPointer(Ty);
1055 void *IP = 0;
1056 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1057
Dan Gohman01ecca22009-04-27 20:16:15 +00001058 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001059 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001060 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001061 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001062 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001063 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001064 const SCEV *Start = AR->getStart();
1065 const SCEV *Step = AR->getStepRecurrence(*this);
1066 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1067 const Loop *L = AR->getLoop();
1068
Dan Gohmaneb490a72009-07-25 01:22:26 +00001069 // If we have special knowledge that this addrec won't overflow,
1070 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001071 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001072 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1073 getSignExtendExpr(Step, Ty),
1074 L);
1075
Dan Gohman01ecca22009-04-27 20:16:15 +00001076 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1077 // Note that this serves two purposes: It filters out loops that are
1078 // simply not analyzable, and it covers the case where this code is
1079 // being called from within backedge-taken count analysis, such that
1080 // attempting to ask for the backedge-taken count would likely result
1081 // in infinite recursion. In the later case, the analysis code will
1082 // cope with a conservative value, and it will take care to purge
1083 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001084 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001085 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001086 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001087 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001088
1089 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001090 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001091 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001092 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001093 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001094 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1095 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001096 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001097 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001098 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001099 const SCEV *Add = getAddExpr(Start, SMul);
1100 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001101 getAddExpr(getSignExtendExpr(Start, WideTy),
1102 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1103 getSignExtendExpr(Step, WideTy)));
1104 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001105 // Return the expression with the addrec on the outside.
1106 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1107 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001108 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001109
1110 // Similar to above, only this time treat the step value as unsigned.
1111 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001112 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001113 Add = getAddExpr(Start, UMul);
1114 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001115 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001116 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1117 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001118 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001119 // Return the expression with the addrec on the outside.
1120 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1121 getZeroExtendExpr(Step, Ty),
1122 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001123 }
1124
1125 // If the backedge is guarded by a comparison with the pre-inc value
1126 // the addrec is safe. Also, if the entry is guarded by a comparison
1127 // with the start value and the backedge is guarded by a comparison
1128 // with the post-inc value, the addrec is safe.
1129 if (isKnownPositive(Step)) {
1130 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1131 getSignedRange(Step).getSignedMax());
1132 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001133 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001134 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1135 AR->getPostIncExpr(*this), N)))
1136 // Return the expression with the addrec on the outside.
1137 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1138 getSignExtendExpr(Step, Ty),
1139 L);
1140 } else if (isKnownNegative(Step)) {
1141 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1142 getSignedRange(Step).getSignedMin());
1143 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001144 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001145 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1146 AR->getPostIncExpr(*this), N)))
1147 // Return the expression with the addrec on the outside.
1148 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1149 getSignExtendExpr(Step, Ty),
1150 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001151 }
1152 }
1153 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001154
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001155 // The cast wasn't folded; create an explicit cast node.
1156 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001157 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001158 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1159 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001160 UniqueSCEVs.InsertNode(S, IP);
1161 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001162}
1163
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001164/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1165/// unspecified bits out to the given type.
1166///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001167const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001168 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001169 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1170 "This is not an extending conversion!");
1171 assert(isSCEVable(Ty) &&
1172 "This is not a conversion to a SCEVable type!");
1173 Ty = getEffectiveSCEVType(Ty);
1174
1175 // Sign-extend negative constants.
1176 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1177 if (SC->getValue()->getValue().isNegative())
1178 return getSignExtendExpr(Op, Ty);
1179
1180 // Peel off a truncate cast.
1181 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001182 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001183 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1184 return getAnyExtendExpr(NewOp, Ty);
1185 return getTruncateOrNoop(NewOp, Ty);
1186 }
1187
1188 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001189 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001190 if (!isa<SCEVZeroExtendExpr>(ZExt))
1191 return ZExt;
1192
1193 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001194 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001195 if (!isa<SCEVSignExtendExpr>(SExt))
1196 return SExt;
1197
Dan Gohmana10756e2010-01-21 02:09:26 +00001198 // Force the cast to be folded into the operands of an addrec.
1199 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1200 SmallVector<const SCEV *, 4> Ops;
1201 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1202 I != E; ++I)
1203 Ops.push_back(getAnyExtendExpr(*I, Ty));
1204 return getAddRecExpr(Ops, AR->getLoop());
1205 }
1206
Dan Gohmanf53462d2010-07-15 20:02:11 +00001207 // As a special case, fold anyext(undef) to undef. We don't want to
1208 // know too much about SCEVUnknowns, but this special case is handy
1209 // and harmless.
1210 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1211 if (isa<UndefValue>(U->getValue()))
1212 return getSCEV(UndefValue::get(Ty));
1213
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001214 // If the expression is obviously signed, use the sext cast value.
1215 if (isa<SCEVSMaxExpr>(Op))
1216 return SExt;
1217
1218 // Absent any other information, use the zext cast value.
1219 return ZExt;
1220}
1221
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001222/// CollectAddOperandsWithScales - Process the given Ops list, which is
1223/// a list of operands to be added under the given scale, update the given
1224/// map. This is a helper function for getAddRecExpr. As an example of
1225/// what it does, given a sequence of operands that would form an add
1226/// expression like this:
1227///
1228/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1229///
1230/// where A and B are constants, update the map with these values:
1231///
1232/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1233///
1234/// and add 13 + A*B*29 to AccumulatedConstant.
1235/// This will allow getAddRecExpr to produce this:
1236///
1237/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1238///
1239/// This form often exposes folding opportunities that are hidden in
1240/// the original operand list.
1241///
1242/// Return true iff it appears that any interesting folding opportunities
1243/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1244/// the common case where no interesting opportunities are present, and
1245/// is also used as a check to avoid infinite recursion.
1246///
1247static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001248CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1249 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001250 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001251 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001252 const APInt &Scale,
1253 ScalarEvolution &SE) {
1254 bool Interesting = false;
1255
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001256 // Iterate over the add operands. They are sorted, with constants first.
1257 unsigned i = 0;
1258 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1259 ++i;
1260 // Pull a buried constant out to the outside.
1261 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1262 Interesting = true;
1263 AccumulatedConstant += Scale * C->getValue()->getValue();
1264 }
1265
1266 // Next comes everything else. We're especially interested in multiplies
1267 // here, but they're in the middle, so just visit the rest with one loop.
1268 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001269 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1270 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1271 APInt NewScale =
1272 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1273 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1274 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001275 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001276 Interesting |=
1277 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001278 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001279 NewScale, SE);
1280 } else {
1281 // A multiplication of a constant with some other value. Update
1282 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001283 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1284 const SCEV *Key = SE.getMulExpr(MulOps);
1285 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001286 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001287 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001288 NewOps.push_back(Pair.first->first);
1289 } else {
1290 Pair.first->second += NewScale;
1291 // The map already had an entry for this value, which may indicate
1292 // a folding opportunity.
1293 Interesting = true;
1294 }
1295 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001296 } else {
1297 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001298 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001299 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001300 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001301 NewOps.push_back(Pair.first->first);
1302 } else {
1303 Pair.first->second += Scale;
1304 // The map already had an entry for this value, which may indicate
1305 // a folding opportunity.
1306 Interesting = true;
1307 }
1308 }
1309 }
1310
1311 return Interesting;
1312}
1313
1314namespace {
1315 struct APIntCompare {
1316 bool operator()(const APInt &LHS, const APInt &RHS) const {
1317 return LHS.ult(RHS);
1318 }
1319 };
1320}
1321
Dan Gohman6c0866c2009-05-24 23:45:28 +00001322/// getAddExpr - Get a canonical add expression, or something simpler if
1323/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001324const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1325 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001326 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001327 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001328#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001329 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001330 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001331 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001332 "SCEVAddExpr operand types don't match!");
1333#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001334
Dan Gohmana10756e2010-01-21 02:09:26 +00001335 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1336 if (!HasNUW && HasNSW) {
1337 bool All = true;
1338 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1339 if (!isKnownNonNegative(Ops[i])) {
1340 All = false;
1341 break;
1342 }
1343 if (All) HasNUW = true;
1344 }
1345
Chris Lattner53e677a2004-04-02 20:23:17 +00001346 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001347 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001348
1349 // If there are any constants, fold them together.
1350 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001351 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001352 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001353 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001354 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001355 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001356 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1357 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001358 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001359 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001360 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001361 }
1362
1363 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001364 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001365 Ops.erase(Ops.begin());
1366 --Idx;
1367 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001368
Dan Gohmanbca091d2010-04-12 23:08:18 +00001369 if (Ops.size() == 1) return Ops[0];
1370 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001371
Chris Lattner53e677a2004-04-02 20:23:17 +00001372 // Okay, check to see if the same value occurs in the operand list twice. If
1373 // so, merge them together into an multiply expression. Since we sorted the
1374 // list, these values are required to be adjacent.
1375 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001376 bool FoundMatch = false;
Chris Lattner53e677a2004-04-02 20:23:17 +00001377 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1378 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1379 // Found a match, merge the two values into a multiply, and add any
1380 // remaining values to the result.
Dan Gohmandeff6212010-05-03 22:09:21 +00001381 const SCEV *Two = getConstant(Ty, 2);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001382 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001383 if (Ops.size() == 2)
1384 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001385 Ops[i] = Mul;
1386 Ops.erase(Ops.begin()+i+1);
1387 --i; --e;
1388 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001389 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001390 if (FoundMatch)
1391 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001392
Dan Gohman728c7f32009-05-08 21:03:19 +00001393 // Check for truncates. If all the operands are truncated from the same
1394 // type, see if factoring out the truncate would permit the result to be
1395 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1396 // if the contents of the resulting outer trunc fold to something simple.
1397 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1398 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1399 const Type *DstType = Trunc->getType();
1400 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001401 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001402 bool Ok = true;
1403 // Check all the operands to see if they can be represented in the
1404 // source type of the truncate.
1405 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1406 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1407 if (T->getOperand()->getType() != SrcType) {
1408 Ok = false;
1409 break;
1410 }
1411 LargeOps.push_back(T->getOperand());
1412 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001413 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001414 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001415 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001416 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1417 if (const SCEVTruncateExpr *T =
1418 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1419 if (T->getOperand()->getType() != SrcType) {
1420 Ok = false;
1421 break;
1422 }
1423 LargeMulOps.push_back(T->getOperand());
1424 } else if (const SCEVConstant *C =
1425 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001426 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001427 } else {
1428 Ok = false;
1429 break;
1430 }
1431 }
1432 if (Ok)
1433 LargeOps.push_back(getMulExpr(LargeMulOps));
1434 } else {
1435 Ok = false;
1436 break;
1437 }
1438 }
1439 if (Ok) {
1440 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001441 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001442 // If it folds to something simple, use it. Otherwise, don't.
1443 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1444 return getTruncateExpr(Fold, DstType);
1445 }
1446 }
1447
1448 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001449 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1450 ++Idx;
1451
1452 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001453 if (Idx < Ops.size()) {
1454 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001455 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001456 // If we have an add, expand the add operands onto the end of the operands
1457 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001458 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001459 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 DeletedAdd = true;
1461 }
1462
1463 // If we deleted at least one add, we added operands to the end of the list,
1464 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001465 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001466 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001467 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 }
1469
1470 // Skip over the add expression until we get to a multiply.
1471 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1472 ++Idx;
1473
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001474 // Check to see if there are any folding opportunities present with
1475 // operands multiplied by constant values.
1476 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1477 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001478 DenseMap<const SCEV *, APInt> M;
1479 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001480 APInt AccumulatedConstant(BitWidth, 0);
1481 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001482 Ops.data(), Ops.size(),
1483 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001484 // Some interesting folding opportunity is present, so its worthwhile to
1485 // re-generate the operands list. Group the operands by constant scale,
1486 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001487 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1488 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001489 E = NewOps.end(); I != E; ++I)
1490 MulOpLists[M.find(*I)->second].push_back(*I);
1491 // Re-generate the operands list.
1492 Ops.clear();
1493 if (AccumulatedConstant != 0)
1494 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001495 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1496 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001497 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001498 Ops.push_back(getMulExpr(getConstant(I->first),
1499 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001500 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001501 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001502 if (Ops.size() == 1)
1503 return Ops[0];
1504 return getAddExpr(Ops);
1505 }
1506 }
1507
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 // If we are adding something to a multiply expression, make sure the
1509 // something is not already an operand of the multiply. If so, merge it into
1510 // the multiply.
1511 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001512 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001513 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001514 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001515 if (isa<SCEVConstant>(MulOpSCEV))
1516 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001517 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001518 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001519 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001520 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001521 if (Mul->getNumOperands() != 2) {
1522 // If the multiply has more than two operands, we must get the
1523 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001524 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001525 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001526 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001527 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001528 const SCEV *One = getConstant(Ty, 1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001529 const SCEV *AddOne = getAddExpr(InnerMul, One);
Dan Gohman918e76b2010-08-12 14:52:55 +00001530 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001531 if (Ops.size() == 2) return OuterMul;
1532 if (AddOp < Idx) {
1533 Ops.erase(Ops.begin()+AddOp);
1534 Ops.erase(Ops.begin()+Idx-1);
1535 } else {
1536 Ops.erase(Ops.begin()+Idx);
1537 Ops.erase(Ops.begin()+AddOp-1);
1538 }
1539 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001540 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001541 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001542
Chris Lattner53e677a2004-04-02 20:23:17 +00001543 // Check this multiply against other multiplies being added together.
1544 for (unsigned OtherMulIdx = Idx+1;
1545 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1546 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001547 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001548 // If MulOp occurs in OtherMul, we can fold the two multiplies
1549 // together.
1550 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1551 OMulOp != e; ++OMulOp)
1552 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1553 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001554 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001555 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001556 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1557 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001558 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001559 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001560 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001561 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001562 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001563 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1564 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001565 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001566 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001567 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001568 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1569 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001570 if (Ops.size() == 2) return OuterMul;
1571 Ops.erase(Ops.begin()+Idx);
1572 Ops.erase(Ops.begin()+OtherMulIdx-1);
1573 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001574 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 }
1576 }
1577 }
1578 }
1579
1580 // If there are any add recurrences in the operands list, see if any other
1581 // added values are loop invariant. If so, we can fold them into the
1582 // recurrence.
1583 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1584 ++Idx;
1585
1586 // Scan over all recurrences, trying to fold loop invariants into them.
1587 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1588 // Scan all of the other operands to this add and add them to the vector if
1589 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001590 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001591 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001592 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001593 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanbca091d2010-04-12 23:08:18 +00001594 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 LIOps.push_back(Ops[i]);
1596 Ops.erase(Ops.begin()+i);
1597 --i; --e;
1598 }
1599
1600 // If we found some loop invariants, fold them into the recurrence.
1601 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001602 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001603 LIOps.push_back(AddRec->getStart());
1604
Dan Gohman0bba49c2009-07-07 17:06:11 +00001605 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001606 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001607 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001608
Dan Gohmanb9f96512010-06-30 07:16:37 +00001609 // Build the new addrec. Propagate the NUW and NSW flags if both the
1610 // outer add and the inner addrec are guaranteed to have no overflow.
1611 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1612 HasNUW && AddRec->hasNoUnsignedWrap(),
1613 HasNSW && AddRec->hasNoSignedWrap());
Dan Gohman59de33e2009-12-18 18:45:31 +00001614
Chris Lattner53e677a2004-04-02 20:23:17 +00001615 // If all of the other operands were loop invariant, we are done.
1616 if (Ops.size() == 1) return NewRec;
1617
1618 // Otherwise, add the folded AddRec by the non-liv parts.
1619 for (unsigned i = 0;; ++i)
1620 if (Ops[i] == AddRec) {
1621 Ops[i] = NewRec;
1622 break;
1623 }
Dan Gohman246b2562007-10-22 18:31:58 +00001624 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001625 }
1626
1627 // Okay, if there weren't any loop invariants to be folded, check to see if
1628 // there are multiple AddRec's with the same loop induction variable being
1629 // added together. If so, we can fold them.
1630 for (unsigned OtherIdx = Idx+1;
1631 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1632 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001633 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001634 if (AddRecLoop == OtherAddRec->getLoop()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001635 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001636 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1637 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001638 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1639 if (i >= NewOps.size()) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001640 NewOps.append(OtherAddRec->op_begin()+i,
Chris Lattner53e677a2004-04-02 20:23:17 +00001641 OtherAddRec->op_end());
1642 break;
1643 }
Dan Gohman246b2562007-10-22 18:31:58 +00001644 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001645 }
Dan Gohmanbca091d2010-04-12 23:08:18 +00001646 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +00001647
1648 if (Ops.size() == 2) return NewAddRec;
1649
1650 Ops.erase(Ops.begin()+Idx);
1651 Ops.erase(Ops.begin()+OtherIdx-1);
1652 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001653 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001654 }
1655 }
1656
1657 // Otherwise couldn't fold anything into this recurrence. Move onto the
1658 // next one.
1659 }
1660
1661 // Okay, it looks like we really DO need an add expr. Check to see if we
1662 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001663 FoldingSetNodeID ID;
1664 ID.AddInteger(scAddExpr);
1665 ID.AddInteger(Ops.size());
1666 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1667 ID.AddPointer(Ops[i]);
1668 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001669 SCEVAddExpr *S =
1670 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1671 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001672 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1673 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001674 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1675 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001676 UniqueSCEVs.InsertNode(S, IP);
1677 }
Dan Gohman3645b012009-10-09 00:10:36 +00001678 if (HasNUW) S->setHasNoUnsignedWrap(true);
1679 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001680 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001681}
1682
Dan Gohman6c0866c2009-05-24 23:45:28 +00001683/// getMulExpr - Get a canonical multiply expression, or something simpler if
1684/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001685const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1686 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001687 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001688 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001689#ifndef NDEBUG
1690 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1691 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1692 getEffectiveSCEVType(Ops[0]->getType()) &&
1693 "SCEVMulExpr operand types don't match!");
1694#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001695
Dan Gohmana10756e2010-01-21 02:09:26 +00001696 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1697 if (!HasNUW && HasNSW) {
1698 bool All = true;
1699 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1700 if (!isKnownNonNegative(Ops[i])) {
1701 All = false;
1702 break;
1703 }
1704 if (All) HasNUW = true;
1705 }
1706
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001708 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001709
1710 // If there are any constants, fold them together.
1711 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001712 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001713
1714 // C1*(C2+V) -> C1*C2 + C1*V
1715 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001716 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001717 if (Add->getNumOperands() == 2 &&
1718 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001719 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1720 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001721
Chris Lattner53e677a2004-04-02 20:23:17 +00001722 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001723 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001724 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001725 ConstantInt *Fold = ConstantInt::get(getContext(),
1726 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001727 RHSC->getValue()->getValue());
1728 Ops[0] = getConstant(Fold);
1729 Ops.erase(Ops.begin()+1); // Erase the folded element
1730 if (Ops.size() == 1) return Ops[0];
1731 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001732 }
1733
1734 // If we are left with a constant one being multiplied, strip it off.
1735 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1736 Ops.erase(Ops.begin());
1737 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001738 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001739 // If we have a multiply of zero, it will always be zero.
1740 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001741 } else if (Ops[0]->isAllOnesValue()) {
1742 // If we have a mul by -1 of an add, try distributing the -1 among the
1743 // add operands.
1744 if (Ops.size() == 2)
1745 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1746 SmallVector<const SCEV *, 4> NewOps;
1747 bool AnyFolded = false;
1748 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1749 I != E; ++I) {
1750 const SCEV *Mul = getMulExpr(Ops[0], *I);
1751 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1752 NewOps.push_back(Mul);
1753 }
1754 if (AnyFolded)
1755 return getAddExpr(NewOps);
1756 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001757 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001758
1759 if (Ops.size() == 1)
1760 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001761 }
1762
1763 // Skip over the add expression until we get to a multiply.
1764 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1765 ++Idx;
1766
Chris Lattner53e677a2004-04-02 20:23:17 +00001767 // If there are mul operands inline them all into this expression.
1768 if (Idx < Ops.size()) {
1769 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001770 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001771 // If we have an mul, expand the mul operands onto the end of the operands
1772 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001773 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001774 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001775 DeletedMul = true;
1776 }
1777
1778 // If we deleted at least one mul, we added operands to the end of the list,
1779 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001780 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001781 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001782 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001783 }
1784
1785 // If there are any add recurrences in the operands list, see if any other
1786 // added values are loop invariant. If so, we can fold them into the
1787 // recurrence.
1788 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1789 ++Idx;
1790
1791 // Scan over all recurrences, trying to fold loop invariants into them.
1792 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1793 // Scan all of the other operands to this mul and add them to the vector if
1794 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001795 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001796 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001797 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1798 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1799 LIOps.push_back(Ops[i]);
1800 Ops.erase(Ops.begin()+i);
1801 --i; --e;
1802 }
1803
1804 // If we found some loop invariants, fold them into the recurrence.
1805 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001806 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001807 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001808 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001809 const SCEV *Scale = getMulExpr(LIOps);
1810 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1811 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001812
Dan Gohmanb9f96512010-06-30 07:16:37 +00001813 // Build the new addrec. Propagate the NUW and NSW flags if both the
1814 // outer mul and the inner addrec are guaranteed to have no overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00001815 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1816 HasNUW && AddRec->hasNoUnsignedWrap(),
Dan Gohmanb9f96512010-06-30 07:16:37 +00001817 HasNSW && AddRec->hasNoSignedWrap());
Chris Lattner53e677a2004-04-02 20:23:17 +00001818
1819 // If all of the other operands were loop invariant, we are done.
1820 if (Ops.size() == 1) return NewRec;
1821
1822 // Otherwise, multiply the folded AddRec by the non-liv parts.
1823 for (unsigned i = 0;; ++i)
1824 if (Ops[i] == AddRec) {
1825 Ops[i] = NewRec;
1826 break;
1827 }
Dan Gohman246b2562007-10-22 18:31:58 +00001828 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001829 }
1830
1831 // Okay, if there weren't any loop invariants to be folded, check to see if
1832 // there are multiple AddRec's with the same loop induction variable being
1833 // multiplied together. If so, we can fold them.
1834 for (unsigned OtherIdx = Idx+1;
1835 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1836 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001837 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001838 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1839 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001840 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001841 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001842 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001843 const SCEV *B = F->getStepRecurrence(*this);
1844 const SCEV *D = G->getStepRecurrence(*this);
1845 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001846 getMulExpr(G, B),
1847 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001848 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001849 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001850 if (Ops.size() == 2) return NewAddRec;
1851
1852 Ops.erase(Ops.begin()+Idx);
1853 Ops.erase(Ops.begin()+OtherIdx-1);
1854 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001855 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001856 }
1857 }
1858
1859 // Otherwise couldn't fold anything into this recurrence. Move onto the
1860 // next one.
1861 }
1862
1863 // Okay, it looks like we really DO need an mul expr. Check to see if we
1864 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001865 FoldingSetNodeID ID;
1866 ID.AddInteger(scMulExpr);
1867 ID.AddInteger(Ops.size());
1868 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1869 ID.AddPointer(Ops[i]);
1870 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001871 SCEVMulExpr *S =
1872 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1873 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001874 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1875 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001876 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1877 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001878 UniqueSCEVs.InsertNode(S, IP);
1879 }
Dan Gohman3645b012009-10-09 00:10:36 +00001880 if (HasNUW) S->setHasNoUnsignedWrap(true);
1881 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001882 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001883}
1884
Andreas Bolka8a11c982009-08-07 22:55:26 +00001885/// getUDivExpr - Get a canonical unsigned division expression, or something
1886/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001887const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1888 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001889 assert(getEffectiveSCEVType(LHS->getType()) ==
1890 getEffectiveSCEVType(RHS->getType()) &&
1891 "SCEVUDivExpr operand types don't match!");
1892
Dan Gohman622ed672009-05-04 22:02:23 +00001893 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001894 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001895 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001896 // If the denominator is zero, the result of the udiv is undefined. Don't
1897 // try to analyze it, because the resolution chosen here may differ from
1898 // the resolution chosen in other parts of the compiler.
1899 if (!RHSC->getValue()->isZero()) {
1900 // Determine if the division can be folded into the operands of
1901 // its operands.
1902 // TODO: Generalize this to non-constants by using known-bits information.
1903 const Type *Ty = LHS->getType();
1904 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001905 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001906 // For non-power-of-two values, effectively round the value up to the
1907 // nearest power of two.
1908 if (!RHSC->getValue()->getValue().isPowerOf2())
1909 ++MaxShiftAmt;
1910 const IntegerType *ExtTy =
1911 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1912 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1913 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1914 if (const SCEVConstant *Step =
1915 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1916 if (!Step->getValue()->getValue()
1917 .urem(RHSC->getValue()->getValue()) &&
1918 getZeroExtendExpr(AR, ExtTy) ==
1919 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1920 getZeroExtendExpr(Step, ExtTy),
1921 AR->getLoop())) {
1922 SmallVector<const SCEV *, 4> Operands;
1923 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1924 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1925 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001926 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001927 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1928 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1929 SmallVector<const SCEV *, 4> Operands;
1930 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1931 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1932 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1933 // Find an operand that's safely divisible.
1934 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1935 const SCEV *Op = M->getOperand(i);
1936 const SCEV *Div = getUDivExpr(Op, RHSC);
1937 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1938 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1939 M->op_end());
1940 Operands[i] = Div;
1941 return getMulExpr(Operands);
1942 }
1943 }
Dan Gohman185cf032009-05-08 20:18:49 +00001944 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001945 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1946 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1947 SmallVector<const SCEV *, 4> Operands;
1948 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1949 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1950 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1951 Operands.clear();
1952 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1953 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1954 if (isa<SCEVUDivExpr>(Op) ||
1955 getMulExpr(Op, RHS) != A->getOperand(i))
1956 break;
1957 Operands.push_back(Op);
1958 }
1959 if (Operands.size() == A->getNumOperands())
1960 return getAddExpr(Operands);
1961 }
1962 }
Dan Gohman185cf032009-05-08 20:18:49 +00001963
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001964 // Fold if both operands are constant.
1965 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1966 Constant *LHSCV = LHSC->getValue();
1967 Constant *RHSCV = RHSC->getValue();
1968 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1969 RHSCV)));
1970 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001971 }
1972 }
1973
Dan Gohman1c343752009-06-27 21:21:31 +00001974 FoldingSetNodeID ID;
1975 ID.AddInteger(scUDivExpr);
1976 ID.AddPointer(LHS);
1977 ID.AddPointer(RHS);
1978 void *IP = 0;
1979 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001980 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1981 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001982 UniqueSCEVs.InsertNode(S, IP);
1983 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001984}
1985
1986
Dan Gohman6c0866c2009-05-24 23:45:28 +00001987/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1988/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001989const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001990 const SCEV *Step, const Loop *L,
1991 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001992 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001993 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001994 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001995 if (StepChrec->getLoop() == L) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001996 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001997 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001998 }
1999
2000 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00002001 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002002}
2003
Dan Gohman6c0866c2009-05-24 23:45:28 +00002004/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2005/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00002006const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00002007ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00002008 const Loop *L,
2009 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002010 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002011#ifndef NDEBUG
2012 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
2013 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
2014 getEffectiveSCEVType(Operands[0]->getType()) &&
2015 "SCEVAddRecExpr operand types don't match!");
2016#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002017
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002018 if (Operands.back()->isZero()) {
2019 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00002020 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002021 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002022
Dan Gohmanbc028532010-02-19 18:49:22 +00002023 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2024 // use that information to infer NUW and NSW flags. However, computing a
2025 // BE count requires calling getAddRecExpr, so we may not yet have a
2026 // meaningful BE count at this point (and if we don't, we'd be stuck
2027 // with a SCEVCouldNotCompute as the cached BE count).
2028
Dan Gohmana10756e2010-01-21 02:09:26 +00002029 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
2030 if (!HasNUW && HasNSW) {
2031 bool All = true;
2032 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2033 if (!isKnownNonNegative(Operands[i])) {
2034 All = false;
2035 break;
2036 }
2037 if (All) HasNUW = true;
2038 }
2039
Dan Gohmand9cc7492008-08-08 18:33:12 +00002040 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00002041 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00002042 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00002043 if (L->contains(NestedLoop->getHeader()) ?
2044 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
2045 (!NestedLoop->contains(L->getHeader()) &&
2046 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002047 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00002048 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00002049 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00002050 // AddRecs require their operands be loop-invariant with respect to their
2051 // loops. Don't perform this transformation if it would break this
2052 // requirement.
2053 bool AllInvariant = true;
2054 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2055 if (!Operands[i]->isLoopInvariant(L)) {
2056 AllInvariant = false;
2057 break;
2058 }
2059 if (AllInvariant) {
2060 NestedOperands[0] = getAddRecExpr(Operands, L);
2061 AllInvariant = true;
2062 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
2063 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
2064 AllInvariant = false;
2065 break;
2066 }
2067 if (AllInvariant)
2068 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002069 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002070 }
2071 // Reset Operands to its original state.
2072 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002073 }
2074 }
2075
Dan Gohman67847532010-01-19 22:27:22 +00002076 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2077 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002078 FoldingSetNodeID ID;
2079 ID.AddInteger(scAddRecExpr);
2080 ID.AddInteger(Operands.size());
2081 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2082 ID.AddPointer(Operands[i]);
2083 ID.AddPointer(L);
2084 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002085 SCEVAddRecExpr *S =
2086 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2087 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002088 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2089 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002090 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2091 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002092 UniqueSCEVs.InsertNode(S, IP);
2093 }
Dan Gohman3645b012009-10-09 00:10:36 +00002094 if (HasNUW) S->setHasNoUnsignedWrap(true);
2095 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002096 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002097}
2098
Dan Gohman9311ef62009-06-24 14:49:00 +00002099const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2100 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002101 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002102 Ops.push_back(LHS);
2103 Ops.push_back(RHS);
2104 return getSMaxExpr(Ops);
2105}
2106
Dan Gohman0bba49c2009-07-07 17:06:11 +00002107const SCEV *
2108ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002109 assert(!Ops.empty() && "Cannot get empty smax!");
2110 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002111#ifndef NDEBUG
2112 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2113 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2114 getEffectiveSCEVType(Ops[0]->getType()) &&
2115 "SCEVSMaxExpr operand types don't match!");
2116#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002117
2118 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002119 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002120
2121 // If there are any constants, fold them together.
2122 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002123 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002124 ++Idx;
2125 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002126 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002127 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002128 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002129 APIntOps::smax(LHSC->getValue()->getValue(),
2130 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002131 Ops[0] = getConstant(Fold);
2132 Ops.erase(Ops.begin()+1); // Erase the folded element
2133 if (Ops.size() == 1) return Ops[0];
2134 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002135 }
2136
Dan Gohmane5aceed2009-06-24 14:46:22 +00002137 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002138 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2139 Ops.erase(Ops.begin());
2140 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002141 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2142 // If we have an smax with a constant maximum-int, it will always be
2143 // maximum-int.
2144 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002145 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002146
Dan Gohman3ab13122010-04-13 16:49:23 +00002147 if (Ops.size() == 1) return Ops[0];
2148 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002149
2150 // Find the first SMax
2151 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2152 ++Idx;
2153
2154 // Check to see if one of the operands is an SMax. If so, expand its operands
2155 // onto our operand list, and recurse to simplify.
2156 if (Idx < Ops.size()) {
2157 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002158 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002159 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002160 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002161 DeletedSMax = true;
2162 }
2163
2164 if (DeletedSMax)
2165 return getSMaxExpr(Ops);
2166 }
2167
2168 // Okay, check to see if the same value occurs in the operand list twice. If
2169 // so, delete one. Since we sorted the list, these values are required to
2170 // be adjacent.
2171 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002172 // X smax Y smax Y --> X smax Y
2173 // X smax Y --> X, if X is always greater than Y
2174 if (Ops[i] == Ops[i+1] ||
2175 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2176 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2177 --i; --e;
2178 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002179 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2180 --i; --e;
2181 }
2182
2183 if (Ops.size() == 1) return Ops[0];
2184
2185 assert(!Ops.empty() && "Reduced smax down to nothing!");
2186
Nick Lewycky3e630762008-02-20 06:48:22 +00002187 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002188 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002189 FoldingSetNodeID ID;
2190 ID.AddInteger(scSMaxExpr);
2191 ID.AddInteger(Ops.size());
2192 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2193 ID.AddPointer(Ops[i]);
2194 void *IP = 0;
2195 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002196 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2197 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002198 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2199 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002200 UniqueSCEVs.InsertNode(S, IP);
2201 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002202}
2203
Dan Gohman9311ef62009-06-24 14:49:00 +00002204const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2205 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002206 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002207 Ops.push_back(LHS);
2208 Ops.push_back(RHS);
2209 return getUMaxExpr(Ops);
2210}
2211
Dan Gohman0bba49c2009-07-07 17:06:11 +00002212const SCEV *
2213ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002214 assert(!Ops.empty() && "Cannot get empty umax!");
2215 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002216#ifndef NDEBUG
2217 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2218 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2219 getEffectiveSCEVType(Ops[0]->getType()) &&
2220 "SCEVUMaxExpr operand types don't match!");
2221#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002222
2223 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002224 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002225
2226 // If there are any constants, fold them together.
2227 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002228 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002229 ++Idx;
2230 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002231 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002232 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002233 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002234 APIntOps::umax(LHSC->getValue()->getValue(),
2235 RHSC->getValue()->getValue()));
2236 Ops[0] = getConstant(Fold);
2237 Ops.erase(Ops.begin()+1); // Erase the folded element
2238 if (Ops.size() == 1) return Ops[0];
2239 LHSC = cast<SCEVConstant>(Ops[0]);
2240 }
2241
Dan Gohmane5aceed2009-06-24 14:46:22 +00002242 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002243 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2244 Ops.erase(Ops.begin());
2245 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002246 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2247 // If we have an umax with a constant maximum-int, it will always be
2248 // maximum-int.
2249 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002250 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002251
Dan Gohman3ab13122010-04-13 16:49:23 +00002252 if (Ops.size() == 1) return Ops[0];
2253 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002254
2255 // Find the first UMax
2256 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2257 ++Idx;
2258
2259 // Check to see if one of the operands is a UMax. If so, expand its operands
2260 // onto our operand list, and recurse to simplify.
2261 if (Idx < Ops.size()) {
2262 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002263 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002264 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002265 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002266 DeletedUMax = true;
2267 }
2268
2269 if (DeletedUMax)
2270 return getUMaxExpr(Ops);
2271 }
2272
2273 // Okay, check to see if the same value occurs in the operand list twice. If
2274 // so, delete one. Since we sorted the list, these values are required to
2275 // be adjacent.
2276 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002277 // X umax Y umax Y --> X umax Y
2278 // X umax Y --> X, if X is always greater than Y
2279 if (Ops[i] == Ops[i+1] ||
2280 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2281 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2282 --i; --e;
2283 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002284 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2285 --i; --e;
2286 }
2287
2288 if (Ops.size() == 1) return Ops[0];
2289
2290 assert(!Ops.empty() && "Reduced umax down to nothing!");
2291
2292 // Okay, it looks like we really DO need a umax expr. Check to see if we
2293 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002294 FoldingSetNodeID ID;
2295 ID.AddInteger(scUMaxExpr);
2296 ID.AddInteger(Ops.size());
2297 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2298 ID.AddPointer(Ops[i]);
2299 void *IP = 0;
2300 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002301 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2302 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002303 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2304 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002305 UniqueSCEVs.InsertNode(S, IP);
2306 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002307}
2308
Dan Gohman9311ef62009-06-24 14:49:00 +00002309const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2310 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002311 // ~smax(~x, ~y) == smin(x, y).
2312 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2313}
2314
Dan Gohman9311ef62009-06-24 14:49:00 +00002315const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2316 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002317 // ~umax(~x, ~y) == umin(x, y)
2318 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2319}
2320
Dan Gohman4f8eea82010-02-01 18:27:38 +00002321const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002322 // If we have TargetData, we can bypass creating a target-independent
2323 // constant expression and then folding it back into a ConstantInt.
2324 // This is just a compile-time optimization.
2325 if (TD)
2326 return getConstant(TD->getIntPtrType(getContext()),
2327 TD->getTypeAllocSize(AllocTy));
2328
Dan Gohman4f8eea82010-02-01 18:27:38 +00002329 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2330 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002331 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2332 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002333 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2334 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2335}
2336
2337const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2338 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2339 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002340 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2341 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002342 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2343 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2344}
2345
2346const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2347 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002348 // If we have TargetData, we can bypass creating a target-independent
2349 // constant expression and then folding it back into a ConstantInt.
2350 // This is just a compile-time optimization.
2351 if (TD)
2352 return getConstant(TD->getIntPtrType(getContext()),
2353 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2354
Dan Gohman0f5efe52010-01-28 02:15:55 +00002355 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2356 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002357 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2358 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002359 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002360 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002361}
2362
Dan Gohman4f8eea82010-02-01 18:27:38 +00002363const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2364 Constant *FieldNo) {
2365 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002366 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002367 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2368 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002369 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002370 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002371}
2372
Dan Gohman0bba49c2009-07-07 17:06:11 +00002373const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002374 // Don't attempt to do anything other than create a SCEVUnknown object
2375 // here. createSCEV only calls getUnknown after checking for all other
2376 // interesting possibilities, and any other code that calls getUnknown
2377 // is doing so in order to hide a value from SCEV canonicalization.
2378
Dan Gohman1c343752009-06-27 21:21:31 +00002379 FoldingSetNodeID ID;
2380 ID.AddInteger(scUnknown);
2381 ID.AddPointer(V);
2382 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002383 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2384 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2385 "Stale SCEVUnknown in uniquing map!");
2386 return S;
2387 }
2388 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2389 FirstUnknown);
2390 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002391 UniqueSCEVs.InsertNode(S, IP);
2392 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002393}
2394
Chris Lattner53e677a2004-04-02 20:23:17 +00002395//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002396// Basic SCEV Analysis and PHI Idiom Recognition Code
2397//
2398
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002399/// isSCEVable - Test if values of the given type are analyzable within
2400/// the SCEV framework. This primarily includes integer types, and it
2401/// can optionally include pointer types if the ScalarEvolution class
2402/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002403bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002404 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002405 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002406}
2407
2408/// getTypeSizeInBits - Return the size in bits of the specified type,
2409/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002410uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002411 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2412
2413 // If we have a TargetData, use it!
2414 if (TD)
2415 return TD->getTypeSizeInBits(Ty);
2416
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002417 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002418 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002419 return Ty->getPrimitiveSizeInBits();
2420
2421 // The only other support type is pointer. Without TargetData, conservatively
2422 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002423 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002424 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002425}
2426
2427/// getEffectiveSCEVType - Return a type with the same bitwidth as
2428/// the given type and which represents how SCEV will treat the given
2429/// type, for which isSCEVable must return true. For pointer types,
2430/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002431const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002432 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2433
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002434 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002435 return Ty;
2436
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002437 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002438 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002439 if (TD) return TD->getIntPtrType(getContext());
2440
2441 // Without TargetData, conservatively assume pointers are 64-bit.
2442 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002443}
Chris Lattner53e677a2004-04-02 20:23:17 +00002444
Dan Gohman0bba49c2009-07-07 17:06:11 +00002445const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002446 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002447}
2448
Chris Lattner53e677a2004-04-02 20:23:17 +00002449/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2450/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002451const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002452 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002453
Dan Gohman0bba49c2009-07-07 17:06:11 +00002454 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002455 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002456 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002457 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002458 return S;
2459}
2460
Dan Gohman2d1be872009-04-16 03:18:22 +00002461/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2462///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002463const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002464 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002465 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002466 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002467
2468 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002469 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002470 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002471 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002472}
2473
2474/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002475const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002476 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002477 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002478 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002479
2480 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002481 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002482 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002483 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002484 return getMinusSCEV(AllOnes, V);
2485}
2486
2487/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2488///
Dan Gohman9311ef62009-06-24 14:49:00 +00002489const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2490 const SCEV *RHS) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002491 // Fast path: X - X --> 0.
2492 if (LHS == RHS)
2493 return getConstant(LHS->getType(), 0);
2494
Dan Gohman2d1be872009-04-16 03:18:22 +00002495 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002496 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002497}
2498
2499/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2500/// input value to the specified type. If the type must be extended, it is zero
2501/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002502const SCEV *
2503ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002504 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002505 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002506 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2507 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002508 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002509 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002510 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002511 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002512 return getTruncateExpr(V, Ty);
2513 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002514}
2515
2516/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2517/// input value to the specified type. If the type must be extended, it is sign
2518/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002519const SCEV *
2520ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002521 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002522 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002523 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2524 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002525 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002526 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002527 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002528 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002529 return getTruncateExpr(V, Ty);
2530 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002531}
2532
Dan Gohman467c4302009-05-13 03:46:30 +00002533/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2534/// input value to the specified type. If the type must be extended, it is zero
2535/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002536const SCEV *
2537ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002538 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002539 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2540 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002541 "Cannot noop or zero extend with non-integer arguments!");
2542 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2543 "getNoopOrZeroExtend cannot truncate!");
2544 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2545 return V; // No conversion
2546 return getZeroExtendExpr(V, Ty);
2547}
2548
2549/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2550/// input value to the specified type. If the type must be extended, it is sign
2551/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002552const SCEV *
2553ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002554 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002555 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2556 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002557 "Cannot noop or sign extend with non-integer arguments!");
2558 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2559 "getNoopOrSignExtend cannot truncate!");
2560 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2561 return V; // No conversion
2562 return getSignExtendExpr(V, Ty);
2563}
2564
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002565/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2566/// the input value to the specified type. If the type must be extended,
2567/// it is extended with unspecified bits. The conversion must not be
2568/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002569const SCEV *
2570ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002571 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002572 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2573 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002574 "Cannot noop or any extend with non-integer arguments!");
2575 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2576 "getNoopOrAnyExtend cannot truncate!");
2577 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2578 return V; // No conversion
2579 return getAnyExtendExpr(V, Ty);
2580}
2581
Dan Gohman467c4302009-05-13 03:46:30 +00002582/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2583/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002584const SCEV *
2585ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002586 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002587 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2588 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002589 "Cannot truncate or noop with non-integer arguments!");
2590 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2591 "getTruncateOrNoop cannot extend!");
2592 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2593 return V; // No conversion
2594 return getTruncateExpr(V, Ty);
2595}
2596
Dan Gohmana334aa72009-06-22 00:31:57 +00002597/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2598/// the types using zero-extension, and then perform a umax operation
2599/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002600const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2601 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002602 const SCEV *PromotedLHS = LHS;
2603 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002604
2605 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2606 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2607 else
2608 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2609
2610 return getUMaxExpr(PromotedLHS, PromotedRHS);
2611}
2612
Dan Gohmanc9759e82009-06-22 15:03:27 +00002613/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2614/// the types using zero-extension, and then perform a umin operation
2615/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002616const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2617 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002618 const SCEV *PromotedLHS = LHS;
2619 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002620
2621 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2622 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2623 else
2624 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2625
2626 return getUMinExpr(PromotedLHS, PromotedRHS);
2627}
2628
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002629/// PushDefUseChildren - Push users of the given Instruction
2630/// onto the given Worklist.
2631static void
2632PushDefUseChildren(Instruction *I,
2633 SmallVectorImpl<Instruction *> &Worklist) {
2634 // Push the def-use children onto the Worklist stack.
2635 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2636 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002637 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002638}
2639
2640/// ForgetSymbolicValue - This looks up computed SCEV values for all
2641/// instructions that depend on the given instruction and removes them from
2642/// the Scalars map if they reference SymName. This is used during PHI
2643/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002644void
Dan Gohman85669632010-02-25 06:57:05 +00002645ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002646 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002647 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002648
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002649 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002650 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002651 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002652 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002653 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002654
Dan Gohman5d984912009-12-18 01:14:11 +00002655 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002656 Scalars.find(static_cast<Value *>(I));
2657 if (It != Scalars.end()) {
2658 // Short-circuit the def-use traversal if the symbolic name
2659 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002660 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002661 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002662
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002663 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002664 // structure, it's a PHI that's in the progress of being computed
2665 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2666 // additional loop trip count information isn't going to change anything.
2667 // In the second case, createNodeForPHI will perform the necessary
2668 // updates on its own when it gets to that point. In the third, we do
2669 // want to forget the SCEVUnknown.
2670 if (!isa<PHINode>(I) ||
2671 !isa<SCEVUnknown>(It->second) ||
2672 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002673 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002674 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002675 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002676 }
2677
2678 PushDefUseChildren(I, Worklist);
2679 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002680}
Chris Lattner53e677a2004-04-02 20:23:17 +00002681
2682/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2683/// a loop header, making it a potential recurrence, or it doesn't.
2684///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002685const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002686 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2687 if (L->getHeader() == PN->getParent()) {
2688 // The loop may have multiple entrances or multiple exits; we can analyze
2689 // this phi as an addrec if it has a unique entry value and a unique
2690 // backedge value.
2691 Value *BEValueV = 0, *StartValueV = 0;
2692 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2693 Value *V = PN->getIncomingValue(i);
2694 if (L->contains(PN->getIncomingBlock(i))) {
2695 if (!BEValueV) {
2696 BEValueV = V;
2697 } else if (BEValueV != V) {
2698 BEValueV = 0;
2699 break;
2700 }
2701 } else if (!StartValueV) {
2702 StartValueV = V;
2703 } else if (StartValueV != V) {
2704 StartValueV = 0;
2705 break;
2706 }
2707 }
2708 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002709 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002710 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002711 assert(Scalars.find(PN) == Scalars.end() &&
2712 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002713 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002714
2715 // Using this symbolic name for the PHI, analyze the value coming around
2716 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002717 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002718
2719 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2720 // has a special value for the first iteration of the loop.
2721
2722 // If the value coming around the backedge is an add with the symbolic
2723 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002724 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002725 // If there is a single occurrence of the symbolic value, replace it
2726 // with a recurrence.
2727 unsigned FoundIndex = Add->getNumOperands();
2728 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2729 if (Add->getOperand(i) == SymbolicName)
2730 if (FoundIndex == e) {
2731 FoundIndex = i;
2732 break;
2733 }
2734
2735 if (FoundIndex != Add->getNumOperands()) {
2736 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002737 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002738 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2739 if (i != FoundIndex)
2740 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002741 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002742
2743 // This is not a valid addrec if the step amount is varying each
2744 // loop iteration, but is not itself an addrec in this loop.
2745 if (Accum->isLoopInvariant(L) ||
2746 (isa<SCEVAddRecExpr>(Accum) &&
2747 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002748 bool HasNUW = false;
2749 bool HasNSW = false;
2750
2751 // If the increment doesn't overflow, then neither the addrec nor
2752 // the post-increment will overflow.
2753 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2754 if (OBO->hasNoUnsignedWrap())
2755 HasNUW = true;
2756 if (OBO->hasNoSignedWrap())
2757 HasNSW = true;
2758 }
2759
Dan Gohman27dead42010-04-12 07:49:36 +00002760 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002761 const SCEV *PHISCEV =
2762 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002763
Dan Gohmana10756e2010-01-21 02:09:26 +00002764 // Since the no-wrap flags are on the increment, they apply to the
2765 // post-incremented value as well.
2766 if (Accum->isLoopInvariant(L))
2767 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2768 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002769
2770 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002771 // to be symbolic. We now need to go back and purge all of the
2772 // entries for the scalars that use the symbolic expression.
2773 ForgetSymbolicName(PN, SymbolicName);
2774 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002775 return PHISCEV;
2776 }
2777 }
Dan Gohman622ed672009-05-04 22:02:23 +00002778 } else if (const SCEVAddRecExpr *AddRec =
2779 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002780 // Otherwise, this could be a loop like this:
2781 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2782 // In this case, j = {1,+,1} and BEValue is j.
2783 // Because the other in-value of i (0) fits the evolution of BEValue
2784 // i really is an addrec evolution.
2785 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002786 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002787
2788 // If StartVal = j.start - j.stride, we can use StartVal as the
2789 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002790 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002791 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002792 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002793 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002794
2795 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002796 // to be symbolic. We now need to go back and purge all of the
2797 // entries for the scalars that use the symbolic expression.
2798 ForgetSymbolicName(PN, SymbolicName);
2799 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002800 return PHISCEV;
2801 }
2802 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002803 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002804 }
Dan Gohman27dead42010-04-12 07:49:36 +00002805 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002806
Dan Gohman85669632010-02-25 06:57:05 +00002807 // If the PHI has a single incoming value, follow that value, unless the
2808 // PHI's incoming blocks are in a different loop, in which case doing so
2809 // risks breaking LCSSA form. Instcombine would normally zap these, but
2810 // it doesn't have DominatorTree information, so it may miss cases.
2811 if (Value *V = PN->hasConstantValue(DT)) {
2812 bool AllSameLoop = true;
2813 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2814 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2815 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2816 AllSameLoop = false;
2817 break;
2818 }
2819 if (AllSameLoop)
2820 return getSCEV(V);
2821 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002822
Chris Lattner53e677a2004-04-02 20:23:17 +00002823 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002824 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002825}
2826
Dan Gohman26466c02009-05-08 20:26:55 +00002827/// createNodeForGEP - Expand GEP instructions into add and multiply
2828/// operations. This allows them to be analyzed by regular SCEV code.
2829///
Dan Gohmand281ed22009-12-18 02:09:29 +00002830const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002831
Dan Gohmanb9f96512010-06-30 07:16:37 +00002832 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2833 // Add expression, because the Instruction may be guarded by control flow
2834 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002835 // context.
Dan Gohman7a642572010-06-29 01:41:41 +00002836
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002837 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002838 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002839 // Don't attempt to analyze GEPs over unsized objects.
2840 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2841 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002842 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002843 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002844 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002845 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002846 I != E; ++I) {
2847 Value *Index = *I;
2848 // Compute the (potentially symbolic) offset in bytes for this index.
2849 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2850 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002851 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002852 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2853
Dan Gohmanb9f96512010-06-30 07:16:37 +00002854 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002855 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002856 } else {
2857 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002858 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2859 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002860 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002861 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2862
Dan Gohmanb9f96512010-06-30 07:16:37 +00002863 // Multiply the index by the element size to compute the element offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002864 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002865
2866 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002867 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002868 }
2869 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002870
2871 // Get the SCEV for the GEP base.
2872 const SCEV *BaseS = getSCEV(Base);
2873
Dan Gohmanb9f96512010-06-30 07:16:37 +00002874 // Add the total offset from all the GEP indices to the base.
Dan Gohman70eff632010-06-30 17:27:11 +00002875 return getAddExpr(BaseS, TotalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002876}
2877
Nick Lewycky83bb0052007-11-22 07:59:40 +00002878/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2879/// guaranteed to end in (at every loop iteration). It is, at the same time,
2880/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2881/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002882uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002883ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002884 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002885 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002886
Dan Gohman622ed672009-05-04 22:02:23 +00002887 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002888 return std::min(GetMinTrailingZeros(T->getOperand()),
2889 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002890
Dan Gohman622ed672009-05-04 22:02:23 +00002891 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002892 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2893 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2894 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002895 }
2896
Dan Gohman622ed672009-05-04 22:02:23 +00002897 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002898 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2899 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2900 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002901 }
2902
Dan Gohman622ed672009-05-04 22:02:23 +00002903 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002904 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002905 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002906 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002907 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002908 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002909 }
2910
Dan Gohman622ed672009-05-04 22:02:23 +00002911 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002912 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002913 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2914 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002915 for (unsigned i = 1, e = M->getNumOperands();
2916 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002917 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002918 BitWidth);
2919 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002920 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002921
Dan Gohman622ed672009-05-04 22:02:23 +00002922 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002923 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002924 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002925 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002926 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002927 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002928 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002929
Dan Gohman622ed672009-05-04 22:02:23 +00002930 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002931 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002932 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002933 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002934 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002935 return MinOpRes;
2936 }
2937
Dan Gohman622ed672009-05-04 22:02:23 +00002938 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002939 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002940 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002941 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002942 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002943 return MinOpRes;
2944 }
2945
Dan Gohman2c364ad2009-06-19 23:29:04 +00002946 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2947 // For a SCEVUnknown, ask ValueTracking.
2948 unsigned BitWidth = getTypeSizeInBits(U->getType());
2949 APInt Mask = APInt::getAllOnesValue(BitWidth);
2950 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2951 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2952 return Zeros.countTrailingOnes();
2953 }
2954
2955 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002956 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002957}
Chris Lattner53e677a2004-04-02 20:23:17 +00002958
Dan Gohman85b05a22009-07-13 21:35:55 +00002959/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2960///
2961ConstantRange
2962ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002963
2964 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002965 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002966
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002967 unsigned BitWidth = getTypeSizeInBits(S->getType());
2968 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2969
2970 // If the value has known zeros, the maximum unsigned value will have those
2971 // known zeros as well.
2972 uint32_t TZ = GetMinTrailingZeros(S);
2973 if (TZ != 0)
2974 ConservativeResult =
2975 ConstantRange(APInt::getMinValue(BitWidth),
2976 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2977
Dan Gohman85b05a22009-07-13 21:35:55 +00002978 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2979 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2980 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2981 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002982 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002983 }
2984
2985 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2986 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2987 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2988 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002989 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002990 }
2991
2992 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2993 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2994 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2995 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002996 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002997 }
2998
2999 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3000 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3001 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3002 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003003 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003004 }
3005
3006 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3007 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3008 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003009 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003010 }
3011
3012 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3013 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003014 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003015 }
3016
3017 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3018 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003019 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003020 }
3021
3022 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3023 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003024 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003025 }
3026
Dan Gohman85b05a22009-07-13 21:35:55 +00003027 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003028 // If there's no unsigned wrap, the value will never be less than its
3029 // initial value.
3030 if (AddRec->hasNoUnsignedWrap())
3031 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00003032 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00003033 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00003034 ConservativeResult.intersectWith(
3035 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003036
3037 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003038 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003039 const Type *Ty = AddRec->getType();
3040 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003041 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3042 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003043 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3044
3045 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003046 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003047
3048 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003049 ConstantRange StepRange = getSignedRange(Step);
3050 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3051 ConstantRange EndRange =
3052 StartRange.add(MaxBECountRange.multiply(StepRange));
3053
3054 // Check for overflow. This must be done with ConstantRange arithmetic
3055 // because we could be called from within the ScalarEvolution overflow
3056 // checking code.
3057 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3058 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3059 ConstantRange ExtMaxBECountRange =
3060 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3061 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3062 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3063 ExtEndRange)
3064 return ConservativeResult;
3065
Dan Gohman85b05a22009-07-13 21:35:55 +00003066 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3067 EndRange.getUnsignedMin());
3068 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3069 EndRange.getUnsignedMax());
3070 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003071 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003072 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00003073 }
3074 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003075
3076 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003077 }
3078
3079 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3080 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003081 APInt Mask = APInt::getAllOnesValue(BitWidth);
3082 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3083 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003084 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003085 return ConservativeResult;
3086 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003087 }
3088
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003089 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003090}
3091
Dan Gohman85b05a22009-07-13 21:35:55 +00003092/// getSignedRange - Determine the signed range for a particular SCEV.
3093///
3094ConstantRange
3095ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00003096
Dan Gohman85b05a22009-07-13 21:35:55 +00003097 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
3098 return ConstantRange(C->getValue()->getValue());
3099
Dan Gohman52fddd32010-01-26 04:40:18 +00003100 unsigned BitWidth = getTypeSizeInBits(S->getType());
3101 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3102
3103 // If the value has known zeros, the maximum signed value will have those
3104 // known zeros as well.
3105 uint32_t TZ = GetMinTrailingZeros(S);
3106 if (TZ != 0)
3107 ConservativeResult =
3108 ConstantRange(APInt::getSignedMinValue(BitWidth),
3109 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3110
Dan Gohman85b05a22009-07-13 21:35:55 +00003111 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3112 ConstantRange X = getSignedRange(Add->getOperand(0));
3113 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3114 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003115 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003116 }
3117
Dan Gohman85b05a22009-07-13 21:35:55 +00003118 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3119 ConstantRange X = getSignedRange(Mul->getOperand(0));
3120 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3121 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003122 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003123 }
3124
Dan Gohman85b05a22009-07-13 21:35:55 +00003125 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3126 ConstantRange X = getSignedRange(SMax->getOperand(0));
3127 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3128 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003129 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003130 }
Dan Gohman62849c02009-06-24 01:05:09 +00003131
Dan Gohman85b05a22009-07-13 21:35:55 +00003132 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3133 ConstantRange X = getSignedRange(UMax->getOperand(0));
3134 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3135 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00003136 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00003137 }
Dan Gohman62849c02009-06-24 01:05:09 +00003138
Dan Gohman85b05a22009-07-13 21:35:55 +00003139 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3140 ConstantRange X = getSignedRange(UDiv->getLHS());
3141 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00003142 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00003143 }
Dan Gohman62849c02009-06-24 01:05:09 +00003144
Dan Gohman85b05a22009-07-13 21:35:55 +00003145 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3146 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003147 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003148 }
3149
3150 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3151 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003152 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003153 }
3154
3155 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3156 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003157 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003158 }
3159
Dan Gohman85b05a22009-07-13 21:35:55 +00003160 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003161 // If there's no signed wrap, and all the operands have the same sign or
3162 // zero, the value won't ever change sign.
3163 if (AddRec->hasNoSignedWrap()) {
3164 bool AllNonNeg = true;
3165 bool AllNonPos = true;
3166 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3167 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3168 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3169 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003170 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003171 ConservativeResult = ConservativeResult.intersectWith(
3172 ConstantRange(APInt(BitWidth, 0),
3173 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003174 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003175 ConservativeResult = ConservativeResult.intersectWith(
3176 ConstantRange(APInt::getSignedMinValue(BitWidth),
3177 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003178 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003179
3180 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003181 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003182 const Type *Ty = AddRec->getType();
3183 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003184 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3185 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003186 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3187
3188 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003189 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003190
3191 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003192 ConstantRange StepRange = getSignedRange(Step);
3193 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3194 ConstantRange EndRange =
3195 StartRange.add(MaxBECountRange.multiply(StepRange));
3196
3197 // Check for overflow. This must be done with ConstantRange arithmetic
3198 // because we could be called from within the ScalarEvolution overflow
3199 // checking code.
3200 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3201 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3202 ConstantRange ExtMaxBECountRange =
3203 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3204 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3205 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3206 ExtEndRange)
3207 return ConservativeResult;
3208
Dan Gohman85b05a22009-07-13 21:35:55 +00003209 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3210 EndRange.getSignedMin());
3211 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3212 EndRange.getSignedMax());
3213 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003214 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003215 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003216 }
Dan Gohman62849c02009-06-24 01:05:09 +00003217 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003218
3219 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003220 }
3221
Dan Gohman2c364ad2009-06-19 23:29:04 +00003222 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3223 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003224 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003225 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003226 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3227 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003228 return ConservativeResult;
3229 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003230 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003231 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003232 }
3233
Dan Gohman52fddd32010-01-26 04:40:18 +00003234 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003235}
3236
Chris Lattner53e677a2004-04-02 20:23:17 +00003237/// createSCEV - We know that there is no SCEV for the specified value.
3238/// Analyze the expression.
3239///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003240const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003241 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003242 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003243
Dan Gohman6c459a22008-06-22 19:56:46 +00003244 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003245 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003246 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003247
3248 // Don't attempt to analyze instructions in blocks that aren't
3249 // reachable. Such instructions don't matter, and they aren't required
3250 // to obey basic rules for definitions dominating uses which this
3251 // analysis depends on.
3252 if (!DT->isReachableFromEntry(I->getParent()))
3253 return getUnknown(V);
3254 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003255 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003256 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3257 return getConstant(CI);
3258 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003259 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003260 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3261 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003262 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003263 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003264
Dan Gohmanca178902009-07-17 20:47:02 +00003265 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003266 switch (Opcode) {
Dan Gohman70eff632010-06-30 17:27:11 +00003267 case Instruction::Add:
3268 return getAddExpr(getSCEV(U->getOperand(0)),
3269 getSCEV(U->getOperand(1)));
3270 case Instruction::Mul:
3271 return getMulExpr(getSCEV(U->getOperand(0)),
3272 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003273 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003274 return getUDivExpr(getSCEV(U->getOperand(0)),
3275 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003276 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003277 return getMinusSCEV(getSCEV(U->getOperand(0)),
3278 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003279 case Instruction::And:
3280 // For an expression like x&255 that merely masks off the high bits,
3281 // use zext(trunc(x)) as the SCEV expression.
3282 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003283 if (CI->isNullValue())
3284 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003285 if (CI->isAllOnesValue())
3286 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003287 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003288
3289 // Instcombine's ShrinkDemandedConstant may strip bits out of
3290 // constants, obscuring what would otherwise be a low-bits mask.
3291 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3292 // knew about to reconstruct a low-bits mask value.
3293 unsigned LZ = A.countLeadingZeros();
3294 unsigned BitWidth = A.getBitWidth();
3295 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3296 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3297 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3298
3299 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3300
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003301 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003302 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003303 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003304 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003305 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003306 }
3307 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003308
Dan Gohman6c459a22008-06-22 19:56:46 +00003309 case Instruction::Or:
3310 // If the RHS of the Or is a constant, we may have something like:
3311 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3312 // optimizations will transparently handle this case.
3313 //
3314 // In order for this transformation to be safe, the LHS must be of the
3315 // form X*(2^n) and the Or constant must be less than 2^n.
3316 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003317 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003318 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003319 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003320 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3321 // Build a plain add SCEV.
3322 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3323 // If the LHS of the add was an addrec and it has no-wrap flags,
3324 // transfer the no-wrap flags, since an or won't introduce a wrap.
3325 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3326 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3327 if (OldAR->hasNoUnsignedWrap())
3328 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3329 if (OldAR->hasNoSignedWrap())
3330 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3331 }
3332 return S;
3333 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003334 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003335 break;
3336 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003337 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003338 // If the RHS of the xor is a signbit, then this is just an add.
3339 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003340 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003341 return getAddExpr(getSCEV(U->getOperand(0)),
3342 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003343
3344 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003345 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003346 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003347
3348 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3349 // This is a variant of the check for xor with -1, and it handles
3350 // the case where instcombine has trimmed non-demanded bits out
3351 // of an xor with -1.
3352 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3353 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3354 if (BO->getOpcode() == Instruction::And &&
3355 LCI->getValue() == CI->getValue())
3356 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003357 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003358 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003359 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003360 const Type *Z0Ty = Z0->getType();
3361 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3362
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003363 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003364 // mask off the high bits. Complement the operand and
3365 // re-apply the zext.
3366 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3367 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3368
3369 // If C is a single bit, it may be in the sign-bit position
3370 // before the zero-extend. In this case, represent the xor
3371 // using an add, which is equivalent, and re-apply the zext.
3372 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3373 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3374 Trunc.isSignBit())
3375 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3376 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003377 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003378 }
3379 break;
3380
3381 case Instruction::Shl:
3382 // Turn shift left of a constant amount into a multiply.
3383 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003384 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003385
3386 // If the shift count is not less than the bitwidth, the result of
3387 // the shift is undefined. Don't try to analyze it, because the
3388 // resolution chosen here may differ from the resolution chosen in
3389 // other parts of the compiler.
3390 if (SA->getValue().uge(BitWidth))
3391 break;
3392
Owen Andersoneed707b2009-07-24 23:12:02 +00003393 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003394 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003395 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003396 }
3397 break;
3398
Nick Lewycky01eaf802008-07-07 06:15:49 +00003399 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003400 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003401 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003402 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003403
3404 // If the shift count is not less than the bitwidth, the result of
3405 // the shift is undefined. Don't try to analyze it, because the
3406 // resolution chosen here may differ from the resolution chosen in
3407 // other parts of the compiler.
3408 if (SA->getValue().uge(BitWidth))
3409 break;
3410
Owen Andersoneed707b2009-07-24 23:12:02 +00003411 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003412 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003413 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003414 }
3415 break;
3416
Dan Gohman4ee29af2009-04-21 02:26:00 +00003417 case Instruction::AShr:
3418 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3419 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003420 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003421 if (L->getOpcode() == Instruction::Shl &&
3422 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003423 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3424
3425 // If the shift count is not less than the bitwidth, the result of
3426 // the shift is undefined. Don't try to analyze it, because the
3427 // resolution chosen here may differ from the resolution chosen in
3428 // other parts of the compiler.
3429 if (CI->getValue().uge(BitWidth))
3430 break;
3431
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003432 uint64_t Amt = BitWidth - CI->getZExtValue();
3433 if (Amt == BitWidth)
3434 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003435 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003436 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003437 IntegerType::get(getContext(),
3438 Amt)),
3439 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003440 }
3441 break;
3442
Dan Gohman6c459a22008-06-22 19:56:46 +00003443 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003444 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003445
3446 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003447 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003448
3449 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003450 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003451
3452 case Instruction::BitCast:
3453 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003454 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003455 return getSCEV(U->getOperand(0));
3456 break;
3457
Dan Gohman4f8eea82010-02-01 18:27:38 +00003458 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3459 // lead to pointer expressions which cannot safely be expanded to GEPs,
3460 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3461 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003462
Dan Gohman26466c02009-05-08 20:26:55 +00003463 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003464 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003465
Dan Gohman6c459a22008-06-22 19:56:46 +00003466 case Instruction::PHI:
3467 return createNodeForPHI(cast<PHINode>(U));
3468
3469 case Instruction::Select:
3470 // This could be a smax or umax that was lowered earlier.
3471 // Try to recover it.
3472 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3473 Value *LHS = ICI->getOperand(0);
3474 Value *RHS = ICI->getOperand(1);
3475 switch (ICI->getPredicate()) {
3476 case ICmpInst::ICMP_SLT:
3477 case ICmpInst::ICMP_SLE:
3478 std::swap(LHS, RHS);
3479 // fall through
3480 case ICmpInst::ICMP_SGT:
3481 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003482 // a >s b ? a+x : b+x -> smax(a, b)+x
3483 // a >s b ? b+x : a+x -> smin(a, b)+x
3484 if (LHS->getType() == U->getType()) {
3485 const SCEV *LS = getSCEV(LHS);
3486 const SCEV *RS = getSCEV(RHS);
3487 const SCEV *LA = getSCEV(U->getOperand(1));
3488 const SCEV *RA = getSCEV(U->getOperand(2));
3489 const SCEV *LDiff = getMinusSCEV(LA, LS);
3490 const SCEV *RDiff = getMinusSCEV(RA, RS);
3491 if (LDiff == RDiff)
3492 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3493 LDiff = getMinusSCEV(LA, RS);
3494 RDiff = getMinusSCEV(RA, LS);
3495 if (LDiff == RDiff)
3496 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3497 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003498 break;
3499 case ICmpInst::ICMP_ULT:
3500 case ICmpInst::ICMP_ULE:
3501 std::swap(LHS, RHS);
3502 // fall through
3503 case ICmpInst::ICMP_UGT:
3504 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003505 // a >u b ? a+x : b+x -> umax(a, b)+x
3506 // a >u b ? b+x : a+x -> umin(a, b)+x
3507 if (LHS->getType() == U->getType()) {
3508 const SCEV *LS = getSCEV(LHS);
3509 const SCEV *RS = getSCEV(RHS);
3510 const SCEV *LA = getSCEV(U->getOperand(1));
3511 const SCEV *RA = getSCEV(U->getOperand(2));
3512 const SCEV *LDiff = getMinusSCEV(LA, LS);
3513 const SCEV *RDiff = getMinusSCEV(RA, RS);
3514 if (LDiff == RDiff)
3515 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3516 LDiff = getMinusSCEV(LA, RS);
3517 RDiff = getMinusSCEV(RA, LS);
3518 if (LDiff == RDiff)
3519 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3520 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003521 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003522 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003523 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3524 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003525 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003526 cast<ConstantInt>(RHS)->isZero()) {
3527 const SCEV *One = getConstant(LHS->getType(), 1);
3528 const SCEV *LS = getSCEV(LHS);
3529 const SCEV *LA = getSCEV(U->getOperand(1));
3530 const SCEV *RA = getSCEV(U->getOperand(2));
3531 const SCEV *LDiff = getMinusSCEV(LA, LS);
3532 const SCEV *RDiff = getMinusSCEV(RA, One);
3533 if (LDiff == RDiff)
3534 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3535 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003536 break;
3537 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003538 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3539 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003540 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003541 cast<ConstantInt>(RHS)->isZero()) {
3542 const SCEV *One = getConstant(LHS->getType(), 1);
3543 const SCEV *LS = getSCEV(LHS);
3544 const SCEV *LA = getSCEV(U->getOperand(1));
3545 const SCEV *RA = getSCEV(U->getOperand(2));
3546 const SCEV *LDiff = getMinusSCEV(LA, One);
3547 const SCEV *RDiff = getMinusSCEV(RA, LS);
3548 if (LDiff == RDiff)
3549 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3550 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003551 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003552 default:
3553 break;
3554 }
3555 }
3556
3557 default: // We cannot analyze this expression.
3558 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003559 }
3560
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003561 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003562}
3563
3564
3565
3566//===----------------------------------------------------------------------===//
3567// Iteration Count Computation Code
3568//
3569
Dan Gohman46bdfb02009-02-24 18:55:53 +00003570/// getBackedgeTakenCount - If the specified loop has a predictable
3571/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3572/// object. The backedge-taken count is the number of times the loop header
3573/// will be branched to from within the loop. This is one less than the
3574/// trip count of the loop, since it doesn't count the first iteration,
3575/// when the header is branched to from outside the loop.
3576///
3577/// Note that it is not valid to call this method on a loop without a
3578/// loop-invariant backedge-taken count (see
3579/// hasLoopInvariantBackedgeTakenCount).
3580///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003581const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003582 return getBackedgeTakenInfo(L).Exact;
3583}
3584
3585/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3586/// return the least SCEV value that is known never to be less than the
3587/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003588const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003589 return getBackedgeTakenInfo(L).Max;
3590}
3591
Dan Gohman59ae6b92009-07-08 19:23:34 +00003592/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3593/// onto the given Worklist.
3594static void
3595PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3596 BasicBlock *Header = L->getHeader();
3597
3598 // Push all Loop-header PHIs onto the Worklist stack.
3599 for (BasicBlock::iterator I = Header->begin();
3600 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3601 Worklist.push_back(PN);
3602}
3603
Dan Gohmana1af7572009-04-30 20:47:05 +00003604const ScalarEvolution::BackedgeTakenInfo &
3605ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003606 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003607 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003608 // update the value. The temporary CouldNotCompute value tells SCEV
3609 // code elsewhere that it shouldn't attempt to request a new
3610 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003611 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003612 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3613 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003614 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3615 if (BECount.Exact != getCouldNotCompute()) {
3616 assert(BECount.Exact->isLoopInvariant(L) &&
3617 BECount.Max->isLoopInvariant(L) &&
3618 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003619 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003620
Dan Gohman01ecca22009-04-27 20:16:15 +00003621 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003622 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003623 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003624 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003625 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003626 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003627 if (isa<PHINode>(L->getHeader()->begin()))
3628 // Only count loops that have phi nodes as not being computable.
3629 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003630 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003631
3632 // Now that we know more about the trip count for this loop, forget any
3633 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003634 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003635 // information. This is similar to the code in forgetLoop, except that
3636 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003637 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003638 SmallVector<Instruction *, 16> Worklist;
3639 PushLoopPHIs(L, Worklist);
3640
3641 SmallPtrSet<Instruction *, 8> Visited;
3642 while (!Worklist.empty()) {
3643 Instruction *I = Worklist.pop_back_val();
3644 if (!Visited.insert(I)) continue;
3645
Dan Gohman5d984912009-12-18 01:14:11 +00003646 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003647 Scalars.find(static_cast<Value *>(I));
3648 if (It != Scalars.end()) {
3649 // SCEVUnknown for a PHI either means that it has an unrecognized
3650 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003651 // by createNodeForPHI. In the former case, additional loop trip
3652 // count information isn't going to change anything. In the later
3653 // case, createNodeForPHI will perform the necessary updates on its
3654 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003655 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3656 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003657 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003658 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003659 if (PHINode *PN = dyn_cast<PHINode>(I))
3660 ConstantEvolutionLoopExitValue.erase(PN);
3661 }
3662
3663 PushDefUseChildren(I, Worklist);
3664 }
3665 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003666 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003667 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003668}
3669
Dan Gohman4c7279a2009-10-31 15:04:55 +00003670/// forgetLoop - This method should be called by the client when it has
3671/// changed a loop in a way that may effect ScalarEvolution's ability to
3672/// compute a trip count, or if the loop is deleted.
3673void ScalarEvolution::forgetLoop(const Loop *L) {
3674 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003675 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003676
Dan Gohman4c7279a2009-10-31 15:04:55 +00003677 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003678 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003679 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003680
Dan Gohman59ae6b92009-07-08 19:23:34 +00003681 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003682 while (!Worklist.empty()) {
3683 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003684 if (!Visited.insert(I)) continue;
3685
Dan Gohman5d984912009-12-18 01:14:11 +00003686 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003687 Scalars.find(static_cast<Value *>(I));
3688 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003689 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003690 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003691 if (PHINode *PN = dyn_cast<PHINode>(I))
3692 ConstantEvolutionLoopExitValue.erase(PN);
3693 }
3694
3695 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003696 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003697}
3698
Eric Christophere6cbfa62010-07-29 01:25:38 +00003699/// forgetValue - This method should be called by the client when it has
3700/// changed a value in a way that may effect its value, or which may
3701/// disconnect it from a def-use chain linking it to a loop.
3702void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003703 Instruction *I = dyn_cast<Instruction>(V);
3704 if (!I) return;
3705
3706 // Drop information about expressions based on loop-header PHIs.
3707 SmallVector<Instruction *, 16> Worklist;
3708 Worklist.push_back(I);
3709
3710 SmallPtrSet<Instruction *, 8> Visited;
3711 while (!Worklist.empty()) {
3712 I = Worklist.pop_back_val();
3713 if (!Visited.insert(I)) continue;
3714
3715 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3716 Scalars.find(static_cast<Value *>(I));
3717 if (It != Scalars.end()) {
3718 ValuesAtScopes.erase(It->second);
3719 Scalars.erase(It);
3720 if (PHINode *PN = dyn_cast<PHINode>(I))
3721 ConstantEvolutionLoopExitValue.erase(PN);
3722 }
3723
3724 PushDefUseChildren(I, Worklist);
3725 }
3726}
3727
Dan Gohman46bdfb02009-02-24 18:55:53 +00003728/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3729/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003730ScalarEvolution::BackedgeTakenInfo
3731ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003732 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003733 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003734
Dan Gohmana334aa72009-06-22 00:31:57 +00003735 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003736 const SCEV *BECount = getCouldNotCompute();
3737 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003738 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003739 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3740 BackedgeTakenInfo NewBTI =
3741 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003742
Dan Gohman1c343752009-06-27 21:21:31 +00003743 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003744 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003745 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003746 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003747 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003748 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003749 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003750 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003751 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003752 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003753 }
Dan Gohman1c343752009-06-27 21:21:31 +00003754 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003755 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003756 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003757 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003758 }
3759
3760 return BackedgeTakenInfo(BECount, MaxBECount);
3761}
3762
3763/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3764/// of the specified loop will execute if it exits via the specified block.
3765ScalarEvolution::BackedgeTakenInfo
3766ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3767 BasicBlock *ExitingBlock) {
3768
3769 // Okay, we've chosen an exiting block. See what condition causes us to
3770 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003771 //
3772 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003773 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003774 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003775 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003776
Chris Lattner8b0e3602007-01-07 02:24:26 +00003777 // At this point, we know we have a conditional branch that determines whether
3778 // the loop is exited. However, we don't know if the branch is executed each
3779 // time through the loop. If not, then the execution count of the branch will
3780 // not be equal to the trip count of the loop.
3781 //
3782 // Currently we check for this by checking to see if the Exit branch goes to
3783 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003784 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003785 // loop header. This is common for un-rotated loops.
3786 //
3787 // If both of those tests fail, walk up the unique predecessor chain to the
3788 // header, stopping if there is an edge that doesn't exit the loop. If the
3789 // header is reached, the execution count of the branch will be equal to the
3790 // trip count of the loop.
3791 //
3792 // More extensive analysis could be done to handle more cases here.
3793 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003794 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003795 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003796 ExitBr->getParent() != L->getHeader()) {
3797 // The simple checks failed, try climbing the unique predecessor chain
3798 // up to the header.
3799 bool Ok = false;
3800 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3801 BasicBlock *Pred = BB->getUniquePredecessor();
3802 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003803 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003804 TerminatorInst *PredTerm = Pred->getTerminator();
3805 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3806 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3807 if (PredSucc == BB)
3808 continue;
3809 // If the predecessor has a successor that isn't BB and isn't
3810 // outside the loop, assume the worst.
3811 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003812 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003813 }
3814 if (Pred == L->getHeader()) {
3815 Ok = true;
3816 break;
3817 }
3818 BB = Pred;
3819 }
3820 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003821 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003822 }
3823
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003824 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003825 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3826 ExitBr->getSuccessor(0),
3827 ExitBr->getSuccessor(1));
3828}
3829
3830/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3831/// backedge of the specified loop will execute if its exit condition
3832/// were a conditional branch of ExitCond, TBB, and FBB.
3833ScalarEvolution::BackedgeTakenInfo
3834ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3835 Value *ExitCond,
3836 BasicBlock *TBB,
3837 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003838 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003839 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3840 if (BO->getOpcode() == Instruction::And) {
3841 // Recurse on the operands of the and.
3842 BackedgeTakenInfo BTI0 =
3843 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3844 BackedgeTakenInfo BTI1 =
3845 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003846 const SCEV *BECount = getCouldNotCompute();
3847 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003848 if (L->contains(TBB)) {
3849 // Both conditions must be true for the loop to continue executing.
3850 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003851 if (BTI0.Exact == getCouldNotCompute() ||
3852 BTI1.Exact == getCouldNotCompute())
3853 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003854 else
3855 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003856 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003857 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003858 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003859 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003860 else
3861 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003862 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003863 // Both conditions must be true at the same time for the loop to exit.
3864 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003865 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003866 if (BTI0.Max == BTI1.Max)
3867 MaxBECount = BTI0.Max;
3868 if (BTI0.Exact == BTI1.Exact)
3869 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003870 }
3871
3872 return BackedgeTakenInfo(BECount, MaxBECount);
3873 }
3874 if (BO->getOpcode() == Instruction::Or) {
3875 // Recurse on the operands of the or.
3876 BackedgeTakenInfo BTI0 =
3877 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3878 BackedgeTakenInfo BTI1 =
3879 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003880 const SCEV *BECount = getCouldNotCompute();
3881 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003882 if (L->contains(FBB)) {
3883 // Both conditions must be false for the loop to continue executing.
3884 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003885 if (BTI0.Exact == getCouldNotCompute() ||
3886 BTI1.Exact == getCouldNotCompute())
3887 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003888 else
3889 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003890 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003891 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003892 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003893 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003894 else
3895 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003896 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003897 // Both conditions must be false at the same time for the loop to exit.
3898 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003899 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003900 if (BTI0.Max == BTI1.Max)
3901 MaxBECount = BTI0.Max;
3902 if (BTI0.Exact == BTI1.Exact)
3903 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003904 }
3905
3906 return BackedgeTakenInfo(BECount, MaxBECount);
3907 }
3908 }
3909
3910 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003911 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003912 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3913 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003914
Dan Gohman00cb5b72010-02-19 18:12:07 +00003915 // Check for a constant condition. These are normally stripped out by
3916 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3917 // preserve the CFG and is temporarily leaving constant conditions
3918 // in place.
3919 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3920 if (L->contains(FBB) == !CI->getZExtValue())
3921 // The backedge is always taken.
3922 return getCouldNotCompute();
3923 else
3924 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003925 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003926 }
3927
Eli Friedman361e54d2009-05-09 12:32:42 +00003928 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003929 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3930}
3931
3932/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3933/// backedge of the specified loop will execute if its exit condition
3934/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3935ScalarEvolution::BackedgeTakenInfo
3936ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3937 ICmpInst *ExitCond,
3938 BasicBlock *TBB,
3939 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003940
Reid Spencere4d87aa2006-12-23 06:05:41 +00003941 // If the condition was exit on true, convert the condition to exit on false
3942 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003943 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003944 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003945 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003946 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003947
3948 // Handle common loops like: for (X = "string"; *X; ++X)
3949 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3950 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003951 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003952 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003953 if (ItCnt.hasAnyInfo())
3954 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003955 }
3956
Dan Gohman0bba49c2009-07-07 17:06:11 +00003957 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3958 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003959
3960 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003961 LHS = getSCEVAtScope(LHS, L);
3962 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003963
Dan Gohman64a845e2009-06-24 04:48:43 +00003964 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003965 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003966 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3967 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003968 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003969 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003970 }
3971
Dan Gohman03557dc2010-05-03 16:35:17 +00003972 // Simplify the operands before analyzing them.
3973 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3974
Chris Lattner53e677a2004-04-02 20:23:17 +00003975 // If we have a comparison of a chrec against a constant, try to use value
3976 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003977 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3978 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003979 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003980 // Form the constant range.
3981 ConstantRange CompRange(
3982 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003983
Dan Gohman0bba49c2009-07-07 17:06:11 +00003984 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003985 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003986 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003987
Chris Lattner53e677a2004-04-02 20:23:17 +00003988 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003989 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003990 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003991 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3992 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003993 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003994 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003995 case ICmpInst::ICMP_EQ: { // while (X == Y)
3996 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003997 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3998 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003999 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004000 }
4001 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004002 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4003 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004004 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004005 }
4006 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004007 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4008 getNotSCEV(RHS), L, true);
4009 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004010 break;
4011 }
4012 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004013 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4014 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004015 break;
4016 }
4017 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004018 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4019 getNotSCEV(RHS), L, false);
4020 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004021 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004022 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004023 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004024#if 0
David Greene25e0e872009-12-23 22:18:14 +00004025 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004026 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004027 dbgs() << "[unsigned] ";
4028 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004029 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004030 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004031#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004032 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004033 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004034 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004035 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004036}
4037
Chris Lattner673e02b2004-10-12 01:49:27 +00004038static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004039EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4040 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004041 const SCEV *InVal = SE.getConstant(C);
4042 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004043 assert(isa<SCEVConstant>(Val) &&
4044 "Evaluation of SCEV at constant didn't fold correctly?");
4045 return cast<SCEVConstant>(Val)->getValue();
4046}
4047
4048/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4049/// and a GEP expression (missing the pointer index) indexing into it, return
4050/// the addressed element of the initializer or null if the index expression is
4051/// invalid.
4052static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004053GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004054 const std::vector<ConstantInt*> &Indices) {
4055 Constant *Init = GV->getInitializer();
4056 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004057 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004058 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4059 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4060 Init = cast<Constant>(CS->getOperand(Idx));
4061 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4062 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4063 Init = cast<Constant>(CA->getOperand(Idx));
4064 } else if (isa<ConstantAggregateZero>(Init)) {
4065 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4066 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004067 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004068 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4069 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004070 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004071 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004072 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004073 }
4074 return 0;
4075 } else {
4076 return 0; // Unknown initializer type
4077 }
4078 }
4079 return Init;
4080}
4081
Dan Gohman46bdfb02009-02-24 18:55:53 +00004082/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4083/// 'icmp op load X, cst', try to see if we can compute the backedge
4084/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004085ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004086ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4087 LoadInst *LI,
4088 Constant *RHS,
4089 const Loop *L,
4090 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004091 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004092
4093 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004094 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004095 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004096 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004097
4098 // Make sure that it is really a constant global we are gepping, with an
4099 // initializer, and make sure the first IDX is really 0.
4100 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004101 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004102 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4103 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004104 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004105
4106 // Okay, we allow one non-constant index into the GEP instruction.
4107 Value *VarIdx = 0;
4108 std::vector<ConstantInt*> Indexes;
4109 unsigned VarIdxNum = 0;
4110 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4111 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4112 Indexes.push_back(CI);
4113 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004114 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004115 VarIdx = GEP->getOperand(i);
4116 VarIdxNum = i-2;
4117 Indexes.push_back(0);
4118 }
4119
4120 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4121 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004122 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004123 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004124
4125 // We can only recognize very limited forms of loop index expressions, in
4126 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004127 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00004128 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
4129 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4130 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004131 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004132
4133 unsigned MaxSteps = MaxBruteForceIterations;
4134 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004135 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004136 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004137 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004138
4139 // Form the GEP offset.
4140 Indexes[VarIdxNum] = Val;
4141
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004142 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004143 if (Result == 0) break; // Cannot compute!
4144
4145 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004146 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004147 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004148 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004149#if 0
David Greene25e0e872009-12-23 22:18:14 +00004150 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004151 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4152 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004153#endif
4154 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004155 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004156 }
4157 }
Dan Gohman1c343752009-06-27 21:21:31 +00004158 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004159}
4160
4161
Chris Lattner3221ad02004-04-17 22:58:41 +00004162/// CanConstantFold - Return true if we can constant fold an instruction of the
4163/// specified type, assuming that all operands were constants.
4164static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004165 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004166 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4167 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004168
Chris Lattner3221ad02004-04-17 22:58:41 +00004169 if (const CallInst *CI = dyn_cast<CallInst>(I))
4170 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004171 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004172 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004173}
4174
Chris Lattner3221ad02004-04-17 22:58:41 +00004175/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4176/// in the loop that V is derived from. We allow arbitrary operations along the
4177/// way, but the operands of an operation must either be constants or a value
4178/// derived from a constant PHI. If this expression does not fit with these
4179/// constraints, return null.
4180static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4181 // If this is not an instruction, or if this is an instruction outside of the
4182 // loop, it can't be derived from a loop PHI.
4183 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004184 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004185
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004186 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004187 if (L->getHeader() == I->getParent())
4188 return PN;
4189 else
4190 // We don't currently keep track of the control flow needed to evaluate
4191 // PHIs, so we cannot handle PHIs inside of loops.
4192 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004193 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004194
4195 // If we won't be able to constant fold this expression even if the operands
4196 // are constants, return early.
4197 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004198
Chris Lattner3221ad02004-04-17 22:58:41 +00004199 // Otherwise, we can evaluate this instruction if all of its operands are
4200 // constant or derived from a PHI node themselves.
4201 PHINode *PHI = 0;
4202 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004203 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004204 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4205 if (P == 0) return 0; // Not evolving from PHI
4206 if (PHI == 0)
4207 PHI = P;
4208 else if (PHI != P)
4209 return 0; // Evolving from multiple different PHIs.
4210 }
4211
4212 // This is a expression evolving from a constant PHI!
4213 return PHI;
4214}
4215
4216/// EvaluateExpression - Given an expression that passes the
4217/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4218/// in the loop has the value PHIVal. If we can't fold this expression for some
4219/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004220static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4221 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004222 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004223 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004224 Instruction *I = cast<Instruction>(V);
4225
Dan Gohman9d4588f2010-06-22 13:15:46 +00004226 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004227
4228 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004229 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004230 if (Operands[i] == 0) return 0;
4231 }
4232
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004233 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004234 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004235 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004236 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004237 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004238}
4239
4240/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4241/// in the header of its containing loop, we know the loop executes a
4242/// constant number of times, and the PHI node is just a recurrence
4243/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004244Constant *
4245ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004246 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004247 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004248 std::map<PHINode*, Constant*>::iterator I =
4249 ConstantEvolutionLoopExitValue.find(PN);
4250 if (I != ConstantEvolutionLoopExitValue.end())
4251 return I->second;
4252
Dan Gohmane0567812010-04-08 23:03:40 +00004253 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004254 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4255
4256 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4257
4258 // Since the loop is canonicalized, the PHI node must have two entries. One
4259 // entry must be a constant (coming in from outside of the loop), and the
4260 // second must be derived from the same PHI.
4261 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4262 Constant *StartCST =
4263 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4264 if (StartCST == 0)
4265 return RetVal = 0; // Must be a constant.
4266
4267 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004268 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4269 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004270 return RetVal = 0; // Not derived from same PHI.
4271
4272 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004273 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004274 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004275
Dan Gohman46bdfb02009-02-24 18:55:53 +00004276 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004277 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004278 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4279 if (IterationNum == NumIterations)
4280 return RetVal = PHIVal; // Got exit value!
4281
4282 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004283 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004284 if (NextPHI == PHIVal)
4285 return RetVal = NextPHI; // Stopped evolving!
4286 if (NextPHI == 0)
4287 return 0; // Couldn't evaluate!
4288 PHIVal = NextPHI;
4289 }
4290}
4291
Dan Gohman07ad19b2009-07-27 16:09:48 +00004292/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004293/// constant number of times (the condition evolves only from constants),
4294/// try to evaluate a few iterations of the loop until we get the exit
4295/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004296/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004297const SCEV *
4298ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4299 Value *Cond,
4300 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004301 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004302 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004303
Dan Gohmanb92654d2010-06-19 14:17:24 +00004304 // If the loop is canonicalized, the PHI will have exactly two entries.
4305 // That's the only form we support here.
4306 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4307
4308 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004309 // second must be derived from the same PHI.
4310 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4311 Constant *StartCST =
4312 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004313 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004314
4315 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004316 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4317 !isa<Constant>(BEValue))
4318 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004319
4320 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4321 // the loop symbolically to determine when the condition gets a value of
4322 // "ExitWhen".
4323 unsigned IterationNum = 0;
4324 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4325 for (Constant *PHIVal = StartCST;
4326 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004327 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004328 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004329
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004330 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004331 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004332
Reid Spencere8019bb2007-03-01 07:25:48 +00004333 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004334 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004335 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004336 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004337
Chris Lattner3221ad02004-04-17 22:58:41 +00004338 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004339 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004340 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004341 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004342 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004343 }
4344
4345 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004346 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004347}
4348
Dan Gohmane7125f42009-09-03 15:00:26 +00004349/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004350/// at the specified scope in the program. The L value specifies a loop
4351/// nest to evaluate the expression at, where null is the top-level or a
4352/// specified loop is immediately inside of the loop.
4353///
4354/// This method can be used to compute the exit value for a variable defined
4355/// in a loop by querying what the value will hold in the parent loop.
4356///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004357/// In the case that a relevant loop exit value cannot be computed, the
4358/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004359const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004360 // Check to see if we've folded this expression at this loop before.
4361 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4362 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4363 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4364 if (!Pair.second)
4365 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004366
Dan Gohman42214892009-08-31 21:15:23 +00004367 // Otherwise compute it.
4368 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004369 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004370 return C;
4371}
4372
4373const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004374 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004375
Nick Lewycky3e630762008-02-20 06:48:22 +00004376 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004377 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004378 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004379 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004380 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004381 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4382 if (PHINode *PN = dyn_cast<PHINode>(I))
4383 if (PN->getParent() == LI->getHeader()) {
4384 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004385 // to see if the loop that contains it has a known backedge-taken
4386 // count. If so, we may be able to force computation of the exit
4387 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004388 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004389 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004390 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004391 // Okay, we know how many times the containing loop executes. If
4392 // this is a constant evolving PHI node, get the final value at
4393 // the specified iteration number.
4394 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004395 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004396 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004397 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004398 }
4399 }
4400
Reid Spencer09906f32006-12-04 21:33:23 +00004401 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004402 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004403 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004404 // result. This is particularly useful for computing loop exit values.
4405 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004406 SmallVector<Constant *, 4> Operands;
4407 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004408 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4409 Value *Op = I->getOperand(i);
4410 if (Constant *C = dyn_cast<Constant>(Op)) {
4411 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004412 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004413 }
Dan Gohman11046452010-06-29 23:43:06 +00004414
4415 // If any of the operands is non-constant and if they are
4416 // non-integer and non-pointer, don't even try to analyze them
4417 // with scev techniques.
4418 if (!isSCEVable(Op->getType()))
4419 return V;
4420
4421 const SCEV *OrigV = getSCEV(Op);
4422 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4423 MadeImprovement |= OrigV != OpV;
4424
4425 Constant *C = 0;
4426 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4427 C = SC->getValue();
4428 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4429 C = dyn_cast<Constant>(SU->getValue());
4430 if (!C) return V;
4431 if (C->getType() != Op->getType())
4432 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4433 Op->getType(),
4434 false),
4435 C, Op->getType());
4436 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004437 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004438
Dan Gohman11046452010-06-29 23:43:06 +00004439 // Check to see if getSCEVAtScope actually made an improvement.
4440 if (MadeImprovement) {
4441 Constant *C = 0;
4442 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4443 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4444 Operands[0], Operands[1], TD);
4445 else
4446 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4447 &Operands[0], Operands.size(), TD);
4448 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004449 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004450 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004451 }
4452 }
4453
4454 // This is some other type of SCEVUnknown, just return it.
4455 return V;
4456 }
4457
Dan Gohman622ed672009-05-04 22:02:23 +00004458 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004459 // Avoid performing the look-up in the common case where the specified
4460 // expression has no loop-variant portions.
4461 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004462 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004463 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004464 // Okay, at least one of these operands is loop variant but might be
4465 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004466 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4467 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004468 NewOps.push_back(OpAtScope);
4469
4470 for (++i; i != e; ++i) {
4471 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004472 NewOps.push_back(OpAtScope);
4473 }
4474 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004475 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004476 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004477 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004478 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004479 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004480 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004481 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004482 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004483 }
4484 }
4485 // If we got here, all operands are loop invariant.
4486 return Comm;
4487 }
4488
Dan Gohman622ed672009-05-04 22:02:23 +00004489 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004490 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4491 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004492 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4493 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004494 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004495 }
4496
4497 // If this is a loop recurrence for a loop that does not contain L, then we
4498 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004499 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004500 // First, attempt to evaluate each operand.
4501 // Avoid performing the look-up in the common case where the specified
4502 // expression has no loop-variant portions.
4503 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4504 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4505 if (OpAtScope == AddRec->getOperand(i))
4506 continue;
4507
4508 // Okay, at least one of these operands is loop variant but might be
4509 // foldable. Build a new instance of the folded commutative expression.
4510 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4511 AddRec->op_begin()+i);
4512 NewOps.push_back(OpAtScope);
4513 for (++i; i != e; ++i)
4514 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4515
4516 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4517 break;
4518 }
4519
4520 // If the scope is outside the addrec's loop, evaluate it by using the
4521 // loop exit value of the addrec.
4522 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004523 // To evaluate this recurrence, we need to know how many times the AddRec
4524 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004525 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004526 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004527
Eli Friedmanb42a6262008-08-04 23:49:06 +00004528 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004529 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004530 }
Dan Gohman11046452010-06-29 23:43:06 +00004531
Dan Gohmand594e6f2009-05-24 23:25:42 +00004532 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004533 }
4534
Dan Gohman622ed672009-05-04 22:02:23 +00004535 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004536 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004537 if (Op == Cast->getOperand())
4538 return Cast; // must be loop invariant
4539 return getZeroExtendExpr(Op, Cast->getType());
4540 }
4541
Dan Gohman622ed672009-05-04 22:02:23 +00004542 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004543 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004544 if (Op == Cast->getOperand())
4545 return Cast; // must be loop invariant
4546 return getSignExtendExpr(Op, Cast->getType());
4547 }
4548
Dan Gohman622ed672009-05-04 22:02:23 +00004549 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004550 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004551 if (Op == Cast->getOperand())
4552 return Cast; // must be loop invariant
4553 return getTruncateExpr(Op, Cast->getType());
4554 }
4555
Torok Edwinc23197a2009-07-14 16:55:14 +00004556 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004557 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004558}
4559
Dan Gohman66a7e852009-05-08 20:38:54 +00004560/// getSCEVAtScope - This is a convenience function which does
4561/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004562const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004563 return getSCEVAtScope(getSCEV(V), L);
4564}
4565
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004566/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4567/// following equation:
4568///
4569/// A * X = B (mod N)
4570///
4571/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4572/// A and B isn't important.
4573///
4574/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004575static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004576 ScalarEvolution &SE) {
4577 uint32_t BW = A.getBitWidth();
4578 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4579 assert(A != 0 && "A must be non-zero.");
4580
4581 // 1. D = gcd(A, N)
4582 //
4583 // The gcd of A and N may have only one prime factor: 2. The number of
4584 // trailing zeros in A is its multiplicity
4585 uint32_t Mult2 = A.countTrailingZeros();
4586 // D = 2^Mult2
4587
4588 // 2. Check if B is divisible by D.
4589 //
4590 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4591 // is not less than multiplicity of this prime factor for D.
4592 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004593 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004594
4595 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4596 // modulo (N / D).
4597 //
4598 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4599 // bit width during computations.
4600 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4601 APInt Mod(BW + 1, 0);
4602 Mod.set(BW - Mult2); // Mod = N / D
4603 APInt I = AD.multiplicativeInverse(Mod);
4604
4605 // 4. Compute the minimum unsigned root of the equation:
4606 // I * (B / D) mod (N / D)
4607 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4608
4609 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4610 // bits.
4611 return SE.getConstant(Result.trunc(BW));
4612}
Chris Lattner53e677a2004-04-02 20:23:17 +00004613
4614/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4615/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4616/// might be the same) or two SCEVCouldNotCompute objects.
4617///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004618static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004619SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004620 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004621 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4622 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4623 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004624
Chris Lattner53e677a2004-04-02 20:23:17 +00004625 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004626 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004627 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004628 return std::make_pair(CNC, CNC);
4629 }
4630
Reid Spencere8019bb2007-03-01 07:25:48 +00004631 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004632 const APInt &L = LC->getValue()->getValue();
4633 const APInt &M = MC->getValue()->getValue();
4634 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004635 APInt Two(BitWidth, 2);
4636 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004637
Dan Gohman64a845e2009-06-24 04:48:43 +00004638 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004639 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004640 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004641 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4642 // The B coefficient is M-N/2
4643 APInt B(M);
4644 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004645
Reid Spencere8019bb2007-03-01 07:25:48 +00004646 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004647 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004648
Reid Spencere8019bb2007-03-01 07:25:48 +00004649 // Compute the B^2-4ac term.
4650 APInt SqrtTerm(B);
4651 SqrtTerm *= B;
4652 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004653
Reid Spencere8019bb2007-03-01 07:25:48 +00004654 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4655 // integer value or else APInt::sqrt() will assert.
4656 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004657
Dan Gohman64a845e2009-06-24 04:48:43 +00004658 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004659 // The divisions must be performed as signed divisions.
4660 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004661 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004662 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004663 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004664 return std::make_pair(CNC, CNC);
4665 }
4666
Owen Andersone922c022009-07-22 00:24:57 +00004667 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004668
4669 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004670 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004671 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004672 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004673
Dan Gohman64a845e2009-06-24 04:48:43 +00004674 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004675 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004676 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004677}
4678
4679/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004680/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004681ScalarEvolution::BackedgeTakenInfo
4682ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004683 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004684 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004685 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004686 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004687 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004688 }
4689
Dan Gohman35738ac2009-05-04 22:30:44 +00004690 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004691 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004692 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004693
4694 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004695 // If this is an affine expression, the execution count of this branch is
4696 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004697 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004698 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004699 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004700 // equivalent to:
4701 //
4702 // Step*N = -Start (mod 2^BW)
4703 //
4704 // where BW is the common bit width of Start and Step.
4705
Chris Lattner53e677a2004-04-02 20:23:17 +00004706 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004707 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4708 L->getParentLoop());
4709 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4710 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004711
Dan Gohman622ed672009-05-04 22:02:23 +00004712 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004713 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004714
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004715 // First, handle unitary steps.
4716 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004717 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004718 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4719 return Start; // N = Start (as unsigned)
4720
4721 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004722 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004723 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004724 -StartC->getValue()->getValue(),
4725 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004726 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004727 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004728 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4729 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004730 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004731 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004732 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4733 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004734 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004735#if 0
David Greene25e0e872009-12-23 22:18:14 +00004736 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004737 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004738#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004739 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004740 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004741 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004742 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004743 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004744 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004745
Chris Lattner53e677a2004-04-02 20:23:17 +00004746 // We can only use this value if the chrec ends up with an exact zero
4747 // value at this index. When solving for "X*X != 5", for example, we
4748 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004749 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004750 if (Val->isZero())
4751 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004752 }
4753 }
4754 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004755
Dan Gohman1c343752009-06-27 21:21:31 +00004756 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004757}
4758
4759/// HowFarToNonZero - Return the number of times a backedge checking the
4760/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004761/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004762ScalarEvolution::BackedgeTakenInfo
4763ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004764 // Loops that look like: while (X == 0) are very strange indeed. We don't
4765 // handle them yet except for the trivial case. This could be expanded in the
4766 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004767
Chris Lattner53e677a2004-04-02 20:23:17 +00004768 // If the value is a constant, check to see if it is known to be non-zero
4769 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004770 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004771 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004772 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004773 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004774 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004775
Chris Lattner53e677a2004-04-02 20:23:17 +00004776 // We could implement others, but I really doubt anyone writes loops like
4777 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004778 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004779}
4780
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004781/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4782/// (which may not be an immediate predecessor) which has exactly one
4783/// successor from which BB is reachable, or null if no such block is
4784/// found.
4785///
Dan Gohman005752b2010-04-15 16:19:08 +00004786std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004787ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004788 // If the block has a unique predecessor, then there is no path from the
4789 // predecessor to the block that does not go through the direct edge
4790 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004791 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004792 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004793
4794 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004795 // If the header has a unique predecessor outside the loop, it must be
4796 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004797 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00004798 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004799
Dan Gohman005752b2010-04-15 16:19:08 +00004800 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004801}
4802
Dan Gohman763bad12009-06-20 00:35:32 +00004803/// HasSameValue - SCEV structural equivalence is usually sufficient for
4804/// testing whether two expressions are equal, however for the purposes of
4805/// looking for a condition guarding a loop, it can be useful to be a little
4806/// more general, since a front-end may have replicated the controlling
4807/// expression.
4808///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004809static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004810 // Quick check to see if they are the same SCEV.
4811 if (A == B) return true;
4812
4813 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4814 // two different instructions with the same value. Check for this case.
4815 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4816 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4817 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4818 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004819 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004820 return true;
4821
4822 // Otherwise assume they may have a different value.
4823 return false;
4824}
4825
Dan Gohmane9796502010-04-24 01:28:42 +00004826/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4827/// predicate Pred. Return true iff any changes were made.
4828///
4829bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4830 const SCEV *&LHS, const SCEV *&RHS) {
4831 bool Changed = false;
4832
4833 // Canonicalize a constant to the right side.
4834 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4835 // Check for both operands constant.
4836 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4837 if (ConstantExpr::getICmp(Pred,
4838 LHSC->getValue(),
4839 RHSC->getValue())->isNullValue())
4840 goto trivially_false;
4841 else
4842 goto trivially_true;
4843 }
4844 // Otherwise swap the operands to put the constant on the right.
4845 std::swap(LHS, RHS);
4846 Pred = ICmpInst::getSwappedPredicate(Pred);
4847 Changed = true;
4848 }
4849
4850 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004851 // addrec's loop, put the addrec on the left. Also make a dominance check,
4852 // as both operands could be addrecs loop-invariant in each other's loop.
4853 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4854 const Loop *L = AR->getLoop();
4855 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
Dan Gohmane9796502010-04-24 01:28:42 +00004856 std::swap(LHS, RHS);
4857 Pred = ICmpInst::getSwappedPredicate(Pred);
4858 Changed = true;
4859 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004860 }
Dan Gohmane9796502010-04-24 01:28:42 +00004861
4862 // If there's a constant operand, canonicalize comparisons with boundary
4863 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4864 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4865 const APInt &RA = RC->getValue()->getValue();
4866 switch (Pred) {
4867 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4868 case ICmpInst::ICMP_EQ:
4869 case ICmpInst::ICMP_NE:
4870 break;
4871 case ICmpInst::ICMP_UGE:
4872 if ((RA - 1).isMinValue()) {
4873 Pred = ICmpInst::ICMP_NE;
4874 RHS = getConstant(RA - 1);
4875 Changed = true;
4876 break;
4877 }
4878 if (RA.isMaxValue()) {
4879 Pred = ICmpInst::ICMP_EQ;
4880 Changed = true;
4881 break;
4882 }
4883 if (RA.isMinValue()) goto trivially_true;
4884
4885 Pred = ICmpInst::ICMP_UGT;
4886 RHS = getConstant(RA - 1);
4887 Changed = true;
4888 break;
4889 case ICmpInst::ICMP_ULE:
4890 if ((RA + 1).isMaxValue()) {
4891 Pred = ICmpInst::ICMP_NE;
4892 RHS = getConstant(RA + 1);
4893 Changed = true;
4894 break;
4895 }
4896 if (RA.isMinValue()) {
4897 Pred = ICmpInst::ICMP_EQ;
4898 Changed = true;
4899 break;
4900 }
4901 if (RA.isMaxValue()) goto trivially_true;
4902
4903 Pred = ICmpInst::ICMP_ULT;
4904 RHS = getConstant(RA + 1);
4905 Changed = true;
4906 break;
4907 case ICmpInst::ICMP_SGE:
4908 if ((RA - 1).isMinSignedValue()) {
4909 Pred = ICmpInst::ICMP_NE;
4910 RHS = getConstant(RA - 1);
4911 Changed = true;
4912 break;
4913 }
4914 if (RA.isMaxSignedValue()) {
4915 Pred = ICmpInst::ICMP_EQ;
4916 Changed = true;
4917 break;
4918 }
4919 if (RA.isMinSignedValue()) goto trivially_true;
4920
4921 Pred = ICmpInst::ICMP_SGT;
4922 RHS = getConstant(RA - 1);
4923 Changed = true;
4924 break;
4925 case ICmpInst::ICMP_SLE:
4926 if ((RA + 1).isMaxSignedValue()) {
4927 Pred = ICmpInst::ICMP_NE;
4928 RHS = getConstant(RA + 1);
4929 Changed = true;
4930 break;
4931 }
4932 if (RA.isMinSignedValue()) {
4933 Pred = ICmpInst::ICMP_EQ;
4934 Changed = true;
4935 break;
4936 }
4937 if (RA.isMaxSignedValue()) goto trivially_true;
4938
4939 Pred = ICmpInst::ICMP_SLT;
4940 RHS = getConstant(RA + 1);
4941 Changed = true;
4942 break;
4943 case ICmpInst::ICMP_UGT:
4944 if (RA.isMinValue()) {
4945 Pred = ICmpInst::ICMP_NE;
4946 Changed = true;
4947 break;
4948 }
4949 if ((RA + 1).isMaxValue()) {
4950 Pred = ICmpInst::ICMP_EQ;
4951 RHS = getConstant(RA + 1);
4952 Changed = true;
4953 break;
4954 }
4955 if (RA.isMaxValue()) goto trivially_false;
4956 break;
4957 case ICmpInst::ICMP_ULT:
4958 if (RA.isMaxValue()) {
4959 Pred = ICmpInst::ICMP_NE;
4960 Changed = true;
4961 break;
4962 }
4963 if ((RA - 1).isMinValue()) {
4964 Pred = ICmpInst::ICMP_EQ;
4965 RHS = getConstant(RA - 1);
4966 Changed = true;
4967 break;
4968 }
4969 if (RA.isMinValue()) goto trivially_false;
4970 break;
4971 case ICmpInst::ICMP_SGT:
4972 if (RA.isMinSignedValue()) {
4973 Pred = ICmpInst::ICMP_NE;
4974 Changed = true;
4975 break;
4976 }
4977 if ((RA + 1).isMaxSignedValue()) {
4978 Pred = ICmpInst::ICMP_EQ;
4979 RHS = getConstant(RA + 1);
4980 Changed = true;
4981 break;
4982 }
4983 if (RA.isMaxSignedValue()) goto trivially_false;
4984 break;
4985 case ICmpInst::ICMP_SLT:
4986 if (RA.isMaxSignedValue()) {
4987 Pred = ICmpInst::ICMP_NE;
4988 Changed = true;
4989 break;
4990 }
4991 if ((RA - 1).isMinSignedValue()) {
4992 Pred = ICmpInst::ICMP_EQ;
4993 RHS = getConstant(RA - 1);
4994 Changed = true;
4995 break;
4996 }
4997 if (RA.isMinSignedValue()) goto trivially_false;
4998 break;
4999 }
5000 }
5001
5002 // Check for obvious equality.
5003 if (HasSameValue(LHS, RHS)) {
5004 if (ICmpInst::isTrueWhenEqual(Pred))
5005 goto trivially_true;
5006 if (ICmpInst::isFalseWhenEqual(Pred))
5007 goto trivially_false;
5008 }
5009
Dan Gohman03557dc2010-05-03 16:35:17 +00005010 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5011 // adding or subtracting 1 from one of the operands.
5012 switch (Pred) {
5013 case ICmpInst::ICMP_SLE:
5014 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5015 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5016 /*HasNUW=*/false, /*HasNSW=*/true);
5017 Pred = ICmpInst::ICMP_SLT;
5018 Changed = true;
5019 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005020 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005021 /*HasNUW=*/false, /*HasNSW=*/true);
5022 Pred = ICmpInst::ICMP_SLT;
5023 Changed = true;
5024 }
5025 break;
5026 case ICmpInst::ICMP_SGE:
5027 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005028 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005029 /*HasNUW=*/false, /*HasNSW=*/true);
5030 Pred = ICmpInst::ICMP_SGT;
5031 Changed = true;
5032 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5033 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5034 /*HasNUW=*/false, /*HasNSW=*/true);
5035 Pred = ICmpInst::ICMP_SGT;
5036 Changed = true;
5037 }
5038 break;
5039 case ICmpInst::ICMP_ULE:
5040 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005041 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005042 /*HasNUW=*/true, /*HasNSW=*/false);
5043 Pred = ICmpInst::ICMP_ULT;
5044 Changed = true;
5045 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005046 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005047 /*HasNUW=*/true, /*HasNSW=*/false);
5048 Pred = ICmpInst::ICMP_ULT;
5049 Changed = true;
5050 }
5051 break;
5052 case ICmpInst::ICMP_UGE:
5053 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005054 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005055 /*HasNUW=*/true, /*HasNSW=*/false);
5056 Pred = ICmpInst::ICMP_UGT;
5057 Changed = true;
5058 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005059 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005060 /*HasNUW=*/true, /*HasNSW=*/false);
5061 Pred = ICmpInst::ICMP_UGT;
5062 Changed = true;
5063 }
5064 break;
5065 default:
5066 break;
5067 }
5068
Dan Gohmane9796502010-04-24 01:28:42 +00005069 // TODO: More simplifications are possible here.
5070
5071 return Changed;
5072
5073trivially_true:
5074 // Return 0 == 0.
5075 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5076 Pred = ICmpInst::ICMP_EQ;
5077 return true;
5078
5079trivially_false:
5080 // Return 0 != 0.
5081 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5082 Pred = ICmpInst::ICMP_NE;
5083 return true;
5084}
5085
Dan Gohman85b05a22009-07-13 21:35:55 +00005086bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5087 return getSignedRange(S).getSignedMax().isNegative();
5088}
5089
5090bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5091 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5092}
5093
5094bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5095 return !getSignedRange(S).getSignedMin().isNegative();
5096}
5097
5098bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5099 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5100}
5101
5102bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5103 return isKnownNegative(S) || isKnownPositive(S);
5104}
5105
5106bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5107 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005108 // Canonicalize the inputs first.
5109 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5110
Dan Gohman53c66ea2010-04-11 22:16:48 +00005111 // If LHS or RHS is an addrec, check to see if the condition is true in
5112 // every iteration of the loop.
5113 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5114 if (isLoopEntryGuardedByCond(
5115 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5116 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005117 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005118 return true;
5119 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5120 if (isLoopEntryGuardedByCond(
5121 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5122 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005123 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005124 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005125
Dan Gohman53c66ea2010-04-11 22:16:48 +00005126 // Otherwise see what can be done with known constant ranges.
5127 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5128}
5129
5130bool
5131ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5132 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005133 if (HasSameValue(LHS, RHS))
5134 return ICmpInst::isTrueWhenEqual(Pred);
5135
Dan Gohman53c66ea2010-04-11 22:16:48 +00005136 // This code is split out from isKnownPredicate because it is called from
5137 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005138 switch (Pred) {
5139 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005140 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005141 break;
5142 case ICmpInst::ICMP_SGT:
5143 Pred = ICmpInst::ICMP_SLT;
5144 std::swap(LHS, RHS);
5145 case ICmpInst::ICMP_SLT: {
5146 ConstantRange LHSRange = getSignedRange(LHS);
5147 ConstantRange RHSRange = getSignedRange(RHS);
5148 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5149 return true;
5150 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5151 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005152 break;
5153 }
5154 case ICmpInst::ICMP_SGE:
5155 Pred = ICmpInst::ICMP_SLE;
5156 std::swap(LHS, RHS);
5157 case ICmpInst::ICMP_SLE: {
5158 ConstantRange LHSRange = getSignedRange(LHS);
5159 ConstantRange RHSRange = getSignedRange(RHS);
5160 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5161 return true;
5162 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5163 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005164 break;
5165 }
5166 case ICmpInst::ICMP_UGT:
5167 Pred = ICmpInst::ICMP_ULT;
5168 std::swap(LHS, RHS);
5169 case ICmpInst::ICMP_ULT: {
5170 ConstantRange LHSRange = getUnsignedRange(LHS);
5171 ConstantRange RHSRange = getUnsignedRange(RHS);
5172 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5173 return true;
5174 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5175 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005176 break;
5177 }
5178 case ICmpInst::ICMP_UGE:
5179 Pred = ICmpInst::ICMP_ULE;
5180 std::swap(LHS, RHS);
5181 case ICmpInst::ICMP_ULE: {
5182 ConstantRange LHSRange = getUnsignedRange(LHS);
5183 ConstantRange RHSRange = getUnsignedRange(RHS);
5184 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5185 return true;
5186 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5187 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005188 break;
5189 }
5190 case ICmpInst::ICMP_NE: {
5191 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5192 return true;
5193 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5194 return true;
5195
5196 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5197 if (isKnownNonZero(Diff))
5198 return true;
5199 break;
5200 }
5201 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005202 // The check at the top of the function catches the case where
5203 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005204 break;
5205 }
5206 return false;
5207}
5208
5209/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5210/// protected by a conditional between LHS and RHS. This is used to
5211/// to eliminate casts.
5212bool
5213ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5214 ICmpInst::Predicate Pred,
5215 const SCEV *LHS, const SCEV *RHS) {
5216 // Interpret a null as meaning no loop, where there is obviously no guard
5217 // (interprocedural conditions notwithstanding).
5218 if (!L) return true;
5219
5220 BasicBlock *Latch = L->getLoopLatch();
5221 if (!Latch)
5222 return false;
5223
5224 BranchInst *LoopContinuePredicate =
5225 dyn_cast<BranchInst>(Latch->getTerminator());
5226 if (!LoopContinuePredicate ||
5227 LoopContinuePredicate->isUnconditional())
5228 return false;
5229
Dan Gohmanaf08a362010-08-10 23:46:30 +00005230 return isImpliedCond(Pred, LHS, RHS,
5231 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005232 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005233}
5234
Dan Gohman3948d0b2010-04-11 19:27:13 +00005235/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005236/// by a conditional between LHS and RHS. This is used to help avoid max
5237/// expressions in loop trip counts, and to eliminate casts.
5238bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005239ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5240 ICmpInst::Predicate Pred,
5241 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005242 // Interpret a null as meaning no loop, where there is obviously no guard
5243 // (interprocedural conditions notwithstanding).
5244 if (!L) return false;
5245
Dan Gohman859b4822009-05-18 15:36:09 +00005246 // Starting at the loop predecessor, climb up the predecessor chain, as long
5247 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005248 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005249 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005250 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005251 Pair.first;
5252 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005253
5254 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005255 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005256 if (!LoopEntryPredicate ||
5257 LoopEntryPredicate->isUnconditional())
5258 continue;
5259
Dan Gohmanaf08a362010-08-10 23:46:30 +00005260 if (isImpliedCond(Pred, LHS, RHS,
5261 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005262 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005263 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005264 }
5265
Dan Gohman38372182008-08-12 20:17:31 +00005266 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005267}
5268
Dan Gohman0f4b2852009-07-21 23:03:19 +00005269/// isImpliedCond - Test whether the condition described by Pred, LHS,
5270/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005271bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005272 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005273 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005274 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005275 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005277 if (BO->getOpcode() == Instruction::And) {
5278 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005279 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5280 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005281 } else if (BO->getOpcode() == Instruction::Or) {
5282 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005283 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5284 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005285 }
5286 }
5287
Dan Gohmanaf08a362010-08-10 23:46:30 +00005288 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005289 if (!ICI) return false;
5290
Dan Gohman85b05a22009-07-13 21:35:55 +00005291 // Bail if the ICmp's operands' types are wider than the needed type
5292 // before attempting to call getSCEV on them. This avoids infinite
5293 // recursion, since the analysis of widening casts can require loop
5294 // exit condition information for overflow checking, which would
5295 // lead back here.
5296 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005297 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005298 return false;
5299
Dan Gohman0f4b2852009-07-21 23:03:19 +00005300 // Now that we found a conditional branch that dominates the loop, check to
5301 // see if it is the comparison we are looking for.
5302 ICmpInst::Predicate FoundPred;
5303 if (Inverse)
5304 FoundPred = ICI->getInversePredicate();
5305 else
5306 FoundPred = ICI->getPredicate();
5307
5308 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5309 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005310
5311 // Balance the types. The case where FoundLHS' type is wider than
5312 // LHS' type is checked for above.
5313 if (getTypeSizeInBits(LHS->getType()) >
5314 getTypeSizeInBits(FoundLHS->getType())) {
5315 if (CmpInst::isSigned(Pred)) {
5316 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5317 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5318 } else {
5319 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5320 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5321 }
5322 }
5323
Dan Gohman0f4b2852009-07-21 23:03:19 +00005324 // Canonicalize the query to match the way instcombine will have
5325 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005326 if (SimplifyICmpOperands(Pred, LHS, RHS))
5327 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005328 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005329 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5330 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005331 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005332
5333 // Check to see if we can make the LHS or RHS match.
5334 if (LHS == FoundRHS || RHS == FoundLHS) {
5335 if (isa<SCEVConstant>(RHS)) {
5336 std::swap(FoundLHS, FoundRHS);
5337 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5338 } else {
5339 std::swap(LHS, RHS);
5340 Pred = ICmpInst::getSwappedPredicate(Pred);
5341 }
5342 }
5343
5344 // Check whether the found predicate is the same as the desired predicate.
5345 if (FoundPred == Pred)
5346 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5347
5348 // Check whether swapping the found predicate makes it the same as the
5349 // desired predicate.
5350 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5351 if (isa<SCEVConstant>(RHS))
5352 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5353 else
5354 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5355 RHS, LHS, FoundLHS, FoundRHS);
5356 }
5357
5358 // Check whether the actual condition is beyond sufficient.
5359 if (FoundPred == ICmpInst::ICMP_EQ)
5360 if (ICmpInst::isTrueWhenEqual(Pred))
5361 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5362 return true;
5363 if (Pred == ICmpInst::ICMP_NE)
5364 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5365 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5366 return true;
5367
5368 // Otherwise assume the worst.
5369 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005370}
5371
Dan Gohman0f4b2852009-07-21 23:03:19 +00005372/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005373/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005374/// and FoundRHS is true.
5375bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5376 const SCEV *LHS, const SCEV *RHS,
5377 const SCEV *FoundLHS,
5378 const SCEV *FoundRHS) {
5379 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5380 FoundLHS, FoundRHS) ||
5381 // ~x < ~y --> x > y
5382 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5383 getNotSCEV(FoundRHS),
5384 getNotSCEV(FoundLHS));
5385}
5386
5387/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005388/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005389/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005390bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005391ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5392 const SCEV *LHS, const SCEV *RHS,
5393 const SCEV *FoundLHS,
5394 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005395 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005396 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5397 case ICmpInst::ICMP_EQ:
5398 case ICmpInst::ICMP_NE:
5399 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5400 return true;
5401 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005402 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005403 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005404 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5405 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005406 return true;
5407 break;
5408 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005409 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005410 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5411 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005412 return true;
5413 break;
5414 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005415 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005416 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5417 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005418 return true;
5419 break;
5420 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005421 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005422 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5423 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005424 return true;
5425 break;
5426 }
5427
5428 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005429}
5430
Dan Gohman51f53b72009-06-21 23:46:38 +00005431/// getBECount - Subtract the end and start values and divide by the step,
5432/// rounding up, to get the number of times the backedge is executed. Return
5433/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005434const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005435 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005436 const SCEV *Step,
5437 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005438 assert(!isKnownNegative(Step) &&
5439 "This code doesn't handle negative strides yet!");
5440
Dan Gohman51f53b72009-06-21 23:46:38 +00005441 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005442 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005443 const SCEV *Diff = getMinusSCEV(End, Start);
5444 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005445
5446 // Add an adjustment to the difference between End and Start so that
5447 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005448 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005449
Dan Gohman1f96e672009-09-17 18:05:20 +00005450 if (!NoWrap) {
5451 // Check Add for unsigned overflow.
5452 // TODO: More sophisticated things could be done here.
5453 const Type *WideTy = IntegerType::get(getContext(),
5454 getTypeSizeInBits(Ty) + 1);
5455 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5456 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5457 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5458 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5459 return getCouldNotCompute();
5460 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005461
5462 return getUDivExpr(Add, Step);
5463}
5464
Chris Lattnerdb25de42005-08-15 23:33:51 +00005465/// HowManyLessThans - Return the number of times a backedge containing the
5466/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005467/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005468ScalarEvolution::BackedgeTakenInfo
5469ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5470 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005471 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005472 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005473
Dan Gohman35738ac2009-05-04 22:30:44 +00005474 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005475 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005476 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005477
Dan Gohman1f96e672009-09-17 18:05:20 +00005478 // Check to see if we have a flag which makes analysis easy.
5479 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5480 AddRec->hasNoUnsignedWrap();
5481
Chris Lattnerdb25de42005-08-15 23:33:51 +00005482 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005483 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005484 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005485
Dan Gohman52fddd32010-01-26 04:40:18 +00005486 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005487 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005488 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005489 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005490 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005491 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005492 // value and past the maximum value for its type in a single step.
5493 // Note that it's not sufficient to check NoWrap here, because even
5494 // though the value after a wrap is undefined, it's not undefined
5495 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005496 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005497 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005498 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005499 if (isSigned) {
5500 APInt Max = APInt::getSignedMaxValue(BitWidth);
5501 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5502 .slt(getSignedRange(RHS).getSignedMax()))
5503 return getCouldNotCompute();
5504 } else {
5505 APInt Max = APInt::getMaxValue(BitWidth);
5506 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5507 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5508 return getCouldNotCompute();
5509 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005510 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005511 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005512 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005513
Dan Gohmana1af7572009-04-30 20:47:05 +00005514 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5515 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5516 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005517 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005518
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005519 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005520 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005521
Dan Gohmana1af7572009-04-30 20:47:05 +00005522 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005523 const SCEV *MinStart = getConstant(isSigned ?
5524 getSignedRange(Start).getSignedMin() :
5525 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005526
Dan Gohmana1af7572009-04-30 20:47:05 +00005527 // If we know that the condition is true in order to enter the loop,
5528 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005529 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5530 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005531 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005532 if (!isLoopEntryGuardedByCond(L,
5533 isSigned ? ICmpInst::ICMP_SLT :
5534 ICmpInst::ICMP_ULT,
5535 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005536 End = isSigned ? getSMaxExpr(RHS, Start)
5537 : getUMaxExpr(RHS, Start);
5538
5539 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005540 const SCEV *MaxEnd = getConstant(isSigned ?
5541 getSignedRange(End).getSignedMax() :
5542 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005543
Dan Gohman52fddd32010-01-26 04:40:18 +00005544 // If MaxEnd is within a step of the maximum integer value in its type,
5545 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005546 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005547 // compute the correct value.
5548 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005549 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005550 MaxEnd = isSigned ?
5551 getSMinExpr(MaxEnd,
5552 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5553 StepMinusOne)) :
5554 getUMinExpr(MaxEnd,
5555 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5556 StepMinusOne));
5557
Dan Gohmana1af7572009-04-30 20:47:05 +00005558 // Finally, we subtract these two values and divide, rounding up, to get
5559 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005560 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005561
5562 // The maximum backedge count is similar, except using the minimum start
5563 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005564 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005565
5566 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005567 }
5568
Dan Gohman1c343752009-06-27 21:21:31 +00005569 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005570}
5571
Chris Lattner53e677a2004-04-02 20:23:17 +00005572/// getNumIterationsInRange - Return the number of iterations of this loop that
5573/// produce values in the specified constant range. Another way of looking at
5574/// this is that it returns the first iteration number where the value is not in
5575/// the condition, thus computing the exit count. If the iteration count can't
5576/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005577const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005578 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005579 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005580 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005581
5582 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005583 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005584 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005585 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005586 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005587 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005588 if (const SCEVAddRecExpr *ShiftedAddRec =
5589 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005590 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005591 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005592 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005593 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005594 }
5595
5596 // The only time we can solve this is when we have all constant indices.
5597 // Otherwise, we cannot determine the overflow conditions.
5598 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5599 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005600 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005601
5602
5603 // Okay at this point we know that all elements of the chrec are constants and
5604 // that the start element is zero.
5605
5606 // First check to see if the range contains zero. If not, the first
5607 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005608 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005609 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005610 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005611
Chris Lattner53e677a2004-04-02 20:23:17 +00005612 if (isAffine()) {
5613 // If this is an affine expression then we have this situation:
5614 // Solve {0,+,A} in Range === Ax in Range
5615
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005616 // We know that zero is in the range. If A is positive then we know that
5617 // the upper value of the range must be the first possible exit value.
5618 // If A is negative then the lower of the range is the last possible loop
5619 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005620 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005621 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5622 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005623
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005624 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005625 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005626 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005627
5628 // Evaluate at the exit value. If we really did fall out of the valid
5629 // range, then we computed our trip count, otherwise wrap around or other
5630 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005631 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005632 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005633 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005634
5635 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005636 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005637 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005638 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005639 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005640 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005641 } else if (isQuadratic()) {
5642 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5643 // quadratic equation to solve it. To do this, we must frame our problem in
5644 // terms of figuring out when zero is crossed, instead of when
5645 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005646 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005647 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005648 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005649
5650 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005651 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005652 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005653 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5654 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005655 if (R1) {
5656 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005657 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005658 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005659 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005660 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005661 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005662
Chris Lattner53e677a2004-04-02 20:23:17 +00005663 // Make sure the root is not off by one. The returned iteration should
5664 // not be in the range, but the previous one should be. When solving
5665 // for "X*X < 5", for example, we should not return a root of 2.
5666 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005667 R1->getValue(),
5668 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005669 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005670 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005671 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005672 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005673
Dan Gohman246b2562007-10-22 18:31:58 +00005674 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005675 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005676 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005677 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005678 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005679
Chris Lattner53e677a2004-04-02 20:23:17 +00005680 // If R1 was not in the range, then it is a good return value. Make
5681 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005682 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005683 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005684 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005685 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005686 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005687 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005688 }
5689 }
5690 }
5691
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005692 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005693}
5694
5695
5696
5697//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005698// SCEVCallbackVH Class Implementation
5699//===----------------------------------------------------------------------===//
5700
Dan Gohman1959b752009-05-19 19:22:47 +00005701void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005702 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005703 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5704 SE->ConstantEvolutionLoopExitValue.erase(PN);
5705 SE->Scalars.erase(getValPtr());
5706 // this now dangles!
5707}
5708
Dan Gohman81f91212010-07-28 01:09:07 +00005709void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005710 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005711
Dan Gohman35738ac2009-05-04 22:30:44 +00005712 // Forget all the expressions associated with users of the old value,
5713 // so that future queries will recompute the expressions using the new
5714 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00005715 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00005716 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005717 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005718 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5719 UI != UE; ++UI)
5720 Worklist.push_back(*UI);
5721 while (!Worklist.empty()) {
5722 User *U = Worklist.pop_back_val();
5723 // Deleting the Old value will cause this to dangle. Postpone
5724 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00005725 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00005726 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00005727 if (!Visited.insert(U))
5728 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005729 if (PHINode *PN = dyn_cast<PHINode>(U))
5730 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005731 SE->Scalars.erase(U);
5732 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5733 UI != UE; ++UI)
5734 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005735 }
Dan Gohman59846ac2010-07-28 00:28:25 +00005736 // Delete the Old value.
5737 if (PHINode *PN = dyn_cast<PHINode>(Old))
5738 SE->ConstantEvolutionLoopExitValue.erase(PN);
5739 SE->Scalars.erase(Old);
5740 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00005741}
5742
Dan Gohman1959b752009-05-19 19:22:47 +00005743ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005744 : CallbackVH(V), SE(se) {}
5745
5746//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005747// ScalarEvolution Class Implementation
5748//===----------------------------------------------------------------------===//
5749
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005750ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00005751 : FunctionPass(ID), FirstUnknown(0) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005752}
5753
Chris Lattner53e677a2004-04-02 20:23:17 +00005754bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005755 this->F = &F;
5756 LI = &getAnalysis<LoopInfo>();
5757 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005758 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005759 return false;
5760}
5761
5762void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00005763 // Iterate through all the SCEVUnknown instances and call their
5764 // destructors, so that they release their references to their values.
5765 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5766 U->~SCEVUnknown();
5767 FirstUnknown = 0;
5768
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005769 Scalars.clear();
5770 BackedgeTakenCounts.clear();
5771 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005772 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005773 UniqueSCEVs.clear();
5774 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005775}
5776
5777void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5778 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005779 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005780 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005781}
5782
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005783bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005784 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005785}
5786
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005787static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005788 const Loop *L) {
5789 // Print all inner loops first
5790 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5791 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005792
Dan Gohman30733292010-01-09 18:17:45 +00005793 OS << "Loop ";
5794 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5795 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005796
Dan Gohman5d984912009-12-18 01:14:11 +00005797 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005798 L->getExitBlocks(ExitBlocks);
5799 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005800 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005801
Dan Gohman46bdfb02009-02-24 18:55:53 +00005802 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5803 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005804 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005805 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005806 }
5807
Dan Gohman30733292010-01-09 18:17:45 +00005808 OS << "\n"
5809 "Loop ";
5810 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5811 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005812
5813 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5814 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5815 } else {
5816 OS << "Unpredictable max backedge-taken count. ";
5817 }
5818
5819 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005820}
5821
Dan Gohman5d984912009-12-18 01:14:11 +00005822void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005823 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005824 // out SCEV values of all instructions that are interesting. Doing
5825 // this potentially causes it to create new SCEV objects though,
5826 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005827 // observable from outside the class though, so casting away the
5828 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005829 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005830
Dan Gohman30733292010-01-09 18:17:45 +00005831 OS << "Classifying expressions for: ";
5832 WriteAsOperand(OS, F, /*PrintType=*/false);
5833 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005834 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005835 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005836 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005837 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005838 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005839 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005840
Dan Gohman0c689c52009-06-19 17:49:54 +00005841 const Loop *L = LI->getLoopFor((*I).getParent());
5842
Dan Gohman0bba49c2009-07-07 17:06:11 +00005843 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005844 if (AtUse != SV) {
5845 OS << " --> ";
5846 AtUse->print(OS);
5847 }
5848
5849 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005850 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005851 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005852 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005853 OS << "<<Unknown>>";
5854 } else {
5855 OS << *ExitValue;
5856 }
5857 }
5858
Chris Lattner53e677a2004-04-02 20:23:17 +00005859 OS << "\n";
5860 }
5861
Dan Gohman30733292010-01-09 18:17:45 +00005862 OS << "Determining loop execution counts for: ";
5863 WriteAsOperand(OS, F, /*PrintType=*/false);
5864 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005865 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5866 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005867}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005868