blob: c66fb1d79843dbadb4c24564144466848d2c1023 [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
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "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 Gohmanfd447ef2010-06-07 19:36:14 +0000144 SCEV(FoldingSetNodeIDRef(), 0, 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 Gohmanfd447ef2010-06-07 19:36:14 +0000180 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator),
181 CurAllocationSequenceNumber++,
182 V);
Dan Gohman1c343752009-06-27 21:21:31 +0000183 UniqueSCEVs.InsertNode(S, IP);
184 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185}
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Dan Gohman0bba49c2009-07-07 17:06:11 +0000187const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000188 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000189}
190
Dan Gohman0bba49c2009-07-07 17:06:11 +0000191const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000192ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000193 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
194 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000195}
196
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000197const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000198
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000199void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000200 WriteAsOperand(OS, V, false);
201}
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000203SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, unsigned Num,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000204 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000205 : SCEV(ID, Num, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000206
Dan Gohman84923602009-04-21 01:25:57 +0000207bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
208 return Op->dominates(BB, DT);
209}
210
Dan Gohman6e70e312009-09-27 15:26:03 +0000211bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
212 return Op->properlyDominates(BB, DT);
213}
214
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000215SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, unsigned Num,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000216 const SCEV *op, const Type *ty)
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000217 : SCEVCastExpr(ID, Num, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000218 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
219 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221}
Chris Lattner53e677a2004-04-02 20:23:17 +0000222
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000223void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000224 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000225}
226
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000227SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, unsigned Num,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000228 const SCEV *op, const Type *ty)
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000229 : SCEVCastExpr(ID, Num, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000230 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
231 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233}
234
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000235void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000236 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000237}
238
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000239SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, unsigned Num,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000240 const SCEV *op, const Type *ty)
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000241 : SCEVCastExpr(ID, Num, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000242 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
243 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000244 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000245}
246
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000247void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000248 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000249}
250
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000251void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000252 const char *OpStr = getOperationStr();
Dan Gohmana5145c82010-04-16 15:03:25 +0000253 OS << "(";
254 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
255 OS << **I;
256 if (next(I) != E)
257 OS << OpStr;
258 }
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000259 OS << ")";
260}
261
Dan Gohmanecb403a2009-05-07 14:00:19 +0000262bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000263 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
264 if (!getOperand(i)->dominates(BB, DT))
265 return false;
266 }
267 return true;
268}
269
Dan Gohman6e70e312009-09-27 15:26:03 +0000270bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
271 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
272 if (!getOperand(i)->properlyDominates(BB, DT))
273 return false;
274 }
275 return true;
276}
277
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000278bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
279 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
280}
281
Dan Gohman6e70e312009-09-27 15:26:03 +0000282bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
283 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
284}
285
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000286void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000287 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000288}
289
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000290const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000291 // In most cases the types of LHS and RHS will be the same, but in some
292 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
293 // depend on the type for correctness, but handling types carefully can
294 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
295 // a pointer type than the RHS, so use the RHS' type here.
296 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297}
298
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000299bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000300 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000301 if (!QueryLoop)
302 return false;
303
304 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000305 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000306 return false;
307
308 // This recurrence is variant w.r.t. QueryLoop if any of its operands
309 // are variant.
310 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
311 if (!getOperand(i)->isLoopInvariant(QueryLoop))
312 return false;
313
314 // Otherwise it's loop-invariant.
315 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000316}
317
Dan Gohman39125d82010-02-13 00:19:39 +0000318bool
319SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
320 return DT->dominates(L->getHeader(), BB) &&
321 SCEVNAryExpr::dominates(BB, DT);
322}
323
324bool
325SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
326 // This uses a "dominates" query instead of "properly dominates" query because
327 // the instruction which produces the addrec's value is a PHI, and a PHI
328 // effectively properly dominates its entire containing block.
329 return DT->dominates(L->getHeader(), BB) &&
330 SCEVNAryExpr::properlyDominates(BB, DT);
331}
332
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000333void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000335 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000337 OS << "}<";
338 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
339 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000340}
Chris Lattner53e677a2004-04-02 20:23:17 +0000341
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000342bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
343 // All non-instruction values are loop invariant. All instructions are loop
344 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000345 // Instructions are never considered invariant in the function body
346 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000347 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman92329c72009-12-18 01:24:09 +0000348 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000349 return true;
350}
Chris Lattner53e677a2004-04-02 20:23:17 +0000351
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000352bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
353 if (Instruction *I = dyn_cast<Instruction>(getValue()))
354 return DT->dominates(I->getParent(), BB);
355 return true;
356}
357
Dan Gohman6e70e312009-09-27 15:26:03 +0000358bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
359 if (Instruction *I = dyn_cast<Instruction>(getValue()))
360 return DT->properlyDominates(I->getParent(), BB);
361 return true;
362}
363
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000364const Type *SCEVUnknown::getType() const {
365 return V->getType();
366}
Chris Lattner53e677a2004-04-02 20:23:17 +0000367
Dan Gohman0f5efe52010-01-28 02:15:55 +0000368bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
369 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
370 if (VCE->getOpcode() == Instruction::PtrToInt)
371 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000372 if (CE->getOpcode() == Instruction::GetElementPtr &&
373 CE->getOperand(0)->isNullValue() &&
374 CE->getNumOperands() == 2)
375 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
376 if (CI->isOne()) {
377 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
378 ->getElementType();
379 return true;
380 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000381
382 return false;
383}
384
385bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
386 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
387 if (VCE->getOpcode() == Instruction::PtrToInt)
388 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000389 if (CE->getOpcode() == Instruction::GetElementPtr &&
390 CE->getOperand(0)->isNullValue()) {
391 const Type *Ty =
392 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
393 if (const StructType *STy = dyn_cast<StructType>(Ty))
394 if (!STy->isPacked() &&
395 CE->getNumOperands() == 3 &&
396 CE->getOperand(1)->isNullValue()) {
397 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
398 if (CI->isOne() &&
399 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000400 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000401 AllocTy = STy->getElementType(1);
402 return true;
403 }
404 }
405 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000406
407 return false;
408}
409
Dan Gohman4f8eea82010-02-01 18:27:38 +0000410bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
411 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
412 if (VCE->getOpcode() == Instruction::PtrToInt)
413 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
414 if (CE->getOpcode() == Instruction::GetElementPtr &&
415 CE->getNumOperands() == 3 &&
416 CE->getOperand(0)->isNullValue() &&
417 CE->getOperand(1)->isNullValue()) {
418 const Type *Ty =
419 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
420 // Ignore vector types here so that ScalarEvolutionExpander doesn't
421 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000422 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000423 CTy = Ty;
424 FieldNo = CE->getOperand(2);
425 return true;
426 }
427 }
428
429 return false;
430}
431
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000432void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000433 const Type *AllocTy;
434 if (isSizeOf(AllocTy)) {
435 OS << "sizeof(" << *AllocTy << ")";
436 return;
437 }
438 if (isAlignOf(AllocTy)) {
439 OS << "alignof(" << *AllocTy << ")";
440 return;
441 }
442
Dan Gohman4f8eea82010-02-01 18:27:38 +0000443 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000444 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000445 if (isOffsetOf(CTy, FieldNo)) {
446 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000447 WriteAsOperand(OS, FieldNo, false);
448 OS << ")";
449 return;
450 }
451
452 // Otherwise just print it normally.
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000453 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000454}
455
Chris Lattner8d741b82004-06-20 06:23:15 +0000456//===----------------------------------------------------------------------===//
457// SCEV Utilities
458//===----------------------------------------------------------------------===//
459
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000460static bool CompareTypes(const Type *A, const Type *B) {
461 if (A->getTypeID() != B->getTypeID())
462 return A->getTypeID() < B->getTypeID();
463 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
464 const IntegerType *BI = cast<IntegerType>(B);
465 return AI->getBitWidth() < BI->getBitWidth();
466 }
467 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
468 const PointerType *BI = cast<PointerType>(B);
469 return CompareTypes(AI->getElementType(), BI->getElementType());
470 }
471 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
472 const ArrayType *BI = cast<ArrayType>(B);
473 if (AI->getNumElements() != BI->getNumElements())
474 return AI->getNumElements() < BI->getNumElements();
475 return CompareTypes(AI->getElementType(), BI->getElementType());
476 }
477 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
478 const VectorType *BI = cast<VectorType>(B);
479 if (AI->getNumElements() != BI->getNumElements())
480 return AI->getNumElements() < BI->getNumElements();
481 return CompareTypes(AI->getElementType(), BI->getElementType());
482 }
483 if (const StructType *AI = dyn_cast<StructType>(A)) {
484 const StructType *BI = cast<StructType>(B);
485 if (AI->getNumElements() != BI->getNumElements())
486 return AI->getNumElements() < BI->getNumElements();
487 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
488 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
489 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
490 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
491 }
492 return false;
493}
494
Chris Lattner8d741b82004-06-20 06:23:15 +0000495namespace {
496 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
497 /// than the complexity of the RHS. This comparator is used to canonicalize
498 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000499 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000500 LoopInfo *LI;
501 public:
502 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
503
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000504 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000505 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
506 if (LHS == RHS)
507 return false;
508
Dan Gohman72861302009-05-07 14:39:04 +0000509 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohmanef071582010-06-07 19:12:54 +0000510 unsigned LST = LHS->getSCEVType();
511 unsigned RST = RHS->getSCEVType();
512 if (LST != RST)
513 return LST < RST;
Dan Gohman72861302009-05-07 14:39:04 +0000514
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000515 // Then, pick an arbitrary deterministic sort.
516 return LHS->getAllocationSequenceNumber() <
517 RHS->getAllocationSequenceNumber();
Chris Lattner8d741b82004-06-20 06:23:15 +0000518 }
519 };
520}
521
522/// GroupByComplexity - Given a list of SCEV objects, order them by their
523/// complexity, and group objects of the same complexity together by value.
524/// When this routine is finished, we know that any duplicates in the vector are
525/// consecutive and that complexity is monotonically increasing.
526///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000527/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000528/// results from this routine. In other words, we don't want the results of
529/// this to depend on where the addresses of various SCEV objects happened to
530/// land in memory.
531///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000532static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000533 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000534 if (Ops.size() < 2) return; // Noop
Dan Gohman4d52c6d2010-06-07 19:06:13 +0000535
536 SCEVComplexityCompare Comp(LI);
537
Chris Lattner8d741b82004-06-20 06:23:15 +0000538 if (Ops.size() == 2) {
539 // This is the common case, which also happens to be trivially simple.
540 // Special case it.
Dan Gohman4d52c6d2010-06-07 19:06:13 +0000541 if (Comp(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000542 std::swap(Ops[0], Ops[1]);
543 return;
544 }
545
Dan Gohman4d52c6d2010-06-07 19:06:13 +0000546 std::stable_sort(Ops.begin(), Ops.end(), Comp);
Chris Lattner8d741b82004-06-20 06:23:15 +0000547}
548
Chris Lattner53e677a2004-04-02 20:23:17 +0000549
Chris Lattner53e677a2004-04-02 20:23:17 +0000550
551//===----------------------------------------------------------------------===//
552// Simple SCEV method implementations
553//===----------------------------------------------------------------------===//
554
Eli Friedmanb42a6262008-08-04 23:49:06 +0000555/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000556/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000557static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000558 ScalarEvolution &SE,
559 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000560 // Handle the simplest case efficiently.
561 if (K == 1)
562 return SE.getTruncateOrZeroExtend(It, ResultTy);
563
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000564 // We are using the following formula for BC(It, K):
565 //
566 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
567 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000568 // Suppose, W is the bitwidth of the return value. We must be prepared for
569 // overflow. Hence, we must assure that the result of our computation is
570 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
571 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000572 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000573 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000574 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000575 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
576 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000577 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000578 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000579 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000580 // This formula is trivially equivalent to the previous formula. However,
581 // this formula can be implemented much more efficiently. The trick is that
582 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
583 // arithmetic. To do exact division in modular arithmetic, all we have
584 // to do is multiply by the inverse. Therefore, this step can be done at
585 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000586 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000587 // The next issue is how to safely do the division by 2^T. The way this
588 // is done is by doing the multiplication step at a width of at least W + T
589 // bits. This way, the bottom W+T bits of the product are accurate. Then,
590 // when we perform the division by 2^T (which is equivalent to a right shift
591 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
592 // truncated out after the division by 2^T.
593 //
594 // In comparison to just directly using the first formula, this technique
595 // is much more efficient; using the first formula requires W * K bits,
596 // but this formula less than W + K bits. Also, the first formula requires
597 // a division step, whereas this formula only requires multiplies and shifts.
598 //
599 // It doesn't matter whether the subtraction step is done in the calculation
600 // width or the input iteration count's width; if the subtraction overflows,
601 // the result must be zero anyway. We prefer here to do it in the width of
602 // the induction variable because it helps a lot for certain cases; CodeGen
603 // isn't smart enough to ignore the overflow, which leads to much less
604 // efficient code if the width of the subtraction is wider than the native
605 // register width.
606 //
607 // (It's possible to not widen at all by pulling out factors of 2 before
608 // the multiplication; for example, K=2 can be calculated as
609 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
610 // extra arithmetic, so it's not an obvious win, and it gets
611 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000612
Eli Friedmanb42a6262008-08-04 23:49:06 +0000613 // Protection from insane SCEVs; this bound is conservative,
614 // but it probably doesn't matter.
615 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000616 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000617
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000618 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000619
Eli Friedmanb42a6262008-08-04 23:49:06 +0000620 // Calculate K! / 2^T and T; we divide out the factors of two before
621 // multiplying for calculating K! / 2^T to avoid overflow.
622 // Other overflow doesn't matter because we only care about the bottom
623 // W bits of the result.
624 APInt OddFactorial(W, 1);
625 unsigned T = 1;
626 for (unsigned i = 3; i <= K; ++i) {
627 APInt Mult(W, i);
628 unsigned TwoFactors = Mult.countTrailingZeros();
629 T += TwoFactors;
630 Mult = Mult.lshr(TwoFactors);
631 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000632 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000633
Eli Friedmanb42a6262008-08-04 23:49:06 +0000634 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000635 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000636
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000637 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000638 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
639
640 // Calculate the multiplicative inverse of K! / 2^T;
641 // this multiplication factor will perform the exact division by
642 // K! / 2^T.
643 APInt Mod = APInt::getSignedMinValue(W+1);
644 APInt MultiplyFactor = OddFactorial.zext(W+1);
645 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
646 MultiplyFactor = MultiplyFactor.trunc(W);
647
648 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000649 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
650 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000651 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000652 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000653 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000654 Dividend = SE.getMulExpr(Dividend,
655 SE.getTruncateOrZeroExtend(S, CalculationTy));
656 }
657
658 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000659 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000660
661 // Truncate the result, and divide by K! / 2^T.
662
663 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
664 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000665}
666
Chris Lattner53e677a2004-04-02 20:23:17 +0000667/// evaluateAtIteration - Return the value of this chain of recurrences at
668/// the specified iteration number. We can evaluate this recurrence by
669/// multiplying each element in the chain by the binomial coefficient
670/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
671///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000672/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000673///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000674/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000675///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000676const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000677 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000678 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000679 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000680 // The computation is correct in the face of overflow provided that the
681 // multiplication is performed _after_ the evaluation of the binomial
682 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000683 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000684 if (isa<SCEVCouldNotCompute>(Coeff))
685 return Coeff;
686
687 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000688 }
689 return Result;
690}
691
Chris Lattner53e677a2004-04-02 20:23:17 +0000692//===----------------------------------------------------------------------===//
693// SCEV Expression folder implementations
694//===----------------------------------------------------------------------===//
695
Dan Gohman0bba49c2009-07-07 17:06:11 +0000696const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000697 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000698 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000699 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000700 assert(isSCEVable(Ty) &&
701 "This is not a conversion to a SCEVable type!");
702 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000703
Dan Gohmanc050fd92009-07-13 20:50:19 +0000704 FoldingSetNodeID ID;
705 ID.AddInteger(scTruncate);
706 ID.AddPointer(Op);
707 ID.AddPointer(Ty);
708 void *IP = 0;
709 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
710
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000711 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000712 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000713 return getConstant(
714 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000715
Dan Gohman20900ca2009-04-22 16:20:48 +0000716 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000717 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000718 return getTruncateExpr(ST->getOperand(), Ty);
719
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000720 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000721 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000722 return getTruncateOrSignExtend(SS->getOperand(), Ty);
723
724 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000725 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000726 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
727
Dan Gohman6864db62009-06-18 16:24:47 +0000728 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000729 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000730 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000731 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000732 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
733 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000734 }
735
Dan Gohmanc050fd92009-07-13 20:50:19 +0000736 // The cast wasn't folded; create an explicit cast node.
737 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000738 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +0000739 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000740 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +0000741 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000742 UniqueSCEVs.InsertNode(S, IP);
743 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000744}
745
Dan Gohman0bba49c2009-07-07 17:06:11 +0000746const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000747 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000748 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000749 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000750 assert(isSCEVable(Ty) &&
751 "This is not a conversion to a SCEVable type!");
752 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000753
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000754 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000755 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000756 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000757 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
758 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000759 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000760 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000761
Dan Gohman20900ca2009-04-22 16:20:48 +0000762 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000763 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000764 return getZeroExtendExpr(SZ->getOperand(), Ty);
765
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000766 // Before doing any expensive analysis, check to see if we've already
767 // computed a SCEV for this Op and Ty.
768 FoldingSetNodeID ID;
769 ID.AddInteger(scZeroExtend);
770 ID.AddPointer(Op);
771 ID.AddPointer(Ty);
772 void *IP = 0;
773 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
774
Dan Gohman01ecca22009-04-27 20:16:15 +0000775 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000776 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000777 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000778 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000779 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000780 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000781 const SCEV *Start = AR->getStart();
782 const SCEV *Step = AR->getStepRecurrence(*this);
783 unsigned BitWidth = getTypeSizeInBits(AR->getType());
784 const Loop *L = AR->getLoop();
785
Dan Gohmaneb490a72009-07-25 01:22:26 +0000786 // If we have special knowledge that this addrec won't overflow,
787 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000788 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000789 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
790 getZeroExtendExpr(Step, Ty),
791 L);
792
Dan Gohman01ecca22009-04-27 20:16:15 +0000793 // Check whether the backedge-taken count is SCEVCouldNotCompute.
794 // Note that this serves two purposes: It filters out loops that are
795 // simply not analyzable, and it covers the case where this code is
796 // being called from within backedge-taken count analysis, such that
797 // attempting to ask for the backedge-taken count would likely result
798 // in infinite recursion. In the later case, the analysis code will
799 // cope with a conservative value, and it will take care to purge
800 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000801 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000802 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000803 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000804 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000805
806 // Check whether the backedge-taken count can be losslessly casted to
807 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000808 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000809 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000810 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000811 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
812 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000813 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000814 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000815 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000816 const SCEV *Add = getAddExpr(Start, ZMul);
817 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000818 getAddExpr(getZeroExtendExpr(Start, WideTy),
819 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
820 getZeroExtendExpr(Step, WideTy)));
821 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000822 // Return the expression with the addrec on the outside.
823 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
824 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000825 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000826
827 // Similar to above, only this time treat the step value as signed.
828 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000829 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000830 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000831 OperandExtendedAdd =
832 getAddExpr(getZeroExtendExpr(Start, WideTy),
833 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
834 getSignExtendExpr(Step, WideTy)));
835 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000836 // Return the expression with the addrec on the outside.
837 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
838 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000839 L);
840 }
841
842 // If the backedge is guarded by a comparison with the pre-inc value
843 // the addrec is safe. Also, if the entry is guarded by a comparison
844 // with the start value and the backedge is guarded by a comparison
845 // with the post-inc value, the addrec is safe.
846 if (isKnownPositive(Step)) {
847 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
848 getUnsignedRange(Step).getUnsignedMax());
849 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000850 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000851 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
852 AR->getPostIncExpr(*this), N)))
853 // Return the expression with the addrec on the outside.
854 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
855 getZeroExtendExpr(Step, Ty),
856 L);
857 } else if (isKnownNegative(Step)) {
858 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
859 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +0000860 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
861 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000862 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
863 AR->getPostIncExpr(*this), N)))
864 // Return the expression with the addrec on the outside.
865 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
866 getSignExtendExpr(Step, Ty),
867 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000868 }
869 }
870 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000871
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000872 // The cast wasn't folded; create an explicit cast node.
873 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000874 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +0000875 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +0000876 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +0000877 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000878 UniqueSCEVs.InsertNode(S, IP);
879 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000880}
881
Dan Gohman0bba49c2009-07-07 17:06:11 +0000882const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000883 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000884 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000885 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000886 assert(isSCEVable(Ty) &&
887 "This is not a conversion to a SCEVable type!");
888 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000889
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000890 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000891 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000892 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000893 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
894 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000895 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000896 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000897
Dan Gohman20900ca2009-04-22 16:20:48 +0000898 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000899 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000900 return getSignExtendExpr(SS->getOperand(), Ty);
901
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000902 // Before doing any expensive analysis, check to see if we've already
903 // computed a SCEV for this Op and Ty.
904 FoldingSetNodeID ID;
905 ID.AddInteger(scSignExtend);
906 ID.AddPointer(Op);
907 ID.AddPointer(Ty);
908 void *IP = 0;
909 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
910
Dan Gohman01ecca22009-04-27 20:16:15 +0000911 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000912 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000913 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000914 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000915 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000916 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000917 const SCEV *Start = AR->getStart();
918 const SCEV *Step = AR->getStepRecurrence(*this);
919 unsigned BitWidth = getTypeSizeInBits(AR->getType());
920 const Loop *L = AR->getLoop();
921
Dan Gohmaneb490a72009-07-25 01:22:26 +0000922 // If we have special knowledge that this addrec won't overflow,
923 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000924 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000925 return getAddRecExpr(getSignExtendExpr(Start, Ty),
926 getSignExtendExpr(Step, Ty),
927 L);
928
Dan Gohman01ecca22009-04-27 20:16:15 +0000929 // Check whether the backedge-taken count is SCEVCouldNotCompute.
930 // Note that this serves two purposes: It filters out loops that are
931 // simply not analyzable, and it covers the case where this code is
932 // being called from within backedge-taken count analysis, such that
933 // attempting to ask for the backedge-taken count would likely result
934 // in infinite recursion. In the later case, the analysis code will
935 // cope with a conservative value, and it will take care to purge
936 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000937 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000938 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000939 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000940 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000941
942 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000943 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000944 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000945 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000946 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000947 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
948 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000949 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000950 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000951 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000952 const SCEV *Add = getAddExpr(Start, SMul);
953 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000954 getAddExpr(getSignExtendExpr(Start, WideTy),
955 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
956 getSignExtendExpr(Step, WideTy)));
957 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000958 // Return the expression with the addrec on the outside.
959 return getAddRecExpr(getSignExtendExpr(Start, Ty),
960 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000961 L);
Dan Gohman850f7912009-07-16 17:34:36 +0000962
963 // Similar to above, only this time treat the step value as unsigned.
964 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +0000965 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +0000966 Add = getAddExpr(Start, UMul);
967 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +0000968 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +0000969 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
970 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +0000971 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +0000972 // Return the expression with the addrec on the outside.
973 return getAddRecExpr(getSignExtendExpr(Start, Ty),
974 getZeroExtendExpr(Step, Ty),
975 L);
Dan Gohman85b05a22009-07-13 21:35:55 +0000976 }
977
978 // If the backedge is guarded by a comparison with the pre-inc value
979 // the addrec is safe. Also, if the entry is guarded by a comparison
980 // with the start value and the backedge is guarded by a comparison
981 // with the post-inc value, the addrec is safe.
982 if (isKnownPositive(Step)) {
983 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
984 getSignedRange(Step).getSignedMax());
985 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000986 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000987 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
988 AR->getPostIncExpr(*this), N)))
989 // Return the expression with the addrec on the outside.
990 return getAddRecExpr(getSignExtendExpr(Start, Ty),
991 getSignExtendExpr(Step, Ty),
992 L);
993 } else if (isKnownNegative(Step)) {
994 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
995 getSignedRange(Step).getSignedMin());
996 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000997 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000998 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
999 AR->getPostIncExpr(*this), N)))
1000 // Return the expression with the addrec on the outside.
1001 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1002 getSignExtendExpr(Step, Ty),
1003 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001004 }
1005 }
1006 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001007
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001008 // The cast wasn't folded; create an explicit cast node.
1009 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001010 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001011 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +00001012 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +00001013 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001014 UniqueSCEVs.InsertNode(S, IP);
1015 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001016}
1017
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001018/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1019/// unspecified bits out to the given type.
1020///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001021const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001022 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001023 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1024 "This is not an extending conversion!");
1025 assert(isSCEVable(Ty) &&
1026 "This is not a conversion to a SCEVable type!");
1027 Ty = getEffectiveSCEVType(Ty);
1028
1029 // Sign-extend negative constants.
1030 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1031 if (SC->getValue()->getValue().isNegative())
1032 return getSignExtendExpr(Op, Ty);
1033
1034 // Peel off a truncate cast.
1035 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001036 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001037 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1038 return getAnyExtendExpr(NewOp, Ty);
1039 return getTruncateOrNoop(NewOp, Ty);
1040 }
1041
1042 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001043 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001044 if (!isa<SCEVZeroExtendExpr>(ZExt))
1045 return ZExt;
1046
1047 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001048 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001049 if (!isa<SCEVSignExtendExpr>(SExt))
1050 return SExt;
1051
Dan Gohmana10756e2010-01-21 02:09:26 +00001052 // Force the cast to be folded into the operands of an addrec.
1053 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1054 SmallVector<const SCEV *, 4> Ops;
1055 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1056 I != E; ++I)
1057 Ops.push_back(getAnyExtendExpr(*I, Ty));
1058 return getAddRecExpr(Ops, AR->getLoop());
1059 }
1060
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001061 // If the expression is obviously signed, use the sext cast value.
1062 if (isa<SCEVSMaxExpr>(Op))
1063 return SExt;
1064
1065 // Absent any other information, use the zext cast value.
1066 return ZExt;
1067}
1068
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001069/// CollectAddOperandsWithScales - Process the given Ops list, which is
1070/// a list of operands to be added under the given scale, update the given
1071/// map. This is a helper function for getAddRecExpr. As an example of
1072/// what it does, given a sequence of operands that would form an add
1073/// expression like this:
1074///
1075/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1076///
1077/// where A and B are constants, update the map with these values:
1078///
1079/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1080///
1081/// and add 13 + A*B*29 to AccumulatedConstant.
1082/// This will allow getAddRecExpr to produce this:
1083///
1084/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1085///
1086/// This form often exposes folding opportunities that are hidden in
1087/// the original operand list.
1088///
1089/// Return true iff it appears that any interesting folding opportunities
1090/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1091/// the common case where no interesting opportunities are present, and
1092/// is also used as a check to avoid infinite recursion.
1093///
1094static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001095CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1096 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001097 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001098 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001099 const APInt &Scale,
1100 ScalarEvolution &SE) {
1101 bool Interesting = false;
1102
Dan Gohman5e5dd682010-06-07 19:20:57 +00001103 // Iterate over the add operands. They are sorted, with constants first.
1104 unsigned i = 0;
1105 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1106 ++i;
1107 // Pull a buried constant out to the outside.
1108 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1109 Interesting = true;
1110 AccumulatedConstant += Scale * C->getValue()->getValue();
1111 }
1112
1113 // Next comes everything else. We're especially interested in multiplies
1114 // here, but they're in the middle, so just visit the rest with one loop.
1115 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001116 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1117 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1118 APInt NewScale =
1119 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1120 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1121 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001122 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001123 Interesting |=
1124 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001125 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001126 NewScale, SE);
1127 } else {
1128 // A multiplication of a constant with some other value. Update
1129 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001130 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1131 const SCEV *Key = SE.getMulExpr(MulOps);
1132 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001133 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001134 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001135 NewOps.push_back(Pair.first->first);
1136 } else {
1137 Pair.first->second += NewScale;
1138 // The map already had an entry for this value, which may indicate
1139 // a folding opportunity.
1140 Interesting = true;
1141 }
1142 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001143 } else {
1144 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001145 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001146 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001147 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001148 NewOps.push_back(Pair.first->first);
1149 } else {
1150 Pair.first->second += Scale;
1151 // The map already had an entry for this value, which may indicate
1152 // a folding opportunity.
1153 Interesting = true;
1154 }
1155 }
1156 }
1157
1158 return Interesting;
1159}
1160
1161namespace {
1162 struct APIntCompare {
1163 bool operator()(const APInt &LHS, const APInt &RHS) const {
1164 return LHS.ult(RHS);
1165 }
1166 };
1167}
1168
Dan Gohman6c0866c2009-05-24 23:45:28 +00001169/// getAddExpr - Get a canonical add expression, or something simpler if
1170/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001171const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1172 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001173 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001174 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001175#ifndef NDEBUG
Dan Gohman1f23d632010-06-07 19:16:37 +00001176 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001177 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman1f23d632010-06-07 19:16:37 +00001178 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001179 "SCEVAddExpr operand types don't match!");
1180#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001181
Dan Gohmana10756e2010-01-21 02:09:26 +00001182 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1183 if (!HasNUW && HasNSW) {
1184 bool All = true;
1185 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1186 if (!isKnownNonNegative(Ops[i])) {
1187 All = false;
1188 break;
1189 }
1190 if (All) HasNUW = true;
1191 }
1192
Chris Lattner53e677a2004-04-02 20:23:17 +00001193 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001194 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001195
1196 // If there are any constants, fold them together.
1197 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001198 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001199 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001200 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001201 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001202 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001203 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1204 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001205 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001206 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001207 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001208 }
1209
1210 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001211 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001212 Ops.erase(Ops.begin());
1213 --Idx;
1214 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001215
Dan Gohmanbca091d2010-04-12 23:08:18 +00001216 if (Ops.size() == 1) return Ops[0];
1217 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001218
Chris Lattner53e677a2004-04-02 20:23:17 +00001219 // Okay, check to see if the same value occurs in the operand list twice. If
1220 // so, merge them together into an multiply expression. Since we sorted the
1221 // list, these values are required to be adjacent.
1222 const Type *Ty = Ops[0]->getType();
1223 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1224 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1225 // Found a match, merge the two values into a multiply, and add any
1226 // remaining values to the result.
Dan Gohmandeff6212010-05-03 22:09:21 +00001227 const SCEV *Two = getConstant(Ty, 2);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001228 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001229 if (Ops.size() == 2)
1230 return Mul;
1231 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1232 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001233 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001234 }
1235
Dan Gohman728c7f32009-05-08 21:03:19 +00001236 // Check for truncates. If all the operands are truncated from the same
1237 // type, see if factoring out the truncate would permit the result to be
1238 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1239 // if the contents of the resulting outer trunc fold to something simple.
1240 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1241 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1242 const Type *DstType = Trunc->getType();
1243 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001244 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001245 bool Ok = true;
1246 // Check all the operands to see if they can be represented in the
1247 // source type of the truncate.
1248 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1249 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1250 if (T->getOperand()->getType() != SrcType) {
1251 Ok = false;
1252 break;
1253 }
1254 LargeOps.push_back(T->getOperand());
1255 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001256 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001257 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001258 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001259 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1260 if (const SCEVTruncateExpr *T =
1261 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1262 if (T->getOperand()->getType() != SrcType) {
1263 Ok = false;
1264 break;
1265 }
1266 LargeMulOps.push_back(T->getOperand());
1267 } else if (const SCEVConstant *C =
1268 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001269 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001270 } else {
1271 Ok = false;
1272 break;
1273 }
1274 }
1275 if (Ok)
1276 LargeOps.push_back(getMulExpr(LargeMulOps));
1277 } else {
1278 Ok = false;
1279 break;
1280 }
1281 }
1282 if (Ok) {
1283 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001284 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001285 // If it folds to something simple, use it. Otherwise, don't.
1286 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1287 return getTruncateExpr(Fold, DstType);
1288 }
1289 }
1290
1291 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001292 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1293 ++Idx;
1294
1295 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001296 if (Idx < Ops.size()) {
1297 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001298 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001299 // If we have an add, expand the add operands onto the end of the operands
1300 // list.
1301 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1302 Ops.erase(Ops.begin()+Idx);
1303 DeletedAdd = true;
1304 }
1305
1306 // If we deleted at least one add, we added operands to the end of the list,
1307 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001308 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001309 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001310 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001311 }
1312
1313 // Skip over the add expression until we get to a multiply.
1314 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1315 ++Idx;
1316
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001317 // Check to see if there are any folding opportunities present with
1318 // operands multiplied by constant values.
1319 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1320 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001321 DenseMap<const SCEV *, APInt> M;
1322 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001323 APInt AccumulatedConstant(BitWidth, 0);
1324 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001325 Ops.data(), Ops.size(),
1326 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001327 // Some interesting folding opportunity is present, so its worthwhile to
1328 // re-generate the operands list. Group the operands by constant scale,
1329 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001330 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1331 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001332 E = NewOps.end(); I != E; ++I)
1333 MulOpLists[M.find(*I)->second].push_back(*I);
1334 // Re-generate the operands list.
1335 Ops.clear();
1336 if (AccumulatedConstant != 0)
1337 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001338 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1339 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001340 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001341 Ops.push_back(getMulExpr(getConstant(I->first),
1342 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001343 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001344 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001345 if (Ops.size() == 1)
1346 return Ops[0];
1347 return getAddExpr(Ops);
1348 }
1349 }
1350
Chris Lattner53e677a2004-04-02 20:23:17 +00001351 // If we are adding something to a multiply expression, make sure the
1352 // something is not already an operand of the multiply. If so, merge it into
1353 // the multiply.
1354 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001355 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001356 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001357 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001358 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001359 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001361 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001362 if (Mul->getNumOperands() != 2) {
1363 // If the multiply has more than two operands, we must get the
1364 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001365 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001366 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001367 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001368 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001369 const SCEV *One = getConstant(Ty, 1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001370 const SCEV *AddOne = getAddExpr(InnerMul, One);
1371 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001372 if (Ops.size() == 2) return OuterMul;
1373 if (AddOp < Idx) {
1374 Ops.erase(Ops.begin()+AddOp);
1375 Ops.erase(Ops.begin()+Idx-1);
1376 } else {
1377 Ops.erase(Ops.begin()+Idx);
1378 Ops.erase(Ops.begin()+AddOp-1);
1379 }
1380 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001381 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001382 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001383
Chris Lattner53e677a2004-04-02 20:23:17 +00001384 // Check this multiply against other multiplies being added together.
1385 for (unsigned OtherMulIdx = Idx+1;
1386 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1387 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001388 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001389 // If MulOp occurs in OtherMul, we can fold the two multiplies
1390 // together.
1391 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1392 OMulOp != e; ++OMulOp)
1393 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1394 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001395 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001397 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1398 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001399 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001400 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001402 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001403 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001404 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1405 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001406 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001407 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001408 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001409 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1410 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001411 if (Ops.size() == 2) return OuterMul;
1412 Ops.erase(Ops.begin()+Idx);
1413 Ops.erase(Ops.begin()+OtherMulIdx-1);
1414 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001415 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001416 }
1417 }
1418 }
1419 }
1420
1421 // If there are any add recurrences in the operands list, see if any other
1422 // added values are loop invariant. If so, we can fold them into the
1423 // recurrence.
1424 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1425 ++Idx;
1426
1427 // Scan over all recurrences, trying to fold loop invariants into them.
1428 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1429 // Scan all of the other operands to this add and add them to the vector if
1430 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001431 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001432 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001433 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001434 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanbca091d2010-04-12 23:08:18 +00001435 if (Ops[i]->isLoopInvariant(AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001436 LIOps.push_back(Ops[i]);
1437 Ops.erase(Ops.begin()+i);
1438 --i; --e;
1439 }
1440
1441 // If we found some loop invariants, fold them into the recurrence.
1442 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001443 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001444 LIOps.push_back(AddRec->getStart());
1445
Dan Gohman0bba49c2009-07-07 17:06:11 +00001446 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001447 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001448 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001449
Dan Gohman355b4f32009-12-19 01:46:34 +00001450 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001451 // is not associative so this isn't necessarily safe.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001452 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop);
Dan Gohman59de33e2009-12-18 18:45:31 +00001453
Chris Lattner53e677a2004-04-02 20:23:17 +00001454 // If all of the other operands were loop invariant, we are done.
1455 if (Ops.size() == 1) return NewRec;
1456
1457 // Otherwise, add the folded AddRec by the non-liv parts.
1458 for (unsigned i = 0;; ++i)
1459 if (Ops[i] == AddRec) {
1460 Ops[i] = NewRec;
1461 break;
1462 }
Dan Gohman246b2562007-10-22 18:31:58 +00001463 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001464 }
1465
1466 // Okay, if there weren't any loop invariants to be folded, check to see if
1467 // there are multiple AddRec's with the same loop induction variable being
1468 // added together. If so, we can fold them.
1469 for (unsigned OtherIdx = Idx+1;
1470 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1471 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001472 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001473 if (AddRecLoop == OtherAddRec->getLoop()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001475 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1476 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1478 if (i >= NewOps.size()) {
1479 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1480 OtherAddRec->op_end());
1481 break;
1482 }
Dan Gohman246b2562007-10-22 18:31:58 +00001483 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001484 }
Dan Gohmanbca091d2010-04-12 23:08:18 +00001485 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRecLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +00001486
1487 if (Ops.size() == 2) return NewAddRec;
1488
1489 Ops.erase(Ops.begin()+Idx);
1490 Ops.erase(Ops.begin()+OtherIdx-1);
1491 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001492 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 }
1494 }
1495
1496 // Otherwise couldn't fold anything into this recurrence. Move onto the
1497 // next one.
1498 }
1499
1500 // Okay, it looks like we really DO need an add expr. Check to see if we
1501 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001502 FoldingSetNodeID ID;
1503 ID.AddInteger(scAddExpr);
1504 ID.AddInteger(Ops.size());
1505 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1506 ID.AddPointer(Ops[i]);
1507 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001508 SCEVAddExpr *S =
1509 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1510 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001511 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1512 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001513 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +00001514 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +00001515 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001516 UniqueSCEVs.InsertNode(S, IP);
1517 }
Dan Gohman3645b012009-10-09 00:10:36 +00001518 if (HasNUW) S->setHasNoUnsignedWrap(true);
1519 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001520 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001521}
1522
Dan Gohman6c0866c2009-05-24 23:45:28 +00001523/// getMulExpr - Get a canonical multiply expression, or something simpler if
1524/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001525const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1526 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001527 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001528 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001529#ifndef NDEBUG
1530 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1531 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1532 getEffectiveSCEVType(Ops[0]->getType()) &&
1533 "SCEVMulExpr operand types don't match!");
1534#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001535
Dan Gohmana10756e2010-01-21 02:09:26 +00001536 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1537 if (!HasNUW && HasNSW) {
1538 bool All = true;
1539 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1540 if (!isKnownNonNegative(Ops[i])) {
1541 All = false;
1542 break;
1543 }
1544 if (All) HasNUW = true;
1545 }
1546
Chris Lattner53e677a2004-04-02 20:23:17 +00001547 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001548 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001549
1550 // If there are any constants, fold them together.
1551 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001552 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001553
1554 // C1*(C2+V) -> C1*C2 + C1*V
1555 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001556 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001557 if (Add->getNumOperands() == 2 &&
1558 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001559 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1560 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001561
Chris Lattner53e677a2004-04-02 20:23:17 +00001562 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001563 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001564 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001565 ConstantInt *Fold = ConstantInt::get(getContext(),
1566 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001567 RHSC->getValue()->getValue());
1568 Ops[0] = getConstant(Fold);
1569 Ops.erase(Ops.begin()+1); // Erase the folded element
1570 if (Ops.size() == 1) return Ops[0];
1571 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001572 }
1573
1574 // If we are left with a constant one being multiplied, strip it off.
1575 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1576 Ops.erase(Ops.begin());
1577 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001578 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001579 // If we have a multiply of zero, it will always be zero.
1580 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001581 } else if (Ops[0]->isAllOnesValue()) {
1582 // If we have a mul by -1 of an add, try distributing the -1 among the
1583 // add operands.
1584 if (Ops.size() == 2)
1585 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1586 SmallVector<const SCEV *, 4> NewOps;
1587 bool AnyFolded = false;
1588 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1589 I != E; ++I) {
1590 const SCEV *Mul = getMulExpr(Ops[0], *I);
1591 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1592 NewOps.push_back(Mul);
1593 }
1594 if (AnyFolded)
1595 return getAddExpr(NewOps);
1596 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001597 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001598
1599 if (Ops.size() == 1)
1600 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001601 }
1602
1603 // Skip over the add expression until we get to a multiply.
1604 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1605 ++Idx;
1606
Chris Lattner53e677a2004-04-02 20:23:17 +00001607 // If there are mul operands inline them all into this expression.
1608 if (Idx < Ops.size()) {
1609 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001610 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001611 // If we have an mul, expand the mul operands onto the end of the operands
1612 // list.
1613 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1614 Ops.erase(Ops.begin()+Idx);
1615 DeletedMul = true;
1616 }
1617
1618 // If we deleted at least one mul, we added operands to the end of the list,
1619 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001620 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001621 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001622 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001623 }
1624
1625 // If there are any add recurrences in the operands list, see if any other
1626 // added values are loop invariant. If so, we can fold them into the
1627 // recurrence.
1628 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1629 ++Idx;
1630
1631 // Scan over all recurrences, trying to fold loop invariants into them.
1632 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1633 // Scan all of the other operands to this mul and add them to the vector if
1634 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001635 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001636 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001637 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1638 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1639 LIOps.push_back(Ops[i]);
1640 Ops.erase(Ops.begin()+i);
1641 --i; --e;
1642 }
1643
1644 // If we found some loop invariants, fold them into the recurrence.
1645 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001646 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001647 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001648 NewOps.reserve(AddRec->getNumOperands());
1649 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001650 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001651 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001652 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 } else {
1654 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001655 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001656 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001657 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001658 }
1659 }
1660
Dan Gohman355b4f32009-12-19 01:46:34 +00001661 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001662 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001663 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1664 HasNUW && AddRec->hasNoUnsignedWrap(),
1665 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001666
1667 // If all of the other operands were loop invariant, we are done.
1668 if (Ops.size() == 1) return NewRec;
1669
1670 // Otherwise, multiply the folded AddRec by the non-liv parts.
1671 for (unsigned i = 0;; ++i)
1672 if (Ops[i] == AddRec) {
1673 Ops[i] = NewRec;
1674 break;
1675 }
Dan Gohman246b2562007-10-22 18:31:58 +00001676 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001677 }
1678
1679 // Okay, if there weren't any loop invariants to be folded, check to see if
1680 // there are multiple AddRec's with the same loop induction variable being
1681 // multiplied together. If so, we can fold them.
1682 for (unsigned OtherIdx = Idx+1;
1683 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1684 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001685 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001686 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1687 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001688 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001689 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001690 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001691 const SCEV *B = F->getStepRecurrence(*this);
1692 const SCEV *D = G->getStepRecurrence(*this);
1693 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001694 getMulExpr(G, B),
1695 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001696 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001697 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001698 if (Ops.size() == 2) return NewAddRec;
1699
1700 Ops.erase(Ops.begin()+Idx);
1701 Ops.erase(Ops.begin()+OtherIdx-1);
1702 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001703 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001704 }
1705 }
1706
1707 // Otherwise couldn't fold anything into this recurrence. Move onto the
1708 // next one.
1709 }
1710
1711 // Okay, it looks like we really DO need an mul expr. Check to see if we
1712 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001713 FoldingSetNodeID ID;
1714 ID.AddInteger(scMulExpr);
1715 ID.AddInteger(Ops.size());
1716 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1717 ID.AddPointer(Ops[i]);
1718 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001719 SCEVMulExpr *S =
1720 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1721 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001722 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1723 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001724 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +00001725 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +00001726 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001727 UniqueSCEVs.InsertNode(S, IP);
1728 }
Dan Gohman3645b012009-10-09 00:10:36 +00001729 if (HasNUW) S->setHasNoUnsignedWrap(true);
1730 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001731 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001732}
1733
Andreas Bolka8a11c982009-08-07 22:55:26 +00001734/// getUDivExpr - Get a canonical unsigned division expression, or something
1735/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001736const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1737 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001738 assert(getEffectiveSCEVType(LHS->getType()) ==
1739 getEffectiveSCEVType(RHS->getType()) &&
1740 "SCEVUDivExpr operand types don't match!");
1741
Dan Gohman622ed672009-05-04 22:02:23 +00001742 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001743 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001744 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001745 // If the denominator is zero, the result of the udiv is undefined. Don't
1746 // try to analyze it, because the resolution chosen here may differ from
1747 // the resolution chosen in other parts of the compiler.
1748 if (!RHSC->getValue()->isZero()) {
1749 // Determine if the division can be folded into the operands of
1750 // its operands.
1751 // TODO: Generalize this to non-constants by using known-bits information.
1752 const Type *Ty = LHS->getType();
1753 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1754 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1755 // For non-power-of-two values, effectively round the value up to the
1756 // nearest power of two.
1757 if (!RHSC->getValue()->getValue().isPowerOf2())
1758 ++MaxShiftAmt;
1759 const IntegerType *ExtTy =
1760 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1761 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1762 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1763 if (const SCEVConstant *Step =
1764 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1765 if (!Step->getValue()->getValue()
1766 .urem(RHSC->getValue()->getValue()) &&
1767 getZeroExtendExpr(AR, ExtTy) ==
1768 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1769 getZeroExtendExpr(Step, ExtTy),
1770 AR->getLoop())) {
1771 SmallVector<const SCEV *, 4> Operands;
1772 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1773 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1774 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001775 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001776 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1777 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1778 SmallVector<const SCEV *, 4> Operands;
1779 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1780 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1781 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1782 // Find an operand that's safely divisible.
1783 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1784 const SCEV *Op = M->getOperand(i);
1785 const SCEV *Div = getUDivExpr(Op, RHSC);
1786 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1787 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1788 M->op_end());
1789 Operands[i] = Div;
1790 return getMulExpr(Operands);
1791 }
1792 }
Dan Gohman185cf032009-05-08 20:18:49 +00001793 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001794 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1795 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1796 SmallVector<const SCEV *, 4> Operands;
1797 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1798 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1799 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1800 Operands.clear();
1801 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1802 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1803 if (isa<SCEVUDivExpr>(Op) ||
1804 getMulExpr(Op, RHS) != A->getOperand(i))
1805 break;
1806 Operands.push_back(Op);
1807 }
1808 if (Operands.size() == A->getNumOperands())
1809 return getAddExpr(Operands);
1810 }
1811 }
Dan Gohman185cf032009-05-08 20:18:49 +00001812
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001813 // Fold if both operands are constant.
1814 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1815 Constant *LHSCV = LHSC->getValue();
1816 Constant *RHSCV = RHSC->getValue();
1817 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1818 RHSCV)));
1819 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001820 }
1821 }
1822
Dan Gohman1c343752009-06-27 21:21:31 +00001823 FoldingSetNodeID ID;
1824 ID.AddInteger(scUDivExpr);
1825 ID.AddPointer(LHS);
1826 ID.AddPointer(RHS);
1827 void *IP = 0;
1828 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001829 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +00001830 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +00001831 LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001832 UniqueSCEVs.InsertNode(S, IP);
1833 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001834}
1835
1836
Dan Gohman6c0866c2009-05-24 23:45:28 +00001837/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1838/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001839const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001840 const SCEV *Step, const Loop *L,
1841 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001842 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001843 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001844 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001845 if (StepChrec->getLoop() == L) {
1846 Operands.insert(Operands.end(), StepChrec->op_begin(),
1847 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001848 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001849 }
1850
1851 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001852 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001853}
1854
Dan Gohman6c0866c2009-05-24 23:45:28 +00001855/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1856/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001857const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001858ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001859 const Loop *L,
1860 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001861 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001862#ifndef NDEBUG
1863 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1864 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1865 getEffectiveSCEVType(Operands[0]->getType()) &&
1866 "SCEVAddRecExpr operand types don't match!");
1867#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001868
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001869 if (Operands.back()->isZero()) {
1870 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001871 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001872 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001873
Dan Gohmanbc028532010-02-19 18:49:22 +00001874 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1875 // use that information to infer NUW and NSW flags. However, computing a
1876 // BE count requires calling getAddRecExpr, so we may not yet have a
1877 // meaningful BE count at this point (and if we don't, we'd be stuck
1878 // with a SCEVCouldNotCompute as the cached BE count).
1879
Dan Gohmana10756e2010-01-21 02:09:26 +00001880 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1881 if (!HasNUW && HasNSW) {
1882 bool All = true;
1883 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1884 if (!isKnownNonNegative(Operands[i])) {
1885 All = false;
1886 break;
1887 }
1888 if (All) HasNUW = true;
1889 }
1890
Dan Gohmand9cc7492008-08-08 18:33:12 +00001891 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001892 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001893 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001894 if (L->contains(NestedLoop->getHeader()) ?
1895 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1896 (!NestedLoop->contains(L->getHeader()) &&
1897 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001898 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001899 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001900 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001901 // AddRecs require their operands be loop-invariant with respect to their
1902 // loops. Don't perform this transformation if it would break this
1903 // requirement.
1904 bool AllInvariant = true;
1905 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1906 if (!Operands[i]->isLoopInvariant(L)) {
1907 AllInvariant = false;
1908 break;
1909 }
1910 if (AllInvariant) {
1911 NestedOperands[0] = getAddRecExpr(Operands, L);
1912 AllInvariant = true;
1913 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1914 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1915 AllInvariant = false;
1916 break;
1917 }
1918 if (AllInvariant)
1919 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00001920 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00001921 }
1922 // Reset Operands to its original state.
1923 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001924 }
1925 }
1926
Dan Gohman67847532010-01-19 22:27:22 +00001927 // Okay, it looks like we really DO need an addrec expr. Check to see if we
1928 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001929 FoldingSetNodeID ID;
1930 ID.AddInteger(scAddRecExpr);
1931 ID.AddInteger(Operands.size());
1932 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1933 ID.AddPointer(Operands[i]);
1934 ID.AddPointer(L);
1935 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001936 SCEVAddRecExpr *S =
1937 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1938 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001939 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
1940 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001941 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +00001942 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +00001943 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00001944 UniqueSCEVs.InsertNode(S, IP);
1945 }
Dan Gohman3645b012009-10-09 00:10:36 +00001946 if (HasNUW) S->setHasNoUnsignedWrap(true);
1947 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001948 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001949}
1950
Dan Gohman9311ef62009-06-24 14:49:00 +00001951const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1952 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001953 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001954 Ops.push_back(LHS);
1955 Ops.push_back(RHS);
1956 return getSMaxExpr(Ops);
1957}
1958
Dan Gohman0bba49c2009-07-07 17:06:11 +00001959const SCEV *
1960ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001961 assert(!Ops.empty() && "Cannot get empty smax!");
1962 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001963#ifndef NDEBUG
1964 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1965 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1966 getEffectiveSCEVType(Ops[0]->getType()) &&
1967 "SCEVSMaxExpr operand types don't match!");
1968#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001969
1970 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001971 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001972
1973 // If there are any constants, fold them together.
1974 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001975 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001976 ++Idx;
1977 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001978 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001979 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001980 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001981 APIntOps::smax(LHSC->getValue()->getValue(),
1982 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001983 Ops[0] = getConstant(Fold);
1984 Ops.erase(Ops.begin()+1); // Erase the folded element
1985 if (Ops.size() == 1) return Ops[0];
1986 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001987 }
1988
Dan Gohmane5aceed2009-06-24 14:46:22 +00001989 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001990 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1991 Ops.erase(Ops.begin());
1992 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001993 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1994 // If we have an smax with a constant maximum-int, it will always be
1995 // maximum-int.
1996 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001997 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001998
Dan Gohman3ab13122010-04-13 16:49:23 +00001999 if (Ops.size() == 1) return Ops[0];
2000 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002001
2002 // Find the first SMax
2003 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2004 ++Idx;
2005
2006 // Check to see if one of the operands is an SMax. If so, expand its operands
2007 // onto our operand list, and recurse to simplify.
2008 if (Idx < Ops.size()) {
2009 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002010 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002011 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2012 Ops.erase(Ops.begin()+Idx);
2013 DeletedSMax = true;
2014 }
2015
2016 if (DeletedSMax)
2017 return getSMaxExpr(Ops);
2018 }
2019
2020 // Okay, check to see if the same value occurs in the operand list twice. If
2021 // so, delete one. Since we sorted the list, these values are required to
2022 // be adjacent.
2023 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002024 // X smax Y smax Y --> X smax Y
2025 // X smax Y --> X, if X is always greater than Y
2026 if (Ops[i] == Ops[i+1] ||
2027 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2028 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2029 --i; --e;
2030 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002031 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2032 --i; --e;
2033 }
2034
2035 if (Ops.size() == 1) return Ops[0];
2036
2037 assert(!Ops.empty() && "Reduced smax down to nothing!");
2038
Nick Lewycky3e630762008-02-20 06:48:22 +00002039 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002040 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002041 FoldingSetNodeID ID;
2042 ID.AddInteger(scSMaxExpr);
2043 ID.AddInteger(Ops.size());
2044 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2045 ID.AddPointer(Ops[i]);
2046 void *IP = 0;
2047 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002048 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2049 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002050 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +00002051 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +00002052 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002053 UniqueSCEVs.InsertNode(S, IP);
2054 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002055}
2056
Dan Gohman9311ef62009-06-24 14:49:00 +00002057const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2058 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002059 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002060 Ops.push_back(LHS);
2061 Ops.push_back(RHS);
2062 return getUMaxExpr(Ops);
2063}
2064
Dan Gohman0bba49c2009-07-07 17:06:11 +00002065const SCEV *
2066ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002067 assert(!Ops.empty() && "Cannot get empty umax!");
2068 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002069#ifndef NDEBUG
2070 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2071 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2072 getEffectiveSCEVType(Ops[0]->getType()) &&
2073 "SCEVUMaxExpr operand types don't match!");
2074#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002075
2076 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002077 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002078
2079 // If there are any constants, fold them together.
2080 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002081 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002082 ++Idx;
2083 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002084 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002085 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002086 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002087 APIntOps::umax(LHSC->getValue()->getValue(),
2088 RHSC->getValue()->getValue()));
2089 Ops[0] = getConstant(Fold);
2090 Ops.erase(Ops.begin()+1); // Erase the folded element
2091 if (Ops.size() == 1) return Ops[0];
2092 LHSC = cast<SCEVConstant>(Ops[0]);
2093 }
2094
Dan Gohmane5aceed2009-06-24 14:46:22 +00002095 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002096 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2097 Ops.erase(Ops.begin());
2098 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002099 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2100 // If we have an umax with a constant maximum-int, it will always be
2101 // maximum-int.
2102 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002103 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002104
Dan Gohman3ab13122010-04-13 16:49:23 +00002105 if (Ops.size() == 1) return Ops[0];
2106 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002107
2108 // Find the first UMax
2109 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2110 ++Idx;
2111
2112 // Check to see if one of the operands is a UMax. If so, expand its operands
2113 // onto our operand list, and recurse to simplify.
2114 if (Idx < Ops.size()) {
2115 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002116 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002117 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2118 Ops.erase(Ops.begin()+Idx);
2119 DeletedUMax = true;
2120 }
2121
2122 if (DeletedUMax)
2123 return getUMaxExpr(Ops);
2124 }
2125
2126 // Okay, check to see if the same value occurs in the operand list twice. If
2127 // so, delete one. Since we sorted the list, these values are required to
2128 // be adjacent.
2129 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002130 // X umax Y umax Y --> X umax Y
2131 // X umax Y --> X, if X is always greater than Y
2132 if (Ops[i] == Ops[i+1] ||
2133 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2134 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2135 --i; --e;
2136 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002137 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2138 --i; --e;
2139 }
2140
2141 if (Ops.size() == 1) return Ops[0];
2142
2143 assert(!Ops.empty() && "Reduced umax down to nothing!");
2144
2145 // Okay, it looks like we really DO need a umax expr. Check to see if we
2146 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002147 FoldingSetNodeID ID;
2148 ID.AddInteger(scUMaxExpr);
2149 ID.AddInteger(Ops.size());
2150 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2151 ID.AddPointer(Ops[i]);
2152 void *IP = 0;
2153 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002154 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2155 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002156 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
Dan Gohmanfd447ef2010-06-07 19:36:14 +00002157 CurAllocationSequenceNumber++,
Dan Gohman95531882010-03-18 18:49:47 +00002158 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002159 UniqueSCEVs.InsertNode(S, IP);
2160 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002161}
2162
Dan Gohman9311ef62009-06-24 14:49:00 +00002163const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2164 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002165 // ~smax(~x, ~y) == smin(x, y).
2166 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2167}
2168
Dan Gohman9311ef62009-06-24 14:49:00 +00002169const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2170 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002171 // ~umax(~x, ~y) == umin(x, y)
2172 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2173}
2174
Dan Gohman4f8eea82010-02-01 18:27:38 +00002175const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002176 // If we have TargetData, we can bypass creating a target-independent
2177 // constant expression and then folding it back into a ConstantInt.
2178 // This is just a compile-time optimization.
2179 if (TD)
2180 return getConstant(TD->getIntPtrType(getContext()),
2181 TD->getTypeAllocSize(AllocTy));
2182
Dan Gohman4f8eea82010-02-01 18:27:38 +00002183 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2184 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002185 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2186 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002187 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2188 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2189}
2190
2191const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2192 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2193 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002194 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2195 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002196 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2197 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2198}
2199
2200const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2201 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002202 // If we have TargetData, we can bypass creating a target-independent
2203 // constant expression and then folding it back into a ConstantInt.
2204 // This is just a compile-time optimization.
2205 if (TD)
2206 return getConstant(TD->getIntPtrType(getContext()),
2207 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2208
Dan Gohman0f5efe52010-01-28 02:15:55 +00002209 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2210 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002211 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2212 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002213 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002214 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002215}
2216
Dan Gohman4f8eea82010-02-01 18:27:38 +00002217const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2218 Constant *FieldNo) {
2219 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002220 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002221 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2222 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002223 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002224 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002225}
2226
Dan Gohman0bba49c2009-07-07 17:06:11 +00002227const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002228 // Don't attempt to do anything other than create a SCEVUnknown object
2229 // here. createSCEV only calls getUnknown after checking for all other
2230 // interesting possibilities, and any other code that calls getUnknown
2231 // is doing so in order to hide a value from SCEV canonicalization.
2232
Dan Gohman1c343752009-06-27 21:21:31 +00002233 FoldingSetNodeID ID;
2234 ID.AddInteger(scUnknown);
2235 ID.AddPointer(V);
2236 void *IP = 0;
2237 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanfd447ef2010-06-07 19:36:14 +00002238 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator),
2239 CurAllocationSequenceNumber++,
2240 V);
Dan Gohman1c343752009-06-27 21:21:31 +00002241 UniqueSCEVs.InsertNode(S, IP);
2242 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002243}
2244
Chris Lattner53e677a2004-04-02 20:23:17 +00002245//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002246// Basic SCEV Analysis and PHI Idiom Recognition Code
2247//
2248
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002249/// isSCEVable - Test if values of the given type are analyzable within
2250/// the SCEV framework. This primarily includes integer types, and it
2251/// can optionally include pointer types if the ScalarEvolution class
2252/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002253bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002254 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002255 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002256}
2257
2258/// getTypeSizeInBits - Return the size in bits of the specified type,
2259/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002260uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002261 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2262
2263 // If we have a TargetData, use it!
2264 if (TD)
2265 return TD->getTypeSizeInBits(Ty);
2266
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002267 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002268 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002269 return Ty->getPrimitiveSizeInBits();
2270
2271 // The only other support type is pointer. Without TargetData, conservatively
2272 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002273 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002274 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002275}
2276
2277/// getEffectiveSCEVType - Return a type with the same bitwidth as
2278/// the given type and which represents how SCEV will treat the given
2279/// type, for which isSCEVable must return true. For pointer types,
2280/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002281const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002282 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2283
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002284 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002285 return Ty;
2286
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002287 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002288 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002289 if (TD) return TD->getIntPtrType(getContext());
2290
2291 // Without TargetData, conservatively assume pointers are 64-bit.
2292 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002293}
Chris Lattner53e677a2004-04-02 20:23:17 +00002294
Dan Gohman0bba49c2009-07-07 17:06:11 +00002295const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002296 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002297}
2298
Chris Lattner53e677a2004-04-02 20:23:17 +00002299/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2300/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002301const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002302 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002303
Dan Gohman0bba49c2009-07-07 17:06:11 +00002304 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002305 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002306 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002307 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002308 return S;
2309}
2310
Dan Gohman6bbcba12009-06-24 00:54:57 +00002311/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002312/// specified signed integer value and return a SCEV for the constant.
Dan Gohman32efba62010-02-04 02:43:51 +00002313const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002314 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002315 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002316}
2317
2318/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2319///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002320const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002321 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002322 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002323 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002324
2325 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002326 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002327 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002328 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002329}
2330
2331/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002332const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002333 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002334 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002335 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002336
2337 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002338 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002339 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002340 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002341 return getMinusSCEV(AllOnes, V);
2342}
2343
2344/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2345///
Dan Gohman9311ef62009-06-24 14:49:00 +00002346const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2347 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002348 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002349 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002350}
2351
2352/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2353/// input value to the specified type. If the type must be extended, it is zero
2354/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002355const SCEV *
2356ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002357 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002358 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002359 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2360 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002361 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002362 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002363 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002364 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002365 return getTruncateExpr(V, Ty);
2366 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002367}
2368
2369/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2370/// input value to the specified type. If the type must be extended, it is sign
2371/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002372const SCEV *
2373ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002374 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002375 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002376 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2377 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002378 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002379 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002380 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002381 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002382 return getTruncateExpr(V, Ty);
2383 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002384}
2385
Dan Gohman467c4302009-05-13 03:46:30 +00002386/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2387/// input value to the specified type. If the type must be extended, it is zero
2388/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002389const SCEV *
2390ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002391 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002392 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2393 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002394 "Cannot noop or zero extend with non-integer arguments!");
2395 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2396 "getNoopOrZeroExtend cannot truncate!");
2397 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2398 return V; // No conversion
2399 return getZeroExtendExpr(V, Ty);
2400}
2401
2402/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2403/// input value to the specified type. If the type must be extended, it is sign
2404/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002405const SCEV *
2406ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002407 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002408 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2409 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002410 "Cannot noop or sign extend with non-integer arguments!");
2411 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2412 "getNoopOrSignExtend cannot truncate!");
2413 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2414 return V; // No conversion
2415 return getSignExtendExpr(V, Ty);
2416}
2417
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002418/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2419/// the input value to the specified type. If the type must be extended,
2420/// it is extended with unspecified bits. The conversion must not be
2421/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002422const SCEV *
2423ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002424 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002425 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2426 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002427 "Cannot noop or any extend with non-integer arguments!");
2428 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2429 "getNoopOrAnyExtend cannot truncate!");
2430 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2431 return V; // No conversion
2432 return getAnyExtendExpr(V, Ty);
2433}
2434
Dan Gohman467c4302009-05-13 03:46:30 +00002435/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2436/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002437const SCEV *
2438ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002439 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002440 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2441 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002442 "Cannot truncate or noop with non-integer arguments!");
2443 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2444 "getTruncateOrNoop cannot extend!");
2445 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2446 return V; // No conversion
2447 return getTruncateExpr(V, Ty);
2448}
2449
Dan Gohmana334aa72009-06-22 00:31:57 +00002450/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2451/// the types using zero-extension, and then perform a umax operation
2452/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002453const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2454 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002455 const SCEV *PromotedLHS = LHS;
2456 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002457
2458 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2459 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2460 else
2461 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2462
2463 return getUMaxExpr(PromotedLHS, PromotedRHS);
2464}
2465
Dan Gohmanc9759e82009-06-22 15:03:27 +00002466/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2467/// the types using zero-extension, and then perform a umin operation
2468/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002469const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2470 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002471 const SCEV *PromotedLHS = LHS;
2472 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002473
2474 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2475 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2476 else
2477 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2478
2479 return getUMinExpr(PromotedLHS, PromotedRHS);
2480}
2481
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002482/// PushDefUseChildren - Push users of the given Instruction
2483/// onto the given Worklist.
2484static void
2485PushDefUseChildren(Instruction *I,
2486 SmallVectorImpl<Instruction *> &Worklist) {
2487 // Push the def-use children onto the Worklist stack.
2488 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2489 UI != UE; ++UI)
2490 Worklist.push_back(cast<Instruction>(UI));
2491}
2492
2493/// ForgetSymbolicValue - This looks up computed SCEV values for all
2494/// instructions that depend on the given instruction and removes them from
2495/// the Scalars map if they reference SymName. This is used during PHI
2496/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002497void
Dan Gohman85669632010-02-25 06:57:05 +00002498ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002499 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002500 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002501
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002502 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002503 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002504 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002505 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002506 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002507
Dan Gohman5d984912009-12-18 01:14:11 +00002508 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002509 Scalars.find(static_cast<Value *>(I));
2510 if (It != Scalars.end()) {
2511 // Short-circuit the def-use traversal if the symbolic name
2512 // ceases to appear in expressions.
Dan Gohman50922bb2010-02-15 10:28:37 +00002513 if (It->second != SymName && !It->second->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002514 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002515
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002516 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002517 // structure, it's a PHI that's in the progress of being computed
2518 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2519 // additional loop trip count information isn't going to change anything.
2520 // In the second case, createNodeForPHI will perform the necessary
2521 // updates on its own when it gets to that point. In the third, we do
2522 // want to forget the SCEVUnknown.
2523 if (!isa<PHINode>(I) ||
2524 !isa<SCEVUnknown>(It->second) ||
2525 (I != PN && It->second == SymName)) {
Dan Gohman42214892009-08-31 21:15:23 +00002526 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002527 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002528 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002529 }
2530
2531 PushDefUseChildren(I, Worklist);
2532 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002533}
Chris Lattner53e677a2004-04-02 20:23:17 +00002534
2535/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2536/// a loop header, making it a potential recurrence, or it doesn't.
2537///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002538const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002539 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2540 if (L->getHeader() == PN->getParent()) {
2541 // The loop may have multiple entrances or multiple exits; we can analyze
2542 // this phi as an addrec if it has a unique entry value and a unique
2543 // backedge value.
2544 Value *BEValueV = 0, *StartValueV = 0;
2545 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2546 Value *V = PN->getIncomingValue(i);
2547 if (L->contains(PN->getIncomingBlock(i))) {
2548 if (!BEValueV) {
2549 BEValueV = V;
2550 } else if (BEValueV != V) {
2551 BEValueV = 0;
2552 break;
2553 }
2554 } else if (!StartValueV) {
2555 StartValueV = V;
2556 } else if (StartValueV != V) {
2557 StartValueV = 0;
2558 break;
2559 }
2560 }
2561 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002562 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002563 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002564 assert(Scalars.find(PN) == Scalars.end() &&
2565 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002566 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002567
2568 // Using this symbolic name for the PHI, analyze the value coming around
2569 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002570 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002571
2572 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2573 // has a special value for the first iteration of the loop.
2574
2575 // If the value coming around the backedge is an add with the symbolic
2576 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002577 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002578 // If there is a single occurrence of the symbolic value, replace it
2579 // with a recurrence.
2580 unsigned FoundIndex = Add->getNumOperands();
2581 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2582 if (Add->getOperand(i) == SymbolicName)
2583 if (FoundIndex == e) {
2584 FoundIndex = i;
2585 break;
2586 }
2587
2588 if (FoundIndex != Add->getNumOperands()) {
2589 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002590 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002591 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2592 if (i != FoundIndex)
2593 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002594 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002595
2596 // This is not a valid addrec if the step amount is varying each
2597 // loop iteration, but is not itself an addrec in this loop.
2598 if (Accum->isLoopInvariant(L) ||
2599 (isa<SCEVAddRecExpr>(Accum) &&
2600 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002601 bool HasNUW = false;
2602 bool HasNSW = false;
2603
2604 // If the increment doesn't overflow, then neither the addrec nor
2605 // the post-increment will overflow.
2606 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2607 if (OBO->hasNoUnsignedWrap())
2608 HasNUW = true;
2609 if (OBO->hasNoSignedWrap())
2610 HasNSW = true;
2611 }
2612
Dan Gohman27dead42010-04-12 07:49:36 +00002613 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002614 const SCEV *PHISCEV =
2615 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002616
Dan Gohmana10756e2010-01-21 02:09:26 +00002617 // Since the no-wrap flags are on the increment, they apply to the
2618 // post-incremented value as well.
2619 if (Accum->isLoopInvariant(L))
2620 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2621 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002622
2623 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002624 // to be symbolic. We now need to go back and purge all of the
2625 // entries for the scalars that use the symbolic expression.
2626 ForgetSymbolicName(PN, SymbolicName);
2627 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002628 return PHISCEV;
2629 }
2630 }
Dan Gohman622ed672009-05-04 22:02:23 +00002631 } else if (const SCEVAddRecExpr *AddRec =
2632 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002633 // Otherwise, this could be a loop like this:
2634 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2635 // In this case, j = {1,+,1} and BEValue is j.
2636 // Because the other in-value of i (0) fits the evolution of BEValue
2637 // i really is an addrec evolution.
2638 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002639 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002640
2641 // If StartVal = j.start - j.stride, we can use StartVal as the
2642 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002643 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002644 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002645 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002646 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002647
2648 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002649 // to be symbolic. We now need to go back and purge all of the
2650 // entries for the scalars that use the symbolic expression.
2651 ForgetSymbolicName(PN, SymbolicName);
2652 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002653 return PHISCEV;
2654 }
2655 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002656 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002657 }
Dan Gohman27dead42010-04-12 07:49:36 +00002658 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002659
Dan Gohman85669632010-02-25 06:57:05 +00002660 // If the PHI has a single incoming value, follow that value, unless the
2661 // PHI's incoming blocks are in a different loop, in which case doing so
2662 // risks breaking LCSSA form. Instcombine would normally zap these, but
2663 // it doesn't have DominatorTree information, so it may miss cases.
2664 if (Value *V = PN->hasConstantValue(DT)) {
2665 bool AllSameLoop = true;
2666 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2667 for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2668 if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
2669 AllSameLoop = false;
2670 break;
2671 }
2672 if (AllSameLoop)
2673 return getSCEV(V);
2674 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002675
Chris Lattner53e677a2004-04-02 20:23:17 +00002676 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002677 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002678}
2679
Dan Gohman26466c02009-05-08 20:26:55 +00002680/// createNodeForGEP - Expand GEP instructions into add and multiply
2681/// operations. This allows them to be analyzed by regular SCEV code.
2682///
Dan Gohmand281ed22009-12-18 02:09:29 +00002683const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002684
Dan Gohmand281ed22009-12-18 02:09:29 +00002685 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002686 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002687 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002688 // Don't attempt to analyze GEPs over unsized objects.
2689 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2690 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002691 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002692 gep_type_iterator GTI = gep_type_begin(GEP);
2693 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2694 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002695 I != E; ++I) {
2696 Value *Index = *I;
2697 // Compute the (potentially symbolic) offset in bytes for this index.
2698 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2699 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002700 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002701 TotalOffset = getAddExpr(TotalOffset,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002702 getOffsetOfExpr(STy, FieldNo),
Dan Gohmand281ed22009-12-18 02:09:29 +00002703 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002704 } else {
2705 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002706 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002707 // Getelementptr indices are signed.
Dan Gohman8db08df2010-02-02 01:38:49 +00002708 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002709 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohman4f8eea82010-02-01 18:27:38 +00002710 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
Dan Gohmand281ed22009-12-18 02:09:29 +00002711 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2712 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2713 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002714 }
2715 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002716 return getAddExpr(getSCEV(Base), TotalOffset,
2717 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002718}
2719
Nick Lewycky83bb0052007-11-22 07:59:40 +00002720/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2721/// guaranteed to end in (at every loop iteration). It is, at the same time,
2722/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2723/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002724uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002725ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002726 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002727 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002728
Dan Gohman622ed672009-05-04 22:02:23 +00002729 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002730 return std::min(GetMinTrailingZeros(T->getOperand()),
2731 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002732
Dan Gohman622ed672009-05-04 22:02:23 +00002733 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002734 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2735 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2736 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002737 }
2738
Dan Gohman622ed672009-05-04 22:02:23 +00002739 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002740 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2741 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2742 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002743 }
2744
Dan Gohman622ed672009-05-04 22:02:23 +00002745 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002746 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002747 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002748 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002749 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002750 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002751 }
2752
Dan Gohman622ed672009-05-04 22:02:23 +00002753 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002754 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002755 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2756 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002757 for (unsigned i = 1, e = M->getNumOperands();
2758 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002759 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002760 BitWidth);
2761 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002762 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002763
Dan Gohman622ed672009-05-04 22:02:23 +00002764 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002765 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002766 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002767 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002768 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002769 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002770 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002771
Dan Gohman622ed672009-05-04 22:02:23 +00002772 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002773 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002774 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002775 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002776 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002777 return MinOpRes;
2778 }
2779
Dan Gohman622ed672009-05-04 22:02:23 +00002780 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002781 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002782 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002783 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002784 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002785 return MinOpRes;
2786 }
2787
Dan Gohman2c364ad2009-06-19 23:29:04 +00002788 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2789 // For a SCEVUnknown, ask ValueTracking.
2790 unsigned BitWidth = getTypeSizeInBits(U->getType());
2791 APInt Mask = APInt::getAllOnesValue(BitWidth);
2792 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2793 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2794 return Zeros.countTrailingOnes();
2795 }
2796
2797 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002798 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002799}
Chris Lattner53e677a2004-04-02 20:23:17 +00002800
Dan Gohman85b05a22009-07-13 21:35:55 +00002801/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2802///
2803ConstantRange
2804ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002805
2806 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002807 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002808
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002809 unsigned BitWidth = getTypeSizeInBits(S->getType());
2810 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2811
2812 // If the value has known zeros, the maximum unsigned value will have those
2813 // known zeros as well.
2814 uint32_t TZ = GetMinTrailingZeros(S);
2815 if (TZ != 0)
2816 ConservativeResult =
2817 ConstantRange(APInt::getMinValue(BitWidth),
2818 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2819
Dan Gohman85b05a22009-07-13 21:35:55 +00002820 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2821 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2822 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2823 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002824 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002825 }
2826
2827 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2828 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2829 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2830 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002831 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002832 }
2833
2834 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2835 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2836 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2837 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002838 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002839 }
2840
2841 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2842 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2843 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2844 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002845 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002846 }
2847
2848 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2849 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2850 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002851 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002852 }
2853
2854 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2855 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002856 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002857 }
2858
2859 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2860 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002861 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002862 }
2863
2864 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2865 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002866 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002867 }
2868
Dan Gohman85b05a22009-07-13 21:35:55 +00002869 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002870 // If there's no unsigned wrap, the value will never be less than its
2871 // initial value.
2872 if (AddRec->hasNoUnsignedWrap())
2873 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00002874 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00002875 ConservativeResult =
Dan Gohmanb64cf892010-04-11 22:13:11 +00002876 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002877
2878 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002879 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002880 const Type *Ty = AddRec->getType();
2881 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002882 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2883 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002884 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2885
2886 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00002887 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00002888
2889 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00002890 ConstantRange StepRange = getSignedRange(Step);
2891 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
2892 ConstantRange EndRange =
2893 StartRange.add(MaxBECountRange.multiply(StepRange));
2894
2895 // Check for overflow. This must be done with ConstantRange arithmetic
2896 // because we could be called from within the ScalarEvolution overflow
2897 // checking code.
2898 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
2899 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
2900 ConstantRange ExtMaxBECountRange =
2901 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
2902 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
2903 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
2904 ExtEndRange)
2905 return ConservativeResult;
2906
Dan Gohman85b05a22009-07-13 21:35:55 +00002907 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2908 EndRange.getUnsignedMin());
2909 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2910 EndRange.getUnsignedMax());
2911 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002912 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002913 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002914 }
2915 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002916
2917 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002918 }
2919
2920 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2921 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002922 APInt Mask = APInt::getAllOnesValue(BitWidth);
2923 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2924 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002925 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002926 return ConservativeResult;
2927 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002928 }
2929
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002930 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002931}
2932
Dan Gohman85b05a22009-07-13 21:35:55 +00002933/// getSignedRange - Determine the signed range for a particular SCEV.
2934///
2935ConstantRange
2936ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002937
Dan Gohman85b05a22009-07-13 21:35:55 +00002938 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2939 return ConstantRange(C->getValue()->getValue());
2940
Dan Gohman52fddd32010-01-26 04:40:18 +00002941 unsigned BitWidth = getTypeSizeInBits(S->getType());
2942 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2943
2944 // If the value has known zeros, the maximum signed value will have those
2945 // known zeros as well.
2946 uint32_t TZ = GetMinTrailingZeros(S);
2947 if (TZ != 0)
2948 ConservativeResult =
2949 ConstantRange(APInt::getSignedMinValue(BitWidth),
2950 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2951
Dan Gohman85b05a22009-07-13 21:35:55 +00002952 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2953 ConstantRange X = getSignedRange(Add->getOperand(0));
2954 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2955 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002956 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002957 }
2958
Dan Gohman85b05a22009-07-13 21:35:55 +00002959 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2960 ConstantRange X = getSignedRange(Mul->getOperand(0));
2961 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2962 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002963 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002964 }
2965
Dan Gohman85b05a22009-07-13 21:35:55 +00002966 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2967 ConstantRange X = getSignedRange(SMax->getOperand(0));
2968 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2969 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002970 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002971 }
Dan Gohman62849c02009-06-24 01:05:09 +00002972
Dan Gohman85b05a22009-07-13 21:35:55 +00002973 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2974 ConstantRange X = getSignedRange(UMax->getOperand(0));
2975 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2976 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002977 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002978 }
Dan Gohman62849c02009-06-24 01:05:09 +00002979
Dan Gohman85b05a22009-07-13 21:35:55 +00002980 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2981 ConstantRange X = getSignedRange(UDiv->getLHS());
2982 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00002983 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002984 }
Dan Gohman62849c02009-06-24 01:05:09 +00002985
Dan Gohman85b05a22009-07-13 21:35:55 +00002986 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2987 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002988 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002989 }
2990
2991 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2992 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002993 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002994 }
2995
2996 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2997 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002998 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002999 }
3000
Dan Gohman85b05a22009-07-13 21:35:55 +00003001 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003002 // If there's no signed wrap, and all the operands have the same sign or
3003 // zero, the value won't ever change sign.
3004 if (AddRec->hasNoSignedWrap()) {
3005 bool AllNonNeg = true;
3006 bool AllNonPos = true;
3007 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3008 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3009 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3010 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003011 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003012 ConservativeResult = ConservativeResult.intersectWith(
3013 ConstantRange(APInt(BitWidth, 0),
3014 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003015 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003016 ConservativeResult = ConservativeResult.intersectWith(
3017 ConstantRange(APInt::getSignedMinValue(BitWidth),
3018 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003019 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003020
3021 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003022 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003023 const Type *Ty = AddRec->getType();
3024 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003025 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3026 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003027 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3028
3029 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003030 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003031
3032 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003033 ConstantRange StepRange = getSignedRange(Step);
3034 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3035 ConstantRange EndRange =
3036 StartRange.add(MaxBECountRange.multiply(StepRange));
3037
3038 // Check for overflow. This must be done with ConstantRange arithmetic
3039 // because we could be called from within the ScalarEvolution overflow
3040 // checking code.
3041 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3042 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3043 ConstantRange ExtMaxBECountRange =
3044 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3045 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3046 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3047 ExtEndRange)
3048 return ConservativeResult;
3049
Dan Gohman85b05a22009-07-13 21:35:55 +00003050 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3051 EndRange.getSignedMin());
3052 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3053 EndRange.getSignedMax());
3054 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003055 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003056 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003057 }
Dan Gohman62849c02009-06-24 01:05:09 +00003058 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003059
3060 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003061 }
3062
Dan Gohman2c364ad2009-06-19 23:29:04 +00003063 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3064 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003065 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003066 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003067 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3068 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003069 return ConservativeResult;
3070 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003071 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003072 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003073 }
3074
Dan Gohman52fddd32010-01-26 04:40:18 +00003075 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003076}
3077
Chris Lattner53e677a2004-04-02 20:23:17 +00003078/// createSCEV - We know that there is no SCEV for the specified value.
3079/// Analyze the expression.
3080///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003081const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003082 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003083 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003084
Dan Gohman6c459a22008-06-22 19:56:46 +00003085 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003086 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003087 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003088
3089 // Don't attempt to analyze instructions in blocks that aren't
3090 // reachable. Such instructions don't matter, and they aren't required
3091 // to obey basic rules for definitions dominating uses which this
3092 // analysis depends on.
3093 if (!DT->isReachableFromEntry(I->getParent()))
3094 return getUnknown(V);
3095 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003096 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003097 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3098 return getConstant(CI);
3099 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003100 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003101 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3102 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003103 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003104 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003105
Dan Gohmanca178902009-07-17 20:47:02 +00003106 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003107 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003108 case Instruction::Add:
3109 // Don't transfer the NSW and NUW bits from the Add instruction to the
3110 // Add expression, because the Instruction may be guarded by control
3111 // flow and the no-overflow bits may not be valid for the expression in
3112 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003113 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003114 getSCEV(U->getOperand(1)));
3115 case Instruction::Mul:
3116 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3117 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003118 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003119 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003120 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003121 return getUDivExpr(getSCEV(U->getOperand(0)),
3122 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003123 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003124 return getMinusSCEV(getSCEV(U->getOperand(0)),
3125 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003126 case Instruction::And:
3127 // For an expression like x&255 that merely masks off the high bits,
3128 // use zext(trunc(x)) as the SCEV expression.
3129 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003130 if (CI->isNullValue())
3131 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003132 if (CI->isAllOnesValue())
3133 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003134 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003135
3136 // Instcombine's ShrinkDemandedConstant may strip bits out of
3137 // constants, obscuring what would otherwise be a low-bits mask.
3138 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3139 // knew about to reconstruct a low-bits mask value.
3140 unsigned LZ = A.countLeadingZeros();
3141 unsigned BitWidth = A.getBitWidth();
3142 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3143 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3144 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3145
3146 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3147
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003148 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003149 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003150 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003151 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003152 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003153 }
3154 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003155
Dan Gohman6c459a22008-06-22 19:56:46 +00003156 case Instruction::Or:
3157 // If the RHS of the Or is a constant, we may have something like:
3158 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3159 // optimizations will transparently handle this case.
3160 //
3161 // In order for this transformation to be safe, the LHS must be of the
3162 // form X*(2^n) and the Or constant must be less than 2^n.
3163 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003164 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003165 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003166 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003167 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3168 // Build a plain add SCEV.
3169 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3170 // If the LHS of the add was an addrec and it has no-wrap flags,
3171 // transfer the no-wrap flags, since an or won't introduce a wrap.
3172 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3173 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3174 if (OldAR->hasNoUnsignedWrap())
3175 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3176 if (OldAR->hasNoSignedWrap())
3177 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3178 }
3179 return S;
3180 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003181 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003182 break;
3183 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003184 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003185 // If the RHS of the xor is a signbit, then this is just an add.
3186 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003187 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003188 return getAddExpr(getSCEV(U->getOperand(0)),
3189 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003190
3191 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003192 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003193 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003194
3195 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3196 // This is a variant of the check for xor with -1, and it handles
3197 // the case where instcombine has trimmed non-demanded bits out
3198 // of an xor with -1.
3199 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3200 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3201 if (BO->getOpcode() == Instruction::And &&
3202 LCI->getValue() == CI->getValue())
3203 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003204 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003205 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003206 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003207 const Type *Z0Ty = Z0->getType();
3208 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3209
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003210 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003211 // mask off the high bits. Complement the operand and
3212 // re-apply the zext.
3213 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3214 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3215
3216 // If C is a single bit, it may be in the sign-bit position
3217 // before the zero-extend. In this case, represent the xor
3218 // using an add, which is equivalent, and re-apply the zext.
3219 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3220 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3221 Trunc.isSignBit())
3222 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3223 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003224 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003225 }
3226 break;
3227
3228 case Instruction::Shl:
3229 // Turn shift left of a constant amount into a multiply.
3230 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003231 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003232
3233 // If the shift count is not less than the bitwidth, the result of
3234 // the shift is undefined. Don't try to analyze it, because the
3235 // resolution chosen here may differ from the resolution chosen in
3236 // other parts of the compiler.
3237 if (SA->getValue().uge(BitWidth))
3238 break;
3239
Owen Andersoneed707b2009-07-24 23:12:02 +00003240 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003241 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003242 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003243 }
3244 break;
3245
Nick Lewycky01eaf802008-07-07 06:15:49 +00003246 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003247 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003248 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003249 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003250
3251 // If the shift count is not less than the bitwidth, the result of
3252 // the shift is undefined. Don't try to analyze it, because the
3253 // resolution chosen here may differ from the resolution chosen in
3254 // other parts of the compiler.
3255 if (SA->getValue().uge(BitWidth))
3256 break;
3257
Owen Andersoneed707b2009-07-24 23:12:02 +00003258 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003259 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003260 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003261 }
3262 break;
3263
Dan Gohman4ee29af2009-04-21 02:26:00 +00003264 case Instruction::AShr:
3265 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3266 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003267 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003268 if (L->getOpcode() == Instruction::Shl &&
3269 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003270 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3271
3272 // If the shift count is not less than the bitwidth, the result of
3273 // the shift is undefined. Don't try to analyze it, because the
3274 // resolution chosen here may differ from the resolution chosen in
3275 // other parts of the compiler.
3276 if (CI->getValue().uge(BitWidth))
3277 break;
3278
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003279 uint64_t Amt = BitWidth - CI->getZExtValue();
3280 if (Amt == BitWidth)
3281 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003282 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003283 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003284 IntegerType::get(getContext(),
3285 Amt)),
3286 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003287 }
3288 break;
3289
Dan Gohman6c459a22008-06-22 19:56:46 +00003290 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003291 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003292
3293 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003294 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003295
3296 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003297 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003298
3299 case Instruction::BitCast:
3300 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003301 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003302 return getSCEV(U->getOperand(0));
3303 break;
3304
Dan Gohman4f8eea82010-02-01 18:27:38 +00003305 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3306 // lead to pointer expressions which cannot safely be expanded to GEPs,
3307 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3308 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003309
Dan Gohman26466c02009-05-08 20:26:55 +00003310 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003311 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003312
Dan Gohman6c459a22008-06-22 19:56:46 +00003313 case Instruction::PHI:
3314 return createNodeForPHI(cast<PHINode>(U));
3315
3316 case Instruction::Select:
3317 // This could be a smax or umax that was lowered earlier.
3318 // Try to recover it.
3319 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3320 Value *LHS = ICI->getOperand(0);
3321 Value *RHS = ICI->getOperand(1);
3322 switch (ICI->getPredicate()) {
3323 case ICmpInst::ICMP_SLT:
3324 case ICmpInst::ICMP_SLE:
3325 std::swap(LHS, RHS);
3326 // fall through
3327 case ICmpInst::ICMP_SGT:
3328 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003329 // a >s b ? a+x : b+x -> smax(a, b)+x
3330 // a >s b ? b+x : a+x -> smin(a, b)+x
3331 if (LHS->getType() == U->getType()) {
3332 const SCEV *LS = getSCEV(LHS);
3333 const SCEV *RS = getSCEV(RHS);
3334 const SCEV *LA = getSCEV(U->getOperand(1));
3335 const SCEV *RA = getSCEV(U->getOperand(2));
3336 const SCEV *LDiff = getMinusSCEV(LA, LS);
3337 const SCEV *RDiff = getMinusSCEV(RA, RS);
3338 if (LDiff == RDiff)
3339 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3340 LDiff = getMinusSCEV(LA, RS);
3341 RDiff = getMinusSCEV(RA, LS);
3342 if (LDiff == RDiff)
3343 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3344 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003345 break;
3346 case ICmpInst::ICMP_ULT:
3347 case ICmpInst::ICMP_ULE:
3348 std::swap(LHS, RHS);
3349 // fall through
3350 case ICmpInst::ICMP_UGT:
3351 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003352 // a >u b ? a+x : b+x -> umax(a, b)+x
3353 // a >u b ? b+x : a+x -> umin(a, b)+x
3354 if (LHS->getType() == U->getType()) {
3355 const SCEV *LS = getSCEV(LHS);
3356 const SCEV *RS = getSCEV(RHS);
3357 const SCEV *LA = getSCEV(U->getOperand(1));
3358 const SCEV *RA = getSCEV(U->getOperand(2));
3359 const SCEV *LDiff = getMinusSCEV(LA, LS);
3360 const SCEV *RDiff = getMinusSCEV(RA, RS);
3361 if (LDiff == RDiff)
3362 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3363 LDiff = getMinusSCEV(LA, RS);
3364 RDiff = getMinusSCEV(RA, LS);
3365 if (LDiff == RDiff)
3366 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3367 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003368 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003369 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003370 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3371 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003372 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003373 cast<ConstantInt>(RHS)->isZero()) {
3374 const SCEV *One = getConstant(LHS->getType(), 1);
3375 const SCEV *LS = getSCEV(LHS);
3376 const SCEV *LA = getSCEV(U->getOperand(1));
3377 const SCEV *RA = getSCEV(U->getOperand(2));
3378 const SCEV *LDiff = getMinusSCEV(LA, LS);
3379 const SCEV *RDiff = getMinusSCEV(RA, One);
3380 if (LDiff == RDiff)
3381 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3382 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003383 break;
3384 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003385 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3386 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003387 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003388 cast<ConstantInt>(RHS)->isZero()) {
3389 const SCEV *One = getConstant(LHS->getType(), 1);
3390 const SCEV *LS = getSCEV(LHS);
3391 const SCEV *LA = getSCEV(U->getOperand(1));
3392 const SCEV *RA = getSCEV(U->getOperand(2));
3393 const SCEV *LDiff = getMinusSCEV(LA, One);
3394 const SCEV *RDiff = getMinusSCEV(RA, LS);
3395 if (LDiff == RDiff)
3396 return getAddExpr(getUMaxExpr(LS, One), LDiff);
3397 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003398 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003399 default:
3400 break;
3401 }
3402 }
3403
3404 default: // We cannot analyze this expression.
3405 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003406 }
3407
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003408 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003409}
3410
3411
3412
3413//===----------------------------------------------------------------------===//
3414// Iteration Count Computation Code
3415//
3416
Dan Gohman46bdfb02009-02-24 18:55:53 +00003417/// getBackedgeTakenCount - If the specified loop has a predictable
3418/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3419/// object. The backedge-taken count is the number of times the loop header
3420/// will be branched to from within the loop. This is one less than the
3421/// trip count of the loop, since it doesn't count the first iteration,
3422/// when the header is branched to from outside the loop.
3423///
3424/// Note that it is not valid to call this method on a loop without a
3425/// loop-invariant backedge-taken count (see
3426/// hasLoopInvariantBackedgeTakenCount).
3427///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003428const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003429 return getBackedgeTakenInfo(L).Exact;
3430}
3431
3432/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3433/// return the least SCEV value that is known never to be less than the
3434/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003435const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003436 return getBackedgeTakenInfo(L).Max;
3437}
3438
Dan Gohman59ae6b92009-07-08 19:23:34 +00003439/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3440/// onto the given Worklist.
3441static void
3442PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3443 BasicBlock *Header = L->getHeader();
3444
3445 // Push all Loop-header PHIs onto the Worklist stack.
3446 for (BasicBlock::iterator I = Header->begin();
3447 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3448 Worklist.push_back(PN);
3449}
3450
Dan Gohmana1af7572009-04-30 20:47:05 +00003451const ScalarEvolution::BackedgeTakenInfo &
3452ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003453 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003454 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003455 // update the value. The temporary CouldNotCompute value tells SCEV
3456 // code elsewhere that it shouldn't attempt to request a new
3457 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003458 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003459 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3460 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003461 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3462 if (BECount.Exact != getCouldNotCompute()) {
3463 assert(BECount.Exact->isLoopInvariant(L) &&
3464 BECount.Max->isLoopInvariant(L) &&
3465 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003466 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003467
Dan Gohman01ecca22009-04-27 20:16:15 +00003468 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003469 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003470 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003471 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003472 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003473 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003474 if (isa<PHINode>(L->getHeader()->begin()))
3475 // Only count loops that have phi nodes as not being computable.
3476 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003477 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003478
3479 // Now that we know more about the trip count for this loop, forget any
3480 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003481 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003482 // information. This is similar to the code in forgetLoop, except that
3483 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003484 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003485 SmallVector<Instruction *, 16> Worklist;
3486 PushLoopPHIs(L, Worklist);
3487
3488 SmallPtrSet<Instruction *, 8> Visited;
3489 while (!Worklist.empty()) {
3490 Instruction *I = Worklist.pop_back_val();
3491 if (!Visited.insert(I)) continue;
3492
Dan Gohman5d984912009-12-18 01:14:11 +00003493 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003494 Scalars.find(static_cast<Value *>(I));
3495 if (It != Scalars.end()) {
3496 // SCEVUnknown for a PHI either means that it has an unrecognized
3497 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003498 // by createNodeForPHI. In the former case, additional loop trip
3499 // count information isn't going to change anything. In the later
3500 // case, createNodeForPHI will perform the necessary updates on its
3501 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003502 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3503 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003504 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003505 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003506 if (PHINode *PN = dyn_cast<PHINode>(I))
3507 ConstantEvolutionLoopExitValue.erase(PN);
3508 }
3509
3510 PushDefUseChildren(I, Worklist);
3511 }
3512 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003513 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003514 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003515}
3516
Dan Gohman4c7279a2009-10-31 15:04:55 +00003517/// forgetLoop - This method should be called by the client when it has
3518/// changed a loop in a way that may effect ScalarEvolution's ability to
3519/// compute a trip count, or if the loop is deleted.
3520void ScalarEvolution::forgetLoop(const Loop *L) {
3521 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003522 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003523
Dan Gohman4c7279a2009-10-31 15:04:55 +00003524 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003525 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003526 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003527
Dan Gohman59ae6b92009-07-08 19:23:34 +00003528 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003529 while (!Worklist.empty()) {
3530 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003531 if (!Visited.insert(I)) continue;
3532
Dan Gohman5d984912009-12-18 01:14:11 +00003533 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003534 Scalars.find(static_cast<Value *>(I));
3535 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003536 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003537 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003538 if (PHINode *PN = dyn_cast<PHINode>(I))
3539 ConstantEvolutionLoopExitValue.erase(PN);
3540 }
3541
3542 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003543 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003544}
3545
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003546/// forgetValue - This method should be called by the client when it has
3547/// changed a value in a way that may effect its value, or which may
3548/// disconnect it from a def-use chain linking it to a loop.
3549void ScalarEvolution::forgetValue(Value *V) {
3550 Instruction *I = dyn_cast<Instruction>(V);
3551 if (!I) return;
3552
3553 // Drop information about expressions based on loop-header PHIs.
3554 SmallVector<Instruction *, 16> Worklist;
3555 Worklist.push_back(I);
3556
3557 SmallPtrSet<Instruction *, 8> Visited;
3558 while (!Worklist.empty()) {
3559 I = Worklist.pop_back_val();
3560 if (!Visited.insert(I)) continue;
3561
3562 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
3563 Scalars.find(static_cast<Value *>(I));
3564 if (It != Scalars.end()) {
3565 ValuesAtScopes.erase(It->second);
3566 Scalars.erase(It);
3567 if (PHINode *PN = dyn_cast<PHINode>(I))
3568 ConstantEvolutionLoopExitValue.erase(PN);
3569 }
3570
3571 PushDefUseChildren(I, Worklist);
3572 }
3573}
3574
Dan Gohman46bdfb02009-02-24 18:55:53 +00003575/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3576/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003577ScalarEvolution::BackedgeTakenInfo
3578ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003579 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003580 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003581
Dan Gohmana334aa72009-06-22 00:31:57 +00003582 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003583 const SCEV *BECount = getCouldNotCompute();
3584 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003585 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003586 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3587 BackedgeTakenInfo NewBTI =
3588 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003589
Dan Gohman1c343752009-06-27 21:21:31 +00003590 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003591 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003592 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003593 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003594 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003595 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003596 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003597 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003598 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003599 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003600 }
Dan Gohman1c343752009-06-27 21:21:31 +00003601 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003602 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003603 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003604 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003605 }
3606
3607 return BackedgeTakenInfo(BECount, MaxBECount);
3608}
3609
3610/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3611/// of the specified loop will execute if it exits via the specified block.
3612ScalarEvolution::BackedgeTakenInfo
3613ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3614 BasicBlock *ExitingBlock) {
3615
3616 // Okay, we've chosen an exiting block. See what condition causes us to
3617 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003618 //
3619 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003620 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003621 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003622 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003623
Chris Lattner8b0e3602007-01-07 02:24:26 +00003624 // At this point, we know we have a conditional branch that determines whether
3625 // the loop is exited. However, we don't know if the branch is executed each
3626 // time through the loop. If not, then the execution count of the branch will
3627 // not be equal to the trip count of the loop.
3628 //
3629 // Currently we check for this by checking to see if the Exit branch goes to
3630 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003631 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003632 // loop header. This is common for un-rotated loops.
3633 //
3634 // If both of those tests fail, walk up the unique predecessor chain to the
3635 // header, stopping if there is an edge that doesn't exit the loop. If the
3636 // header is reached, the execution count of the branch will be equal to the
3637 // trip count of the loop.
3638 //
3639 // More extensive analysis could be done to handle more cases here.
3640 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003641 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003642 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003643 ExitBr->getParent() != L->getHeader()) {
3644 // The simple checks failed, try climbing the unique predecessor chain
3645 // up to the header.
3646 bool Ok = false;
3647 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3648 BasicBlock *Pred = BB->getUniquePredecessor();
3649 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003650 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003651 TerminatorInst *PredTerm = Pred->getTerminator();
3652 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3653 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3654 if (PredSucc == BB)
3655 continue;
3656 // If the predecessor has a successor that isn't BB and isn't
3657 // outside the loop, assume the worst.
3658 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003659 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003660 }
3661 if (Pred == L->getHeader()) {
3662 Ok = true;
3663 break;
3664 }
3665 BB = Pred;
3666 }
3667 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003668 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003669 }
3670
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003671 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003672 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3673 ExitBr->getSuccessor(0),
3674 ExitBr->getSuccessor(1));
3675}
3676
3677/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3678/// backedge of the specified loop will execute if its exit condition
3679/// were a conditional branch of ExitCond, TBB, and FBB.
3680ScalarEvolution::BackedgeTakenInfo
3681ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3682 Value *ExitCond,
3683 BasicBlock *TBB,
3684 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003685 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003686 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3687 if (BO->getOpcode() == Instruction::And) {
3688 // Recurse on the operands of the and.
3689 BackedgeTakenInfo BTI0 =
3690 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3691 BackedgeTakenInfo BTI1 =
3692 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003693 const SCEV *BECount = getCouldNotCompute();
3694 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003695 if (L->contains(TBB)) {
3696 // Both conditions must be true for the loop to continue executing.
3697 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003698 if (BTI0.Exact == getCouldNotCompute() ||
3699 BTI1.Exact == getCouldNotCompute())
3700 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003701 else
3702 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003703 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003704 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003705 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003706 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003707 else
3708 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003709 } else {
3710 // Both conditions must be true for the loop to exit.
3711 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003712 if (BTI0.Exact != getCouldNotCompute() &&
3713 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003714 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003715 if (BTI0.Max != getCouldNotCompute() &&
3716 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003717 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3718 }
3719
3720 return BackedgeTakenInfo(BECount, MaxBECount);
3721 }
3722 if (BO->getOpcode() == Instruction::Or) {
3723 // Recurse on the operands of the or.
3724 BackedgeTakenInfo BTI0 =
3725 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3726 BackedgeTakenInfo BTI1 =
3727 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003728 const SCEV *BECount = getCouldNotCompute();
3729 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003730 if (L->contains(FBB)) {
3731 // Both conditions must be false for the loop to continue executing.
3732 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003733 if (BTI0.Exact == getCouldNotCompute() ||
3734 BTI1.Exact == getCouldNotCompute())
3735 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003736 else
3737 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003738 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003739 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003740 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003741 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003742 else
3743 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003744 } else {
3745 // Both conditions must be false for the loop to exit.
3746 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003747 if (BTI0.Exact != getCouldNotCompute() &&
3748 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003749 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003750 if (BTI0.Max != getCouldNotCompute() &&
3751 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003752 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3753 }
3754
3755 return BackedgeTakenInfo(BECount, MaxBECount);
3756 }
3757 }
3758
3759 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003760 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003761 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3762 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003763
Dan Gohman00cb5b72010-02-19 18:12:07 +00003764 // Check for a constant condition. These are normally stripped out by
3765 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3766 // preserve the CFG and is temporarily leaving constant conditions
3767 // in place.
3768 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3769 if (L->contains(FBB) == !CI->getZExtValue())
3770 // The backedge is always taken.
3771 return getCouldNotCompute();
3772 else
3773 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003774 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003775 }
3776
Eli Friedman361e54d2009-05-09 12:32:42 +00003777 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003778 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3779}
3780
3781/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3782/// backedge of the specified loop will execute if its exit condition
3783/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3784ScalarEvolution::BackedgeTakenInfo
3785ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3786 ICmpInst *ExitCond,
3787 BasicBlock *TBB,
3788 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003789
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 // If the condition was exit on true, convert the condition to exit on false
3791 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003792 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003793 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003794 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003795 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003796
3797 // Handle common loops like: for (X = "string"; *X; ++X)
3798 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3799 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003800 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003801 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003802 if (ItCnt.hasAnyInfo())
3803 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003804 }
3805
Dan Gohman0bba49c2009-07-07 17:06:11 +00003806 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3807 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003808
3809 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003810 LHS = getSCEVAtScope(LHS, L);
3811 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003812
Dan Gohman64a845e2009-06-24 04:48:43 +00003813 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003814 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003815 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3816 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003817 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003818 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003819 }
3820
Dan Gohman03557dc2010-05-03 16:35:17 +00003821 // Simplify the operands before analyzing them.
3822 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3823
Chris Lattner53e677a2004-04-02 20:23:17 +00003824 // If we have a comparison of a chrec against a constant, try to use value
3825 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003826 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3827 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003828 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003829 // Form the constant range.
3830 ConstantRange CompRange(
3831 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003832
Dan Gohman0bba49c2009-07-07 17:06:11 +00003833 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003834 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003835 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003836
Chris Lattner53e677a2004-04-02 20:23:17 +00003837 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003838 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003839 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003840 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
3841 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003842 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003843 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003844 case ICmpInst::ICMP_EQ: { // while (X == Y)
3845 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003846 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
3847 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00003848 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003849 }
3850 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003851 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3852 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003853 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003854 }
3855 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003856 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3857 getNotSCEV(RHS), L, true);
3858 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003859 break;
3860 }
3861 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003862 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3863 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003864 break;
3865 }
3866 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003867 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3868 getNotSCEV(RHS), L, false);
3869 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003870 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003871 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003872 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003873#if 0
David Greene25e0e872009-12-23 22:18:14 +00003874 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003875 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003876 dbgs() << "[unsigned] ";
3877 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003878 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003879 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003880#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003881 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003882 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003883 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003884 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003885}
3886
Chris Lattner673e02b2004-10-12 01:49:27 +00003887static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003888EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3889 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003890 const SCEV *InVal = SE.getConstant(C);
3891 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003892 assert(isa<SCEVConstant>(Val) &&
3893 "Evaluation of SCEV at constant didn't fold correctly?");
3894 return cast<SCEVConstant>(Val)->getValue();
3895}
3896
3897/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3898/// and a GEP expression (missing the pointer index) indexing into it, return
3899/// the addressed element of the initializer or null if the index expression is
3900/// invalid.
3901static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003902GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003903 const std::vector<ConstantInt*> &Indices) {
3904 Constant *Init = GV->getInitializer();
3905 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003906 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003907 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3908 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3909 Init = cast<Constant>(CS->getOperand(Idx));
3910 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3911 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3912 Init = cast<Constant>(CA->getOperand(Idx));
3913 } else if (isa<ConstantAggregateZero>(Init)) {
3914 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3915 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003916 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003917 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3918 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003919 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003920 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003921 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003922 }
3923 return 0;
3924 } else {
3925 return 0; // Unknown initializer type
3926 }
3927 }
3928 return Init;
3929}
3930
Dan Gohman46bdfb02009-02-24 18:55:53 +00003931/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3932/// 'icmp op load X, cst', try to see if we can compute the backedge
3933/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003934ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00003935ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3936 LoadInst *LI,
3937 Constant *RHS,
3938 const Loop *L,
3939 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003940 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003941
3942 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003943 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00003944 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003945 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003946
3947 // Make sure that it is really a constant global we are gepping, with an
3948 // initializer, and make sure the first IDX is really 0.
3949 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003950 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003951 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3952 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003953 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003954
3955 // Okay, we allow one non-constant index into the GEP instruction.
3956 Value *VarIdx = 0;
3957 std::vector<ConstantInt*> Indexes;
3958 unsigned VarIdxNum = 0;
3959 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3960 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3961 Indexes.push_back(CI);
3962 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003963 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003964 VarIdx = GEP->getOperand(i);
3965 VarIdxNum = i-2;
3966 Indexes.push_back(0);
3967 }
3968
3969 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3970 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003971 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003972 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003973
3974 // We can only recognize very limited forms of loop index expressions, in
3975 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003976 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003977 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3978 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3979 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003980 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003981
3982 unsigned MaxSteps = MaxBruteForceIterations;
3983 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003984 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003985 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003986 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003987
3988 // Form the GEP offset.
3989 Indexes[VarIdxNum] = Val;
3990
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003991 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003992 if (Result == 0) break; // Cannot compute!
3993
3994 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003995 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003996 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003997 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003998#if 0
David Greene25e0e872009-12-23 22:18:14 +00003999 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004000 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4001 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004002#endif
4003 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004004 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004005 }
4006 }
Dan Gohman1c343752009-06-27 21:21:31 +00004007 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004008}
4009
4010
Chris Lattner3221ad02004-04-17 22:58:41 +00004011/// CanConstantFold - Return true if we can constant fold an instruction of the
4012/// specified type, assuming that all operands were constants.
4013static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004014 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004015 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4016 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004017
Chris Lattner3221ad02004-04-17 22:58:41 +00004018 if (const CallInst *CI = dyn_cast<CallInst>(I))
4019 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004020 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004021 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004022}
4023
Chris Lattner3221ad02004-04-17 22:58:41 +00004024/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4025/// in the loop that V is derived from. We allow arbitrary operations along the
4026/// way, but the operands of an operation must either be constants or a value
4027/// derived from a constant PHI. If this expression does not fit with these
4028/// constraints, return null.
4029static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4030 // If this is not an instruction, or if this is an instruction outside of the
4031 // loop, it can't be derived from a loop PHI.
4032 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004033 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004034
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004035 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004036 if (L->getHeader() == I->getParent())
4037 return PN;
4038 else
4039 // We don't currently keep track of the control flow needed to evaluate
4040 // PHIs, so we cannot handle PHIs inside of loops.
4041 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004042 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004043
4044 // If we won't be able to constant fold this expression even if the operands
4045 // are constants, return early.
4046 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004047
Chris Lattner3221ad02004-04-17 22:58:41 +00004048 // Otherwise, we can evaluate this instruction if all of its operands are
4049 // constant or derived from a PHI node themselves.
4050 PHINode *PHI = 0;
4051 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
4052 if (!(isa<Constant>(I->getOperand(Op)) ||
4053 isa<GlobalValue>(I->getOperand(Op)))) {
4054 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4055 if (P == 0) return 0; // Not evolving from PHI
4056 if (PHI == 0)
4057 PHI = P;
4058 else if (PHI != P)
4059 return 0; // Evolving from multiple different PHIs.
4060 }
4061
4062 // This is a expression evolving from a constant PHI!
4063 return PHI;
4064}
4065
4066/// EvaluateExpression - Given an expression that passes the
4067/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4068/// in the loop has the value PHIVal. If we can't fold this expression for some
4069/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004070static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4071 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004072 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004073 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00004074 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00004075 Instruction *I = cast<Instruction>(V);
4076
4077 std::vector<Constant*> Operands;
4078 Operands.resize(I->getNumOperands());
4079
4080 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004081 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004082 if (Operands[i] == 0) return 0;
4083 }
4084
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004085 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004086 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004087 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004088 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004089 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004090}
4091
4092/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4093/// in the header of its containing loop, we know the loop executes a
4094/// constant number of times, and the PHI node is just a recurrence
4095/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004096Constant *
4097ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004098 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004099 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004100 std::map<PHINode*, Constant*>::iterator I =
4101 ConstantEvolutionLoopExitValue.find(PN);
4102 if (I != ConstantEvolutionLoopExitValue.end())
4103 return I->second;
4104
Dan Gohmane0567812010-04-08 23:03:40 +00004105 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004106 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4107
4108 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4109
4110 // Since the loop is canonicalized, the PHI node must have two entries. One
4111 // entry must be a constant (coming in from outside of the loop), and the
4112 // second must be derived from the same PHI.
4113 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4114 Constant *StartCST =
4115 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4116 if (StartCST == 0)
4117 return RetVal = 0; // Must be a constant.
4118
4119 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4120 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4121 if (PN2 != PN)
4122 return RetVal = 0; // Not derived from same PHI.
4123
4124 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004125 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004126 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004127
Dan Gohman46bdfb02009-02-24 18:55:53 +00004128 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004129 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004130 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4131 if (IterationNum == NumIterations)
4132 return RetVal = PHIVal; // Got exit value!
4133
4134 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004135 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004136 if (NextPHI == PHIVal)
4137 return RetVal = NextPHI; // Stopped evolving!
4138 if (NextPHI == 0)
4139 return 0; // Couldn't evaluate!
4140 PHIVal = NextPHI;
4141 }
4142}
4143
Dan Gohman07ad19b2009-07-27 16:09:48 +00004144/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004145/// constant number of times (the condition evolves only from constants),
4146/// try to evaluate a few iterations of the loop until we get the exit
4147/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004148/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004149const SCEV *
4150ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4151 Value *Cond,
4152 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004153 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004154 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004155
4156 // Since the loop is canonicalized, the PHI node must have two entries. One
4157 // entry must be a constant (coming in from outside of the loop), and the
4158 // second must be derived from the same PHI.
4159 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4160 Constant *StartCST =
4161 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004162 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004163
4164 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4165 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004166 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004167
4168 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4169 // the loop symbolically to determine when the condition gets a value of
4170 // "ExitWhen".
4171 unsigned IterationNum = 0;
4172 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4173 for (Constant *PHIVal = StartCST;
4174 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004175 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004176 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004177
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004178 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004179 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004180
Reid Spencere8019bb2007-03-01 07:25:48 +00004181 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004182 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004183 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004184 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004185
Chris Lattner3221ad02004-04-17 22:58:41 +00004186 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004187 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004188 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004189 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004190 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004191 }
4192
4193 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004194 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004195}
4196
Dan Gohmane7125f42009-09-03 15:00:26 +00004197/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004198/// at the specified scope in the program. The L value specifies a loop
4199/// nest to evaluate the expression at, where null is the top-level or a
4200/// specified loop is immediately inside of the loop.
4201///
4202/// This method can be used to compute the exit value for a variable defined
4203/// in a loop by querying what the value will hold in the parent loop.
4204///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004205/// In the case that a relevant loop exit value cannot be computed, the
4206/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004207const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004208 // Check to see if we've folded this expression at this loop before.
4209 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4210 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4211 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4212 if (!Pair.second)
4213 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004214
Dan Gohman42214892009-08-31 21:15:23 +00004215 // Otherwise compute it.
4216 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004217 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004218 return C;
4219}
4220
4221const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004222 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004223
Nick Lewycky3e630762008-02-20 06:48:22 +00004224 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004225 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004226 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004227 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004228 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004229 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4230 if (PHINode *PN = dyn_cast<PHINode>(I))
4231 if (PN->getParent() == LI->getHeader()) {
4232 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004233 // to see if the loop that contains it has a known backedge-taken
4234 // count. If so, we may be able to force computation of the exit
4235 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004236 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004237 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004238 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004239 // Okay, we know how many times the containing loop executes. If
4240 // this is a constant evolving PHI node, get the final value at
4241 // the specified iteration number.
4242 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004243 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004244 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004245 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004246 }
4247 }
4248
Reid Spencer09906f32006-12-04 21:33:23 +00004249 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004250 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004251 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004252 // result. This is particularly useful for computing loop exit values.
4253 if (CanConstantFold(I)) {
4254 std::vector<Constant*> Operands;
4255 Operands.reserve(I->getNumOperands());
4256 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4257 Value *Op = I->getOperand(i);
4258 if (Constant *C = dyn_cast<Constant>(Op)) {
4259 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004260 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004261 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004262 // non-integer and non-pointer, don't even try to analyze them
4263 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004264 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004265 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004266
Dan Gohman5d984912009-12-18 01:14:11 +00004267 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004268 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004269 Constant *C = SC->getValue();
4270 if (C->getType() != Op->getType())
4271 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4272 Op->getType(),
4273 false),
4274 C, Op->getType());
4275 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004276 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004277 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4278 if (C->getType() != Op->getType())
4279 C =
4280 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4281 Op->getType(),
4282 false),
4283 C, Op->getType());
4284 Operands.push_back(C);
4285 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004286 return V;
4287 } else {
4288 return V;
4289 }
4290 }
4291 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004292
Dan Gohmane177c9a2010-02-24 19:31:47 +00004293 Constant *C = 0;
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004294 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4295 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004296 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004297 else
4298 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004299 &Operands[0], Operands.size(), TD);
Dan Gohmane177c9a2010-02-24 19:31:47 +00004300 if (C)
4301 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004302 }
4303 }
4304
4305 // This is some other type of SCEVUnknown, just return it.
4306 return V;
4307 }
4308
Dan Gohman622ed672009-05-04 22:02:23 +00004309 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004310 // Avoid performing the look-up in the common case where the specified
4311 // expression has no loop-variant portions.
4312 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004313 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004314 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004315 // Okay, at least one of these operands is loop variant but might be
4316 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004317 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4318 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004319 NewOps.push_back(OpAtScope);
4320
4321 for (++i; i != e; ++i) {
4322 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004323 NewOps.push_back(OpAtScope);
4324 }
4325 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004326 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004327 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004328 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004329 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004330 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004331 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004332 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004333 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004334 }
4335 }
4336 // If we got here, all operands are loop invariant.
4337 return Comm;
4338 }
4339
Dan Gohman622ed672009-05-04 22:02:23 +00004340 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004341 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4342 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004343 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4344 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004345 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004346 }
4347
4348 // If this is a loop recurrence for a loop that does not contain L, then we
4349 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004350 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004351 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004352 // To evaluate this recurrence, we need to know how many times the AddRec
4353 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004354 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004355 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004356
Eli Friedmanb42a6262008-08-04 23:49:06 +00004357 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004358 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004359 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004360 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004361 }
4362
Dan Gohman622ed672009-05-04 22:02:23 +00004363 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004364 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004365 if (Op == Cast->getOperand())
4366 return Cast; // must be loop invariant
4367 return getZeroExtendExpr(Op, Cast->getType());
4368 }
4369
Dan Gohman622ed672009-05-04 22:02:23 +00004370 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004371 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004372 if (Op == Cast->getOperand())
4373 return Cast; // must be loop invariant
4374 return getSignExtendExpr(Op, Cast->getType());
4375 }
4376
Dan Gohman622ed672009-05-04 22:02:23 +00004377 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004378 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004379 if (Op == Cast->getOperand())
4380 return Cast; // must be loop invariant
4381 return getTruncateExpr(Op, Cast->getType());
4382 }
4383
Torok Edwinc23197a2009-07-14 16:55:14 +00004384 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004385 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004386}
4387
Dan Gohman66a7e852009-05-08 20:38:54 +00004388/// getSCEVAtScope - This is a convenience function which does
4389/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004390const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004391 return getSCEVAtScope(getSCEV(V), L);
4392}
4393
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004394/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4395/// following equation:
4396///
4397/// A * X = B (mod N)
4398///
4399/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4400/// A and B isn't important.
4401///
4402/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004403static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004404 ScalarEvolution &SE) {
4405 uint32_t BW = A.getBitWidth();
4406 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4407 assert(A != 0 && "A must be non-zero.");
4408
4409 // 1. D = gcd(A, N)
4410 //
4411 // The gcd of A and N may have only one prime factor: 2. The number of
4412 // trailing zeros in A is its multiplicity
4413 uint32_t Mult2 = A.countTrailingZeros();
4414 // D = 2^Mult2
4415
4416 // 2. Check if B is divisible by D.
4417 //
4418 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4419 // is not less than multiplicity of this prime factor for D.
4420 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004421 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004422
4423 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4424 // modulo (N / D).
4425 //
4426 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4427 // bit width during computations.
4428 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4429 APInt Mod(BW + 1, 0);
4430 Mod.set(BW - Mult2); // Mod = N / D
4431 APInt I = AD.multiplicativeInverse(Mod);
4432
4433 // 4. Compute the minimum unsigned root of the equation:
4434 // I * (B / D) mod (N / D)
4435 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4436
4437 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4438 // bits.
4439 return SE.getConstant(Result.trunc(BW));
4440}
Chris Lattner53e677a2004-04-02 20:23:17 +00004441
4442/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4443/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4444/// might be the same) or two SCEVCouldNotCompute objects.
4445///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004446static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004447SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004448 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004449 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4450 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4451 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004452
Chris Lattner53e677a2004-04-02 20:23:17 +00004453 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004454 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004455 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004456 return std::make_pair(CNC, CNC);
4457 }
4458
Reid Spencere8019bb2007-03-01 07:25:48 +00004459 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004460 const APInt &L = LC->getValue()->getValue();
4461 const APInt &M = MC->getValue()->getValue();
4462 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004463 APInt Two(BitWidth, 2);
4464 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004465
Dan Gohman64a845e2009-06-24 04:48:43 +00004466 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004467 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004468 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004469 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4470 // The B coefficient is M-N/2
4471 APInt B(M);
4472 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004473
Reid Spencere8019bb2007-03-01 07:25:48 +00004474 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004475 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004476
Reid Spencere8019bb2007-03-01 07:25:48 +00004477 // Compute the B^2-4ac term.
4478 APInt SqrtTerm(B);
4479 SqrtTerm *= B;
4480 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004481
Reid Spencere8019bb2007-03-01 07:25:48 +00004482 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4483 // integer value or else APInt::sqrt() will assert.
4484 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004485
Dan Gohman64a845e2009-06-24 04:48:43 +00004486 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004487 // The divisions must be performed as signed divisions.
4488 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004489 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004490 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004491 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004492 return std::make_pair(CNC, CNC);
4493 }
4494
Owen Andersone922c022009-07-22 00:24:57 +00004495 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004496
4497 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004498 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004499 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004500 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004501
Dan Gohman64a845e2009-06-24 04:48:43 +00004502 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004503 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004504 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004505}
4506
4507/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004508/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004509ScalarEvolution::BackedgeTakenInfo
4510ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004511 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004512 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004513 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004514 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004515 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004516 }
4517
Dan Gohman35738ac2009-05-04 22:30:44 +00004518 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004519 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004520 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004521
4522 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004523 // If this is an affine expression, the execution count of this branch is
4524 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004525 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004526 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004527 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004528 // equivalent to:
4529 //
4530 // Step*N = -Start (mod 2^BW)
4531 //
4532 // where BW is the common bit width of Start and Step.
4533
Chris Lattner53e677a2004-04-02 20:23:17 +00004534 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004535 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4536 L->getParentLoop());
4537 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4538 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004539
Dan Gohman622ed672009-05-04 22:02:23 +00004540 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004541 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004542
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004543 // First, handle unitary steps.
4544 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004545 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004546 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4547 return Start; // N = Start (as unsigned)
4548
4549 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004550 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004551 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004552 -StartC->getValue()->getValue(),
4553 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004554 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004555 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004556 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4557 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004558 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004559 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004560 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4561 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004562 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004563#if 0
David Greene25e0e872009-12-23 22:18:14 +00004564 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004565 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004566#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004567 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004568 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004569 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004570 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004571 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004572 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004573
Chris Lattner53e677a2004-04-02 20:23:17 +00004574 // We can only use this value if the chrec ends up with an exact zero
4575 // value at this index. When solving for "X*X != 5", for example, we
4576 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004577 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004578 if (Val->isZero())
4579 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004580 }
4581 }
4582 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004583
Dan Gohman1c343752009-06-27 21:21:31 +00004584 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004585}
4586
4587/// HowFarToNonZero - Return the number of times a backedge checking the
4588/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004589/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004590ScalarEvolution::BackedgeTakenInfo
4591ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004592 // Loops that look like: while (X == 0) are very strange indeed. We don't
4593 // handle them yet except for the trivial case. This could be expanded in the
4594 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004595
Chris Lattner53e677a2004-04-02 20:23:17 +00004596 // If the value is a constant, check to see if it is known to be non-zero
4597 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004598 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004599 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004600 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004601 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004602 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004603
Chris Lattner53e677a2004-04-02 20:23:17 +00004604 // We could implement others, but I really doubt anyone writes loops like
4605 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004606 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004607}
4608
Dan Gohman859b4822009-05-18 15:36:09 +00004609/// getLoopPredecessor - If the given loop's header has exactly one unique
4610/// predecessor outside the loop, return it. Otherwise return null.
Dan Gohman2c93e392010-04-14 16:08:56 +00004611/// This is less strict that the loop "preheader" concept, which requires
4612/// the predecessor to have only one single successor.
Dan Gohman859b4822009-05-18 15:36:09 +00004613///
4614BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4615 BasicBlock *Header = L->getHeader();
4616 BasicBlock *Pred = 0;
4617 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4618 PI != E; ++PI)
4619 if (!L->contains(*PI)) {
4620 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4621 Pred = *PI;
4622 }
4623 return Pred;
4624}
4625
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004626/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4627/// (which may not be an immediate predecessor) which has exactly one
4628/// successor from which BB is reachable, or null if no such block is
4629/// found.
4630///
Dan Gohman005752b2010-04-15 16:19:08 +00004631std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004632ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004633 // If the block has a unique predecessor, then there is no path from the
4634 // predecessor to the block that does not go through the direct edge
4635 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004636 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004637 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004638
4639 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004640 // If the header has a unique predecessor outside the loop, it must be
4641 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004642 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman005752b2010-04-15 16:19:08 +00004643 return std::make_pair(getLoopPredecessor(L), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004644
Dan Gohman005752b2010-04-15 16:19:08 +00004645 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004646}
4647
Dan Gohman763bad12009-06-20 00:35:32 +00004648/// HasSameValue - SCEV structural equivalence is usually sufficient for
4649/// testing whether two expressions are equal, however for the purposes of
4650/// looking for a condition guarding a loop, it can be useful to be a little
4651/// more general, since a front-end may have replicated the controlling
4652/// expression.
4653///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004654static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004655 // Quick check to see if they are the same SCEV.
4656 if (A == B) return true;
4657
4658 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4659 // two different instructions with the same value. Check for this case.
4660 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4661 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4662 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4663 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004664 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004665 return true;
4666
4667 // Otherwise assume they may have a different value.
4668 return false;
4669}
4670
Dan Gohmane9796502010-04-24 01:28:42 +00004671/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4672/// predicate Pred. Return true iff any changes were made.
4673///
4674bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4675 const SCEV *&LHS, const SCEV *&RHS) {
4676 bool Changed = false;
4677
4678 // Canonicalize a constant to the right side.
4679 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4680 // Check for both operands constant.
4681 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4682 if (ConstantExpr::getICmp(Pred,
4683 LHSC->getValue(),
4684 RHSC->getValue())->isNullValue())
4685 goto trivially_false;
4686 else
4687 goto trivially_true;
4688 }
4689 // Otherwise swap the operands to put the constant on the right.
4690 std::swap(LHS, RHS);
4691 Pred = ICmpInst::getSwappedPredicate(Pred);
4692 Changed = true;
4693 }
4694
4695 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004696 // addrec's loop, put the addrec on the left. Also make a dominance check,
4697 // as both operands could be addrecs loop-invariant in each other's loop.
4698 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4699 const Loop *L = AR->getLoop();
4700 if (LHS->isLoopInvariant(L) && LHS->properlyDominates(L->getHeader(), DT)) {
Dan Gohmane9796502010-04-24 01:28:42 +00004701 std::swap(LHS, RHS);
4702 Pred = ICmpInst::getSwappedPredicate(Pred);
4703 Changed = true;
4704 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004705 }
Dan Gohmane9796502010-04-24 01:28:42 +00004706
4707 // If there's a constant operand, canonicalize comparisons with boundary
4708 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4709 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4710 const APInt &RA = RC->getValue()->getValue();
4711 switch (Pred) {
4712 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4713 case ICmpInst::ICMP_EQ:
4714 case ICmpInst::ICMP_NE:
4715 break;
4716 case ICmpInst::ICMP_UGE:
4717 if ((RA - 1).isMinValue()) {
4718 Pred = ICmpInst::ICMP_NE;
4719 RHS = getConstant(RA - 1);
4720 Changed = true;
4721 break;
4722 }
4723 if (RA.isMaxValue()) {
4724 Pred = ICmpInst::ICMP_EQ;
4725 Changed = true;
4726 break;
4727 }
4728 if (RA.isMinValue()) goto trivially_true;
4729
4730 Pred = ICmpInst::ICMP_UGT;
4731 RHS = getConstant(RA - 1);
4732 Changed = true;
4733 break;
4734 case ICmpInst::ICMP_ULE:
4735 if ((RA + 1).isMaxValue()) {
4736 Pred = ICmpInst::ICMP_NE;
4737 RHS = getConstant(RA + 1);
4738 Changed = true;
4739 break;
4740 }
4741 if (RA.isMinValue()) {
4742 Pred = ICmpInst::ICMP_EQ;
4743 Changed = true;
4744 break;
4745 }
4746 if (RA.isMaxValue()) goto trivially_true;
4747
4748 Pred = ICmpInst::ICMP_ULT;
4749 RHS = getConstant(RA + 1);
4750 Changed = true;
4751 break;
4752 case ICmpInst::ICMP_SGE:
4753 if ((RA - 1).isMinSignedValue()) {
4754 Pred = ICmpInst::ICMP_NE;
4755 RHS = getConstant(RA - 1);
4756 Changed = true;
4757 break;
4758 }
4759 if (RA.isMaxSignedValue()) {
4760 Pred = ICmpInst::ICMP_EQ;
4761 Changed = true;
4762 break;
4763 }
4764 if (RA.isMinSignedValue()) goto trivially_true;
4765
4766 Pred = ICmpInst::ICMP_SGT;
4767 RHS = getConstant(RA - 1);
4768 Changed = true;
4769 break;
4770 case ICmpInst::ICMP_SLE:
4771 if ((RA + 1).isMaxSignedValue()) {
4772 Pred = ICmpInst::ICMP_NE;
4773 RHS = getConstant(RA + 1);
4774 Changed = true;
4775 break;
4776 }
4777 if (RA.isMinSignedValue()) {
4778 Pred = ICmpInst::ICMP_EQ;
4779 Changed = true;
4780 break;
4781 }
4782 if (RA.isMaxSignedValue()) goto trivially_true;
4783
4784 Pred = ICmpInst::ICMP_SLT;
4785 RHS = getConstant(RA + 1);
4786 Changed = true;
4787 break;
4788 case ICmpInst::ICMP_UGT:
4789 if (RA.isMinValue()) {
4790 Pred = ICmpInst::ICMP_NE;
4791 Changed = true;
4792 break;
4793 }
4794 if ((RA + 1).isMaxValue()) {
4795 Pred = ICmpInst::ICMP_EQ;
4796 RHS = getConstant(RA + 1);
4797 Changed = true;
4798 break;
4799 }
4800 if (RA.isMaxValue()) goto trivially_false;
4801 break;
4802 case ICmpInst::ICMP_ULT:
4803 if (RA.isMaxValue()) {
4804 Pred = ICmpInst::ICMP_NE;
4805 Changed = true;
4806 break;
4807 }
4808 if ((RA - 1).isMinValue()) {
4809 Pred = ICmpInst::ICMP_EQ;
4810 RHS = getConstant(RA - 1);
4811 Changed = true;
4812 break;
4813 }
4814 if (RA.isMinValue()) goto trivially_false;
4815 break;
4816 case ICmpInst::ICMP_SGT:
4817 if (RA.isMinSignedValue()) {
4818 Pred = ICmpInst::ICMP_NE;
4819 Changed = true;
4820 break;
4821 }
4822 if ((RA + 1).isMaxSignedValue()) {
4823 Pred = ICmpInst::ICMP_EQ;
4824 RHS = getConstant(RA + 1);
4825 Changed = true;
4826 break;
4827 }
4828 if (RA.isMaxSignedValue()) goto trivially_false;
4829 break;
4830 case ICmpInst::ICMP_SLT:
4831 if (RA.isMaxSignedValue()) {
4832 Pred = ICmpInst::ICMP_NE;
4833 Changed = true;
4834 break;
4835 }
4836 if ((RA - 1).isMinSignedValue()) {
4837 Pred = ICmpInst::ICMP_EQ;
4838 RHS = getConstant(RA - 1);
4839 Changed = true;
4840 break;
4841 }
4842 if (RA.isMinSignedValue()) goto trivially_false;
4843 break;
4844 }
4845 }
4846
4847 // Check for obvious equality.
4848 if (HasSameValue(LHS, RHS)) {
4849 if (ICmpInst::isTrueWhenEqual(Pred))
4850 goto trivially_true;
4851 if (ICmpInst::isFalseWhenEqual(Pred))
4852 goto trivially_false;
4853 }
4854
Dan Gohman03557dc2010-05-03 16:35:17 +00004855 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
4856 // adding or subtracting 1 from one of the operands.
4857 switch (Pred) {
4858 case ICmpInst::ICMP_SLE:
4859 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
4860 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
4861 /*HasNUW=*/false, /*HasNSW=*/true);
4862 Pred = ICmpInst::ICMP_SLT;
4863 Changed = true;
4864 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004865 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004866 /*HasNUW=*/false, /*HasNSW=*/true);
4867 Pred = ICmpInst::ICMP_SLT;
4868 Changed = true;
4869 }
4870 break;
4871 case ICmpInst::ICMP_SGE:
4872 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004873 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004874 /*HasNUW=*/false, /*HasNSW=*/true);
4875 Pred = ICmpInst::ICMP_SGT;
4876 Changed = true;
4877 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
4878 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
4879 /*HasNUW=*/false, /*HasNSW=*/true);
4880 Pred = ICmpInst::ICMP_SGT;
4881 Changed = true;
4882 }
4883 break;
4884 case ICmpInst::ICMP_ULE:
4885 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004886 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004887 /*HasNUW=*/true, /*HasNSW=*/false);
4888 Pred = ICmpInst::ICMP_ULT;
4889 Changed = true;
4890 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004891 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004892 /*HasNUW=*/true, /*HasNSW=*/false);
4893 Pred = ICmpInst::ICMP_ULT;
4894 Changed = true;
4895 }
4896 break;
4897 case ICmpInst::ICMP_UGE:
4898 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004899 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004900 /*HasNUW=*/true, /*HasNSW=*/false);
4901 Pred = ICmpInst::ICMP_UGT;
4902 Changed = true;
4903 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00004904 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00004905 /*HasNUW=*/true, /*HasNSW=*/false);
4906 Pred = ICmpInst::ICMP_UGT;
4907 Changed = true;
4908 }
4909 break;
4910 default:
4911 break;
4912 }
4913
Dan Gohmane9796502010-04-24 01:28:42 +00004914 // TODO: More simplifications are possible here.
4915
4916 return Changed;
4917
4918trivially_true:
4919 // Return 0 == 0.
4920 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
4921 Pred = ICmpInst::ICMP_EQ;
4922 return true;
4923
4924trivially_false:
4925 // Return 0 != 0.
4926 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
4927 Pred = ICmpInst::ICMP_NE;
4928 return true;
4929}
4930
Dan Gohman85b05a22009-07-13 21:35:55 +00004931bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4932 return getSignedRange(S).getSignedMax().isNegative();
4933}
4934
4935bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4936 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4937}
4938
4939bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4940 return !getSignedRange(S).getSignedMin().isNegative();
4941}
4942
4943bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4944 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4945}
4946
4947bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4948 return isKnownNegative(S) || isKnownPositive(S);
4949}
4950
4951bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4952 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00004953 // Canonicalize the inputs first.
4954 (void)SimplifyICmpOperands(Pred, LHS, RHS);
4955
Dan Gohman53c66ea2010-04-11 22:16:48 +00004956 // If LHS or RHS is an addrec, check to see if the condition is true in
4957 // every iteration of the loop.
4958 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
4959 if (isLoopEntryGuardedByCond(
4960 AR->getLoop(), Pred, AR->getStart(), RHS) &&
4961 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00004962 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00004963 return true;
4964 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
4965 if (isLoopEntryGuardedByCond(
4966 AR->getLoop(), Pred, LHS, AR->getStart()) &&
4967 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00004968 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00004969 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00004970
Dan Gohman53c66ea2010-04-11 22:16:48 +00004971 // Otherwise see what can be done with known constant ranges.
4972 return isKnownPredicateWithRanges(Pred, LHS, RHS);
4973}
4974
4975bool
4976ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
4977 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004978 if (HasSameValue(LHS, RHS))
4979 return ICmpInst::isTrueWhenEqual(Pred);
4980
Dan Gohman53c66ea2010-04-11 22:16:48 +00004981 // This code is split out from isKnownPredicate because it is called from
4982 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00004983 switch (Pred) {
4984 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004985 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004986 break;
4987 case ICmpInst::ICMP_SGT:
4988 Pred = ICmpInst::ICMP_SLT;
4989 std::swap(LHS, RHS);
4990 case ICmpInst::ICMP_SLT: {
4991 ConstantRange LHSRange = getSignedRange(LHS);
4992 ConstantRange RHSRange = getSignedRange(RHS);
4993 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4994 return true;
4995 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4996 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004997 break;
4998 }
4999 case ICmpInst::ICMP_SGE:
5000 Pred = ICmpInst::ICMP_SLE;
5001 std::swap(LHS, RHS);
5002 case ICmpInst::ICMP_SLE: {
5003 ConstantRange LHSRange = getSignedRange(LHS);
5004 ConstantRange RHSRange = getSignedRange(RHS);
5005 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5006 return true;
5007 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5008 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005009 break;
5010 }
5011 case ICmpInst::ICMP_UGT:
5012 Pred = ICmpInst::ICMP_ULT;
5013 std::swap(LHS, RHS);
5014 case ICmpInst::ICMP_ULT: {
5015 ConstantRange LHSRange = getUnsignedRange(LHS);
5016 ConstantRange RHSRange = getUnsignedRange(RHS);
5017 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5018 return true;
5019 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5020 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005021 break;
5022 }
5023 case ICmpInst::ICMP_UGE:
5024 Pred = ICmpInst::ICMP_ULE;
5025 std::swap(LHS, RHS);
5026 case ICmpInst::ICMP_ULE: {
5027 ConstantRange LHSRange = getUnsignedRange(LHS);
5028 ConstantRange RHSRange = getUnsignedRange(RHS);
5029 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5030 return true;
5031 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5032 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005033 break;
5034 }
5035 case ICmpInst::ICMP_NE: {
5036 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5037 return true;
5038 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5039 return true;
5040
5041 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5042 if (isKnownNonZero(Diff))
5043 return true;
5044 break;
5045 }
5046 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005047 // The check at the top of the function catches the case where
5048 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005049 break;
5050 }
5051 return false;
5052}
5053
5054/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5055/// protected by a conditional between LHS and RHS. This is used to
5056/// to eliminate casts.
5057bool
5058ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5059 ICmpInst::Predicate Pred,
5060 const SCEV *LHS, const SCEV *RHS) {
5061 // Interpret a null as meaning no loop, where there is obviously no guard
5062 // (interprocedural conditions notwithstanding).
5063 if (!L) return true;
5064
5065 BasicBlock *Latch = L->getLoopLatch();
5066 if (!Latch)
5067 return false;
5068
5069 BranchInst *LoopContinuePredicate =
5070 dyn_cast<BranchInst>(Latch->getTerminator());
5071 if (!LoopContinuePredicate ||
5072 LoopContinuePredicate->isUnconditional())
5073 return false;
5074
Dan Gohman0f4b2852009-07-21 23:03:19 +00005075 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
5076 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005077}
5078
Dan Gohman3948d0b2010-04-11 19:27:13 +00005079/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005080/// by a conditional between LHS and RHS. This is used to help avoid max
5081/// expressions in loop trip counts, and to eliminate casts.
5082bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005083ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5084 ICmpInst::Predicate Pred,
5085 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005086 // Interpret a null as meaning no loop, where there is obviously no guard
5087 // (interprocedural conditions notwithstanding).
5088 if (!L) return false;
5089
Dan Gohman859b4822009-05-18 15:36:09 +00005090 // Starting at the loop predecessor, climb up the predecessor chain, as long
5091 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005092 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005093 for (std::pair<BasicBlock *, BasicBlock *>
5094 Pair(getLoopPredecessor(L), L->getHeader());
5095 Pair.first;
5096 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005097
5098 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005099 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005100 if (!LoopEntryPredicate ||
5101 LoopEntryPredicate->isUnconditional())
5102 continue;
5103
Dan Gohman0f4b2852009-07-21 23:03:19 +00005104 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
Dan Gohman005752b2010-04-15 16:19:08 +00005105 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005106 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005107 }
5108
Dan Gohman38372182008-08-12 20:17:31 +00005109 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005110}
5111
Dan Gohman0f4b2852009-07-21 23:03:19 +00005112/// isImpliedCond - Test whether the condition described by Pred, LHS,
5113/// and RHS is true whenever the given Cond value evaluates to true.
5114bool ScalarEvolution::isImpliedCond(Value *CondValue,
5115 ICmpInst::Predicate Pred,
5116 const SCEV *LHS, const SCEV *RHS,
5117 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005118 // Recursively handle And and Or conditions.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
5120 if (BO->getOpcode() == Instruction::And) {
5121 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00005122 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5123 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005124 } else if (BO->getOpcode() == Instruction::Or) {
5125 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00005126 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
5127 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005128 }
5129 }
5130
5131 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
5132 if (!ICI) return false;
5133
Dan Gohman85b05a22009-07-13 21:35:55 +00005134 // Bail if the ICmp's operands' types are wider than the needed type
5135 // before attempting to call getSCEV on them. This avoids infinite
5136 // recursion, since the analysis of widening casts can require loop
5137 // exit condition information for overflow checking, which would
5138 // lead back here.
5139 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005140 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005141 return false;
5142
Dan Gohman0f4b2852009-07-21 23:03:19 +00005143 // Now that we found a conditional branch that dominates the loop, check to
5144 // see if it is the comparison we are looking for.
5145 ICmpInst::Predicate FoundPred;
5146 if (Inverse)
5147 FoundPred = ICI->getInversePredicate();
5148 else
5149 FoundPred = ICI->getPredicate();
5150
5151 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5152 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005153
5154 // Balance the types. The case where FoundLHS' type is wider than
5155 // LHS' type is checked for above.
5156 if (getTypeSizeInBits(LHS->getType()) >
5157 getTypeSizeInBits(FoundLHS->getType())) {
5158 if (CmpInst::isSigned(Pred)) {
5159 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5160 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5161 } else {
5162 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5163 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5164 }
5165 }
5166
Dan Gohman0f4b2852009-07-21 23:03:19 +00005167 // Canonicalize the query to match the way instcombine will have
5168 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005169 if (SimplifyICmpOperands(Pred, LHS, RHS))
5170 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005171 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005172 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5173 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005174 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005175
5176 // Check to see if we can make the LHS or RHS match.
5177 if (LHS == FoundRHS || RHS == FoundLHS) {
5178 if (isa<SCEVConstant>(RHS)) {
5179 std::swap(FoundLHS, FoundRHS);
5180 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5181 } else {
5182 std::swap(LHS, RHS);
5183 Pred = ICmpInst::getSwappedPredicate(Pred);
5184 }
5185 }
5186
5187 // Check whether the found predicate is the same as the desired predicate.
5188 if (FoundPred == Pred)
5189 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5190
5191 // Check whether swapping the found predicate makes it the same as the
5192 // desired predicate.
5193 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5194 if (isa<SCEVConstant>(RHS))
5195 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5196 else
5197 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5198 RHS, LHS, FoundLHS, FoundRHS);
5199 }
5200
5201 // Check whether the actual condition is beyond sufficient.
5202 if (FoundPred == ICmpInst::ICMP_EQ)
5203 if (ICmpInst::isTrueWhenEqual(Pred))
5204 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5205 return true;
5206 if (Pred == ICmpInst::ICMP_NE)
5207 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5208 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5209 return true;
5210
5211 // Otherwise assume the worst.
5212 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005213}
5214
Dan Gohman0f4b2852009-07-21 23:03:19 +00005215/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005216/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005217/// and FoundRHS is true.
5218bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5219 const SCEV *LHS, const SCEV *RHS,
5220 const SCEV *FoundLHS,
5221 const SCEV *FoundRHS) {
5222 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5223 FoundLHS, FoundRHS) ||
5224 // ~x < ~y --> x > y
5225 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5226 getNotSCEV(FoundRHS),
5227 getNotSCEV(FoundLHS));
5228}
5229
5230/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005231/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005232/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005233bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005234ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5235 const SCEV *LHS, const SCEV *RHS,
5236 const SCEV *FoundLHS,
5237 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005238 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005239 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5240 case ICmpInst::ICMP_EQ:
5241 case ICmpInst::ICMP_NE:
5242 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5243 return true;
5244 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005245 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005246 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005247 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5248 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005249 return true;
5250 break;
5251 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005252 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005253 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5254 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005255 return true;
5256 break;
5257 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005258 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005259 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5260 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005261 return true;
5262 break;
5263 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005264 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005265 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5266 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005267 return true;
5268 break;
5269 }
5270
5271 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005272}
5273
Dan Gohman51f53b72009-06-21 23:46:38 +00005274/// getBECount - Subtract the end and start values and divide by the step,
5275/// rounding up, to get the number of times the backedge is executed. Return
5276/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005277const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005278 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005279 const SCEV *Step,
5280 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005281 assert(!isKnownNegative(Step) &&
5282 "This code doesn't handle negative strides yet!");
5283
Dan Gohman51f53b72009-06-21 23:46:38 +00005284 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005285 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005286 const SCEV *Diff = getMinusSCEV(End, Start);
5287 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005288
5289 // Add an adjustment to the difference between End and Start so that
5290 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005291 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005292
Dan Gohman1f96e672009-09-17 18:05:20 +00005293 if (!NoWrap) {
5294 // Check Add for unsigned overflow.
5295 // TODO: More sophisticated things could be done here.
5296 const Type *WideTy = IntegerType::get(getContext(),
5297 getTypeSizeInBits(Ty) + 1);
5298 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5299 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5300 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5301 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5302 return getCouldNotCompute();
5303 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005304
5305 return getUDivExpr(Add, Step);
5306}
5307
Chris Lattnerdb25de42005-08-15 23:33:51 +00005308/// HowManyLessThans - Return the number of times a backedge containing the
5309/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005310/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005311ScalarEvolution::BackedgeTakenInfo
5312ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5313 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005314 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005315 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005316
Dan Gohman35738ac2009-05-04 22:30:44 +00005317 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005318 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005319 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005320
Dan Gohman1f96e672009-09-17 18:05:20 +00005321 // Check to see if we have a flag which makes analysis easy.
5322 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5323 AddRec->hasNoUnsignedWrap();
5324
Chris Lattnerdb25de42005-08-15 23:33:51 +00005325 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005326 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005327 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005328
Dan Gohman52fddd32010-01-26 04:40:18 +00005329 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005330 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005331 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005332 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005333 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005334 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005335 // value and past the maximum value for its type in a single step.
5336 // Note that it's not sufficient to check NoWrap here, because even
5337 // though the value after a wrap is undefined, it's not undefined
5338 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005339 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005340 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005341 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005342 if (isSigned) {
5343 APInt Max = APInt::getSignedMaxValue(BitWidth);
5344 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5345 .slt(getSignedRange(RHS).getSignedMax()))
5346 return getCouldNotCompute();
5347 } else {
5348 APInt Max = APInt::getMaxValue(BitWidth);
5349 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5350 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5351 return getCouldNotCompute();
5352 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005353 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005354 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005355 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005356
Dan Gohmana1af7572009-04-30 20:47:05 +00005357 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5358 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5359 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005360 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005361
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005362 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005363 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005364
Dan Gohmana1af7572009-04-30 20:47:05 +00005365 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005366 const SCEV *MinStart = getConstant(isSigned ?
5367 getSignedRange(Start).getSignedMin() :
5368 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005369
Dan Gohmana1af7572009-04-30 20:47:05 +00005370 // If we know that the condition is true in order to enter the loop,
5371 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005372 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5373 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005374 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005375 if (!isLoopEntryGuardedByCond(L,
5376 isSigned ? ICmpInst::ICMP_SLT :
5377 ICmpInst::ICMP_ULT,
5378 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005379 End = isSigned ? getSMaxExpr(RHS, Start)
5380 : getUMaxExpr(RHS, Start);
5381
5382 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005383 const SCEV *MaxEnd = getConstant(isSigned ?
5384 getSignedRange(End).getSignedMax() :
5385 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005386
Dan Gohman52fddd32010-01-26 04:40:18 +00005387 // If MaxEnd is within a step of the maximum integer value in its type,
5388 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005389 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005390 // compute the correct value.
5391 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005392 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005393 MaxEnd = isSigned ?
5394 getSMinExpr(MaxEnd,
5395 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5396 StepMinusOne)) :
5397 getUMinExpr(MaxEnd,
5398 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5399 StepMinusOne));
5400
Dan Gohmana1af7572009-04-30 20:47:05 +00005401 // Finally, we subtract these two values and divide, rounding up, to get
5402 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005403 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005404
5405 // The maximum backedge count is similar, except using the minimum start
5406 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005407 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005408
5409 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005410 }
5411
Dan Gohman1c343752009-06-27 21:21:31 +00005412 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005413}
5414
Chris Lattner53e677a2004-04-02 20:23:17 +00005415/// getNumIterationsInRange - Return the number of iterations of this loop that
5416/// produce values in the specified constant range. Another way of looking at
5417/// this is that it returns the first iteration number where the value is not in
5418/// the condition, thus computing the exit count. If the iteration count can't
5419/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005420const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005421 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005422 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005423 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005424
5425 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005426 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005427 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005428 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005429 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005430 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005431 if (const SCEVAddRecExpr *ShiftedAddRec =
5432 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005433 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005434 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005435 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005436 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005437 }
5438
5439 // The only time we can solve this is when we have all constant indices.
5440 // Otherwise, we cannot determine the overflow conditions.
5441 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5442 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005443 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005444
5445
5446 // Okay at this point we know that all elements of the chrec are constants and
5447 // that the start element is zero.
5448
5449 // First check to see if the range contains zero. If not, the first
5450 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005451 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005452 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005453 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005454
Chris Lattner53e677a2004-04-02 20:23:17 +00005455 if (isAffine()) {
5456 // If this is an affine expression then we have this situation:
5457 // Solve {0,+,A} in Range === Ax in Range
5458
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005459 // We know that zero is in the range. If A is positive then we know that
5460 // the upper value of the range must be the first possible exit value.
5461 // If A is negative then the lower of the range is the last possible loop
5462 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005463 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005464 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5465 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005466
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005467 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005468 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005469 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005470
5471 // Evaluate at the exit value. If we really did fall out of the valid
5472 // range, then we computed our trip count, otherwise wrap around or other
5473 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005474 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005475 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005476 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005477
5478 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005479 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005480 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005481 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005482 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005483 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005484 } else if (isQuadratic()) {
5485 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5486 // quadratic equation to solve it. To do this, we must frame our problem in
5487 // terms of figuring out when zero is crossed, instead of when
5488 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005489 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005490 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005491 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005492
5493 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005494 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005495 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005496 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5497 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005498 if (R1) {
5499 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005500 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005501 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005502 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005503 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005504 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005505
Chris Lattner53e677a2004-04-02 20:23:17 +00005506 // Make sure the root is not off by one. The returned iteration should
5507 // not be in the range, but the previous one should be. When solving
5508 // for "X*X < 5", for example, we should not return a root of 2.
5509 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005510 R1->getValue(),
5511 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005512 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005513 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005514 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005515 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005516
Dan Gohman246b2562007-10-22 18:31:58 +00005517 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005518 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005519 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005520 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005521 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005522
Chris Lattner53e677a2004-04-02 20:23:17 +00005523 // If R1 was not in the range, then it is a good return value. Make
5524 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005525 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005526 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005527 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005528 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005529 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005530 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005531 }
5532 }
5533 }
5534
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005535 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005536}
5537
5538
5539
5540//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005541// SCEVCallbackVH Class Implementation
5542//===----------------------------------------------------------------------===//
5543
Dan Gohman1959b752009-05-19 19:22:47 +00005544void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005545 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005546 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5547 SE->ConstantEvolutionLoopExitValue.erase(PN);
5548 SE->Scalars.erase(getValPtr());
5549 // this now dangles!
5550}
5551
Dan Gohman1959b752009-05-19 19:22:47 +00005552void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005553 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005554
5555 // Forget all the expressions associated with users of the old value,
5556 // so that future queries will recompute the expressions using the new
5557 // value.
5558 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005559 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005560 Value *Old = getValPtr();
5561 bool DeleteOld = false;
5562 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5563 UI != UE; ++UI)
5564 Worklist.push_back(*UI);
5565 while (!Worklist.empty()) {
5566 User *U = Worklist.pop_back_val();
5567 // Deleting the Old value will cause this to dangle. Postpone
5568 // that until everything else is done.
5569 if (U == Old) {
5570 DeleteOld = true;
5571 continue;
5572 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005573 if (!Visited.insert(U))
5574 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005575 if (PHINode *PN = dyn_cast<PHINode>(U))
5576 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005577 SE->Scalars.erase(U);
5578 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5579 UI != UE; ++UI)
5580 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005581 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005582 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005583 if (DeleteOld) {
5584 if (PHINode *PN = dyn_cast<PHINode>(Old))
5585 SE->ConstantEvolutionLoopExitValue.erase(PN);
5586 SE->Scalars.erase(Old);
5587 // this now dangles!
5588 }
5589 // this may dangle!
5590}
5591
Dan Gohman1959b752009-05-19 19:22:47 +00005592ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005593 : CallbackVH(V), SE(se) {}
5594
5595//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005596// ScalarEvolution Class Implementation
5597//===----------------------------------------------------------------------===//
5598
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005599ScalarEvolution::ScalarEvolution()
Dan Gohmanfd447ef2010-06-07 19:36:14 +00005600 : FunctionPass(&ID), CurAllocationSequenceNumber(0) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005601}
5602
Chris Lattner53e677a2004-04-02 20:23:17 +00005603bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005604 this->F = &F;
5605 LI = &getAnalysis<LoopInfo>();
5606 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005607 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005608 return false;
5609}
5610
5611void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005612 Scalars.clear();
5613 BackedgeTakenCounts.clear();
5614 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005615 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005616 UniqueSCEVs.clear();
5617 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005618}
5619
5620void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5621 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005622 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005623 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005624}
5625
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005626bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005627 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005628}
5629
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005630static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005631 const Loop *L) {
5632 // Print all inner loops first
5633 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5634 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005635
Dan Gohman30733292010-01-09 18:17:45 +00005636 OS << "Loop ";
5637 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5638 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005639
Dan Gohman5d984912009-12-18 01:14:11 +00005640 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005641 L->getExitBlocks(ExitBlocks);
5642 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005643 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005644
Dan Gohman46bdfb02009-02-24 18:55:53 +00005645 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5646 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005647 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005648 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005649 }
5650
Dan Gohman30733292010-01-09 18:17:45 +00005651 OS << "\n"
5652 "Loop ";
5653 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5654 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005655
5656 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5657 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5658 } else {
5659 OS << "Unpredictable max backedge-taken count. ";
5660 }
5661
5662 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005663}
5664
Dan Gohman5d984912009-12-18 01:14:11 +00005665void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005666 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005667 // out SCEV values of all instructions that are interesting. Doing
5668 // this potentially causes it to create new SCEV objects though,
5669 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005670 // observable from outside the class though, so casting away the
5671 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005672 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005673
Dan Gohman30733292010-01-09 18:17:45 +00005674 OS << "Classifying expressions for: ";
5675 WriteAsOperand(OS, F, /*PrintType=*/false);
5676 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005677 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005678 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005679 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005680 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005681 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005682 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005683
Dan Gohman0c689c52009-06-19 17:49:54 +00005684 const Loop *L = LI->getLoopFor((*I).getParent());
5685
Dan Gohman0bba49c2009-07-07 17:06:11 +00005686 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005687 if (AtUse != SV) {
5688 OS << " --> ";
5689 AtUse->print(OS);
5690 }
5691
5692 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005693 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005694 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005695 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005696 OS << "<<Unknown>>";
5697 } else {
5698 OS << *ExitValue;
5699 }
5700 }
5701
Chris Lattner53e677a2004-04-02 20:23:17 +00005702 OS << "\n";
5703 }
5704
Dan Gohman30733292010-01-09 18:17:45 +00005705 OS << "Determining loop execution counts for: ";
5706 WriteAsOperand(OS, F, /*PrintType=*/false);
5707 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005708 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5709 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005710}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005711