blob: 2d8bd7d53a6ac4105bbb4b65e98c64f75ef8b710 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Owen Andersonecd0cd72009-06-22 21:39:50 +000017// can handle. These classes are reference counted, managed by the const SCEV*
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
Dan Gohmana7726c32009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000073#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074#include "llvm/Support/CommandLine.h"
75#include "llvm/Support/Compiler.h"
76#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000077#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078#include "llvm/Support/InstIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084using namespace llvm;
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman089efff2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman9bc642f2009-06-24 04:48:43 +000098 "symbolically execute a constant "
99 "derived loop"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100 cl::init(100));
101
Dan Gohman089efff2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104char ScalarEvolution::ID = 0;
105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122}
123
Dan Gohman7b560c42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohmanf8bc8e82009-05-18 15:22:39 +0000130bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
133 return false;
134}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135
Dan Gohmanf05118e2009-06-24 00:30:26 +0000136bool SCEV::isAllOnesValue() const {
137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
138 return SC->getValue()->isAllOnesValue();
139 return false;
140}
141
Owen Andersonb70139d2009-06-22 21:57:23 +0000142SCEVCouldNotCompute::SCEVCouldNotCompute() :
143 SCEV(scCouldNotCompute) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144
145bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 return false;
148}
149
150const Type *SCEVCouldNotCompute::getType() const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return 0;
153}
154
155bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
156 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
157 return false;
158}
159
Dan Gohman9bc642f2009-06-24 04:48:43 +0000160const SCEV *
161SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
162 const SCEV *Sym,
163 const SCEV *Conc,
164 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 return this;
166}
167
Dan Gohman13058cc2009-04-21 00:47:46 +0000168void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 OS << "***COULDNOTCOMPUTE***";
170}
171
172bool SCEVCouldNotCompute::classof(const SCEV *S) {
173 return S->getSCEVType() == scCouldNotCompute;
174}
175
Owen Andersonecd0cd72009-06-22 21:39:50 +0000176const SCEV* ScalarEvolution::getConstant(ConstantInt *V) {
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000177 SCEVConstant *&R = SCEVConstants[V];
Owen Andersonb70139d2009-06-22 21:57:23 +0000178 if (R == 0) R = new SCEVConstant(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 return R;
180}
181
Owen Andersonecd0cd72009-06-22 21:39:50 +0000182const SCEV* ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman89f85052007-10-22 18:31:58 +0000183 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184}
185
Owen Andersonecd0cd72009-06-22 21:39:50 +0000186const SCEV*
Dan Gohman8fd520a2009-06-15 22:12:54 +0000187ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
188 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
189}
190
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191const Type *SCEVConstant::getType() const { return V->getType(); }
192
Dan Gohman13058cc2009-04-21 00:47:46 +0000193void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 WriteAsOperand(OS, V, false);
195}
196
Dan Gohman2a381532009-04-21 01:25:57 +0000197SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Andersonb70139d2009-06-22 21:57:23 +0000198 const SCEV* op, const Type *ty)
199 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman2a381532009-04-21 01:25:57 +0000200
201bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
202 return Op->dominates(BB, DT);
203}
204
Owen Andersonb70139d2009-06-22 21:57:23 +0000205SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty)
206 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000207 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
208 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210}
211
Dan Gohman13058cc2009-04-21 00:47:46 +0000212void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000213 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214}
215
Owen Andersonb70139d2009-06-22 21:57:23 +0000216SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty)
217 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000218 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
219 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221}
222
Dan Gohman13058cc2009-04-21 00:47:46 +0000223void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000224 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225}
226
Owen Andersonb70139d2009-06-22 21:57:23 +0000227SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty)
228 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000229 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
230 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232}
233
Dan Gohman13058cc2009-04-21 00:47:46 +0000234void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000235 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236}
237
Dan Gohman13058cc2009-04-21 00:47:46 +0000238void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
240 const char *OpStr = getOperationStr();
241 OS << "(" << *Operands[0];
242 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
243 OS << OpStr << *Operands[i];
244 OS << ")";
245}
246
Dan Gohman9bc642f2009-06-24 04:48:43 +0000247const SCEV *
248SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
249 const SCEV *Sym,
250 const SCEV *Conc,
251 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000253 const SCEV* H =
Dan Gohman89f85052007-10-22 18:31:58 +0000254 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 if (H != getOperand(i)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000256 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 NewOps.reserve(getNumOperands());
258 for (unsigned j = 0; j != i; ++j)
259 NewOps.push_back(getOperand(j));
260 NewOps.push_back(H);
261 for (++i; i != e; ++i)
262 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000263 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264
265 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000266 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000268 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000269 else if (isa<SCEVSMaxExpr>(this))
270 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000271 else if (isa<SCEVUMaxExpr>(this))
272 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 else
274 assert(0 && "Unknown commutative expr!");
275 }
276 }
277 return this;
278}
279
Dan Gohman72a8a022009-05-07 14:00:19 +0000280bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
282 if (!getOperand(i)->dominates(BB, DT))
283 return false;
284 }
285 return true;
286}
287
Evan Cheng98c073b2009-02-17 00:13:06 +0000288bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
289 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
290}
291
Dan Gohman13058cc2009-04-21 00:47:46 +0000292void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000293 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294}
295
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000296const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000297 // In most cases the types of LHS and RHS will be the same, but in some
298 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
299 // depend on the type for correctness, but handling types carefully can
300 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
301 // a pointer type than the RHS, so use the RHS' type here.
302 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303}
304
Dan Gohman9bc642f2009-06-24 04:48:43 +0000305const SCEV *
306SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
307 const SCEV *Conc,
308 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000310 const SCEV* H =
Dan Gohman89f85052007-10-22 18:31:58 +0000311 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 if (H != getOperand(i)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000313 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 NewOps.reserve(getNumOperands());
315 for (unsigned j = 0; j != i; ++j)
316 NewOps.push_back(getOperand(j));
317 NewOps.push_back(H);
318 for (++i; i != e; ++i)
319 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000320 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321
Dan Gohman89f85052007-10-22 18:31:58 +0000322 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 }
324 }
325 return this;
326}
327
328
329bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000330 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohman2d888d82009-06-26 22:17:21 +0000331 if (!QueryLoop)
332 return false;
333
334 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
335 if (QueryLoop->contains(L->getHeader()))
336 return false;
337
338 // This recurrence is variant w.r.t. QueryLoop if any of its operands
339 // are variant.
340 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
341 if (!getOperand(i)->isLoopInvariant(QueryLoop))
342 return false;
343
344 // Otherwise it's loop-invariant.
345 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346}
347
348
Dan Gohman13058cc2009-04-21 00:47:46 +0000349void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 OS << "{" << *Operands[0];
351 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
352 OS << ",+," << *Operands[i];
353 OS << "}<" << L->getHeader()->getName() + ">";
354}
355
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
357 // All non-instruction values are loop invariant. All instructions are loop
358 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000359 // Instructions are never considered invariant in the function body
360 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000362 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 return true;
364}
365
Evan Cheng98c073b2009-02-17 00:13:06 +0000366bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
367 if (Instruction *I = dyn_cast<Instruction>(getValue()))
368 return DT->dominates(I->getParent(), BB);
369 return true;
370}
371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372const Type *SCEVUnknown::getType() const {
373 return V->getType();
374}
375
Dan Gohman13058cc2009-04-21 00:47:46 +0000376void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 WriteAsOperand(OS, V, false);
378}
379
380//===----------------------------------------------------------------------===//
381// SCEV Utilities
382//===----------------------------------------------------------------------===//
383
384namespace {
385 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
386 /// than the complexity of the RHS. This comparator is used to canonicalize
387 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000388 class VISIBILITY_HIDDEN SCEVComplexityCompare {
389 LoopInfo *LI;
390 public:
391 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
392
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000393 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000394 // Primarily, sort the SCEVs by their getSCEVType().
395 if (LHS->getSCEVType() != RHS->getSCEVType())
396 return LHS->getSCEVType() < RHS->getSCEVType();
397
398 // Aside from the getSCEVType() ordering, the particular ordering
399 // isn't very important except that it's beneficial to be consistent,
400 // so that (a + b) and (b + a) don't end up as different expressions.
401
402 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
403 // not as complete as it could be.
404 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
405 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
406
Dan Gohmand0c01232009-05-19 02:15:55 +0000407 // Order pointer values after integer values. This helps SCEVExpander
408 // form GEPs.
409 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
410 return false;
411 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
412 return true;
413
Dan Gohman5d486452009-05-07 14:39:04 +0000414 // Compare getValueID values.
415 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
416 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
417
418 // Sort arguments by their position.
419 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
420 const Argument *RA = cast<Argument>(RU->getValue());
421 return LA->getArgNo() < RA->getArgNo();
422 }
423
424 // For instructions, compare their loop depth, and their opcode.
425 // This is pretty loose.
426 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
427 Instruction *RV = cast<Instruction>(RU->getValue());
428
429 // Compare loop depths.
430 if (LI->getLoopDepth(LV->getParent()) !=
431 LI->getLoopDepth(RV->getParent()))
432 return LI->getLoopDepth(LV->getParent()) <
433 LI->getLoopDepth(RV->getParent());
434
435 // Compare opcodes.
436 if (LV->getOpcode() != RV->getOpcode())
437 return LV->getOpcode() < RV->getOpcode();
438
439 // Compare the number of operands.
440 if (LV->getNumOperands() != RV->getNumOperands())
441 return LV->getNumOperands() < RV->getNumOperands();
442 }
443
444 return false;
445 }
446
Dan Gohman56fc8f12009-06-14 22:51:25 +0000447 // Compare constant values.
448 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
449 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
450 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
451 }
452
453 // Compare addrec loop depths.
454 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
455 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
456 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
457 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
458 }
Dan Gohman5d486452009-05-07 14:39:04 +0000459
460 // Lexicographically compare n-ary expressions.
461 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
462 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
463 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
464 if (i >= RC->getNumOperands())
465 return false;
466 if (operator()(LC->getOperand(i), RC->getOperand(i)))
467 return true;
468 if (operator()(RC->getOperand(i), LC->getOperand(i)))
469 return false;
470 }
471 return LC->getNumOperands() < RC->getNumOperands();
472 }
473
Dan Gohman6e10db12009-05-07 19:23:21 +0000474 // Lexicographically compare udiv expressions.
475 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
476 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
477 if (operator()(LC->getLHS(), RC->getLHS()))
478 return true;
479 if (operator()(RC->getLHS(), LC->getLHS()))
480 return false;
481 if (operator()(LC->getRHS(), RC->getRHS()))
482 return true;
483 if (operator()(RC->getRHS(), LC->getRHS()))
484 return false;
485 return false;
486 }
487
Dan Gohman5d486452009-05-07 14:39:04 +0000488 // Compare cast expressions by operand.
489 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
490 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
491 return operator()(LC->getOperand(), RC->getOperand());
492 }
493
494 assert(0 && "Unknown SCEV kind!");
495 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496 }
497 };
498}
499
500/// GroupByComplexity - Given a list of SCEV objects, order them by their
501/// complexity, and group objects of the same complexity together by value.
502/// When this routine is finished, we know that any duplicates in the vector are
503/// consecutive and that complexity is monotonically increasing.
504///
505/// Note that we go take special precautions to ensure that we get determinstic
506/// results from this routine. In other words, we don't want the results of
507/// this to depend on where the addresses of various SCEV objects happened to
508/// land in memory.
509///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000510static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000511 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512 if (Ops.size() < 2) return; // Noop
513 if (Ops.size() == 2) {
514 // This is the common case, which also happens to be trivially simple.
515 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000516 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 std::swap(Ops[0], Ops[1]);
518 return;
519 }
520
521 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000522 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523
524 // Now that we are sorted by complexity, group elements of the same
525 // complexity. Note that this is, at worst, N^2, but the vector is likely to
526 // be extremely short in practice. Note that we take this approach because we
527 // do not want to depend on the addresses of the objects we are grouping.
528 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000529 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 unsigned Complexity = S->getSCEVType();
531
532 // If there are any objects of the same complexity and same value as this
533 // one, group them.
534 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
535 if (Ops[j] == S) { // Found a duplicate.
536 // Move it to immediately after i'th element.
537 std::swap(Ops[i+1], Ops[j]);
538 ++i; // no need to rescan it.
539 if (i == e-2) return; // Done!
540 }
541 }
542 }
543}
544
545
546
547//===----------------------------------------------------------------------===//
548// Simple SCEV method implementations
549//===----------------------------------------------------------------------===//
550
Eli Friedman7489ec92008-08-04 23:49:06 +0000551/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000552/// Assume, K > 0.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000553static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000554 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000555 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000556 // Handle the simplest case efficiently.
557 if (K == 1)
558 return SE.getTruncateOrZeroExtend(It, ResultTy);
559
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000560 // We are using the following formula for BC(It, K):
561 //
562 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
563 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000564 // Suppose, W is the bitwidth of the return value. We must be prepared for
565 // overflow. Hence, we must assure that the result of our computation is
566 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
567 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000568 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000569 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman9bc642f2009-06-24 04:48:43 +0000570 // is something like the following, where T is the number of factors of 2 in
Eli Friedman7489ec92008-08-04 23:49:06 +0000571 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
572 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000573 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000574 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000575 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000576 // This formula is trivially equivalent to the previous formula. However,
577 // this formula can be implemented much more efficiently. The trick is that
578 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
579 // arithmetic. To do exact division in modular arithmetic, all we have
580 // to do is multiply by the inverse. Therefore, this step can be done at
581 // width W.
Dan Gohman9bc642f2009-06-24 04:48:43 +0000582 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000583 // The next issue is how to safely do the division by 2^T. The way this
584 // is done is by doing the multiplication step at a width of at least W + T
585 // bits. This way, the bottom W+T bits of the product are accurate. Then,
586 // when we perform the division by 2^T (which is equivalent to a right shift
587 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
588 // truncated out after the division by 2^T.
589 //
590 // In comparison to just directly using the first formula, this technique
591 // is much more efficient; using the first formula requires W * K bits,
592 // but this formula less than W + K bits. Also, the first formula requires
593 // a division step, whereas this formula only requires multiplies and shifts.
594 //
595 // It doesn't matter whether the subtraction step is done in the calculation
596 // width or the input iteration count's width; if the subtraction overflows,
597 // the result must be zero anyway. We prefer here to do it in the width of
598 // the induction variable because it helps a lot for certain cases; CodeGen
599 // isn't smart enough to ignore the overflow, which leads to much less
600 // efficient code if the width of the subtraction is wider than the native
601 // register width.
602 //
603 // (It's possible to not widen at all by pulling out factors of 2 before
604 // the multiplication; for example, K=2 can be calculated as
605 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
606 // extra arithmetic, so it's not an obvious win, and it gets
607 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000608
Eli Friedman7489ec92008-08-04 23:49:06 +0000609 // Protection from insane SCEVs; this bound is conservative,
610 // but it probably doesn't matter.
611 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000612 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000613
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000614 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000615
Eli Friedman7489ec92008-08-04 23:49:06 +0000616 // Calculate K! / 2^T and T; we divide out the factors of two before
617 // multiplying for calculating K! / 2^T to avoid overflow.
618 // Other overflow doesn't matter because we only care about the bottom
619 // W bits of the result.
620 APInt OddFactorial(W, 1);
621 unsigned T = 1;
622 for (unsigned i = 3; i <= K; ++i) {
623 APInt Mult(W, i);
624 unsigned TwoFactors = Mult.countTrailingZeros();
625 T += TwoFactors;
626 Mult = Mult.lshr(TwoFactors);
627 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000629
Eli Friedman7489ec92008-08-04 23:49:06 +0000630 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000631 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000632
633 // Calcuate 2^T, at width T+W.
634 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
635
636 // Calculate the multiplicative inverse of K! / 2^T;
637 // this multiplication factor will perform the exact division by
638 // K! / 2^T.
639 APInt Mod = APInt::getSignedMinValue(W+1);
640 APInt MultiplyFactor = OddFactorial.zext(W+1);
641 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
642 MultiplyFactor = MultiplyFactor.trunc(W);
643
644 // Calculate the product, at width T+W
645 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Owen Andersonecd0cd72009-06-22 21:39:50 +0000646 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000647 for (unsigned i = 1; i != K; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000648 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000649 Dividend = SE.getMulExpr(Dividend,
650 SE.getTruncateOrZeroExtend(S, CalculationTy));
651 }
652
653 // Divide by 2^T
Owen Andersonecd0cd72009-06-22 21:39:50 +0000654 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000655
656 // Truncate the result, and divide by K! / 2^T.
657
658 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
659 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660}
661
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662/// evaluateAtIteration - Return the value of this chain of recurrences at
663/// the specified iteration number. We can evaluate this recurrence by
664/// multiplying each element in the chain by the binomial coefficient
665/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
666///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000667/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000669/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000671const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It,
Dan Gohman89f85052007-10-22 18:31:58 +0000672 ScalarEvolution &SE) const {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000673 const SCEV* Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000675 // The computation is correct in the face of overflow provided that the
676 // multiplication is performed _after_ the evaluation of the binomial
677 // coefficient.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000678 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000679 if (isa<SCEVCouldNotCompute>(Coeff))
680 return Coeff;
681
682 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 }
684 return Result;
685}
686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687//===----------------------------------------------------------------------===//
688// SCEV Expression folder implementations
689//===----------------------------------------------------------------------===//
690
Owen Andersonecd0cd72009-06-22 21:39:50 +0000691const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op,
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000692 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000693 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000694 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000695 assert(isSCEVable(Ty) &&
696 "This is not a conversion to a SCEVable type!");
697 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000698
Dan Gohmanc76b5452009-05-04 22:02:23 +0000699 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000700 return getConstant(
701 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702
Dan Gohman1a5c4992009-04-22 16:20:48 +0000703 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000704 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000705 return getTruncateExpr(ST->getOperand(), Ty);
706
Nick Lewycky37d04642009-04-23 05:15:08 +0000707 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000708 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000709 return getTruncateOrSignExtend(SS->getOperand(), Ty);
710
711 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000712 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000713 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
714
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000715 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000716 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000717 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000719 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
720 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 }
722
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000723 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000724 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 return Result;
726}
727
Owen Andersonecd0cd72009-06-22 21:39:50 +0000728const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op,
Dan Gohman36d40922009-04-16 19:25:55 +0000729 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000730 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000731 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000732 assert(isSCEVable(Ty) &&
733 "This is not a conversion to a SCEVable type!");
734 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000735
Dan Gohmanc76b5452009-05-04 22:02:23 +0000736 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000737 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000738 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
739 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000740 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000741 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742
Dan Gohman1a5c4992009-04-22 16:20:48 +0000743 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000744 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000745 return getZeroExtendExpr(SZ->getOperand(), Ty);
746
Dan Gohmana9dba962009-04-27 20:16:15 +0000747 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000749 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000751 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000752 if (AR->isAffine()) {
753 // Check whether the backedge-taken count is SCEVCouldNotCompute.
754 // Note that this serves two purposes: It filters out loops that are
755 // simply not analyzable, and it covers the case where this code is
756 // being called from within backedge-taken count analysis, such that
757 // attempting to ask for the backedge-taken count would likely result
758 // in infinite recursion. In the later case, the analysis code will
759 // cope with a conservative value, and it will take care to purge
760 // that value once it has finished.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000761 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000762 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000763 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000764 // overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000765 const SCEV* Start = AR->getStart();
766 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000767
768 // Check whether the backedge-taken count can be losslessly casted to
769 // the addrec's type. The count is always unsigned.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000770 const SCEV* CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000771 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +0000772 const SCEV* RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000773 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
774 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000775 const Type *WideTy =
776 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000777 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000778 const SCEV* ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000779 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000780 getTruncateOrZeroExtend(Step, Start->getType()));
Owen Andersonecd0cd72009-06-22 21:39:50 +0000781 const SCEV* Add = getAddExpr(Start, ZMul);
782 const SCEV* OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000783 getAddExpr(getZeroExtendExpr(Start, WideTy),
784 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
785 getZeroExtendExpr(Step, WideTy)));
786 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000787 // Return the expression with the addrec on the outside.
788 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
789 getZeroExtendExpr(Step, Ty),
790 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000791
792 // Similar to above, only this time treat the step value as signed.
793 // This covers loops that count down.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000794 const SCEV* SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000795 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000796 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000797 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000798 OperandExtendedAdd =
799 getAddExpr(getZeroExtendExpr(Start, WideTy),
800 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
801 getSignExtendExpr(Step, WideTy)));
802 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000803 // Return the expression with the addrec on the outside.
804 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
805 getSignExtendExpr(Step, Ty),
806 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000807 }
808 }
809 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000811 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000812 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 return Result;
814}
815
Owen Andersonecd0cd72009-06-22 21:39:50 +0000816const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op,
Dan Gohmana9dba962009-04-27 20:16:15 +0000817 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000818 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000819 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000820 assert(isSCEVable(Ty) &&
821 "This is not a conversion to a SCEVable type!");
822 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000823
Dan Gohmanc76b5452009-05-04 22:02:23 +0000824 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000825 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000826 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
827 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000828 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000829 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000830
Dan Gohman1a5c4992009-04-22 16:20:48 +0000831 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000832 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000833 return getSignExtendExpr(SS->getOperand(), Ty);
834
Dan Gohmana9dba962009-04-27 20:16:15 +0000835 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000837 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000839 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000840 if (AR->isAffine()) {
841 // Check whether the backedge-taken count is SCEVCouldNotCompute.
842 // Note that this serves two purposes: It filters out loops that are
843 // simply not analyzable, and it covers the case where this code is
844 // being called from within backedge-taken count analysis, such that
845 // attempting to ask for the backedge-taken count would likely result
846 // in infinite recursion. In the later case, the analysis code will
847 // cope with a conservative value, and it will take care to purge
848 // that value once it has finished.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000849 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000850 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000851 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000852 // overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000853 const SCEV* Start = AR->getStart();
854 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000855
856 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000857 // the addrec's type. The count is always unsigned.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000858 const SCEV* CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000859 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +0000860 const SCEV* RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000861 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
862 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000863 const Type *WideTy =
864 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000865 // Check whether Start+Step*MaxBECount has no signed overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000866 const SCEV* SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000867 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000868 getTruncateOrSignExtend(Step, Start->getType()));
Owen Andersonecd0cd72009-06-22 21:39:50 +0000869 const SCEV* Add = getAddExpr(Start, SMul);
870 const SCEV* OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000871 getAddExpr(getSignExtendExpr(Start, WideTy),
872 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
873 getSignExtendExpr(Step, WideTy)));
874 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000875 // Return the expression with the addrec on the outside.
876 return getAddRecExpr(getSignExtendExpr(Start, Ty),
877 getSignExtendExpr(Step, Ty),
878 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000879 }
880 }
881 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000883 SCEVSignExtendExpr *&Result = SCEVSignExtends[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000884 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885 return Result;
886}
887
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000888/// getAnyExtendExpr - Return a SCEV for the given operand extended with
889/// unspecified bits out to the given type.
890///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000891const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000892 const Type *Ty) {
893 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
894 "This is not an extending conversion!");
895 assert(isSCEVable(Ty) &&
896 "This is not a conversion to a SCEVable type!");
897 Ty = getEffectiveSCEVType(Ty);
898
899 // Sign-extend negative constants.
900 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
901 if (SC->getValue()->getValue().isNegative())
902 return getSignExtendExpr(Op, Ty);
903
904 // Peel off a truncate cast.
905 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000906 const SCEV* NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000907 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
908 return getAnyExtendExpr(NewOp, Ty);
909 return getTruncateOrNoop(NewOp, Ty);
910 }
911
912 // Next try a zext cast. If the cast is folded, use it.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000913 const SCEV* ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000914 if (!isa<SCEVZeroExtendExpr>(ZExt))
915 return ZExt;
916
917 // Next try a sext cast. If the cast is folded, use it.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000918 const SCEV* SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000919 if (!isa<SCEVSignExtendExpr>(SExt))
920 return SExt;
921
922 // If the expression is obviously signed, use the sext cast value.
923 if (isa<SCEVSMaxExpr>(Op))
924 return SExt;
925
926 // Absent any other information, use the zext cast value.
927 return ZExt;
928}
929
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000930/// CollectAddOperandsWithScales - Process the given Ops list, which is
931/// a list of operands to be added under the given scale, update the given
932/// map. This is a helper function for getAddRecExpr. As an example of
933/// what it does, given a sequence of operands that would form an add
934/// expression like this:
935///
936/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
937///
938/// where A and B are constants, update the map with these values:
939///
940/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
941///
942/// and add 13 + A*B*29 to AccumulatedConstant.
943/// This will allow getAddRecExpr to produce this:
944///
945/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
946///
947/// This form often exposes folding opportunities that are hidden in
948/// the original operand list.
949///
950/// Return true iff it appears that any interesting folding opportunities
951/// may be exposed. This helps getAddRecExpr short-circuit extra work in
952/// the common case where no interesting opportunities are present, and
953/// is also used as a check to avoid infinite recursion.
954///
955static bool
Owen Andersonecd0cd72009-06-22 21:39:50 +0000956CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M,
957 SmallVector<const SCEV*, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000958 APInt &AccumulatedConstant,
Owen Andersonecd0cd72009-06-22 21:39:50 +0000959 const SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000960 const APInt &Scale,
961 ScalarEvolution &SE) {
962 bool Interesting = false;
963
964 // Iterate over the add operands.
965 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
966 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
967 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
968 APInt NewScale =
969 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
970 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
971 // A multiplication of a constant with another add; recurse.
972 Interesting |=
973 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
974 cast<SCEVAddExpr>(Mul->getOperand(1))
975 ->getOperands(),
976 NewScale, SE);
977 } else {
978 // A multiplication of a constant with some other value. Update
979 // the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000980 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
981 const SCEV* Key = SE.getMulExpr(MulOps);
982 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000983 M.insert(std::make_pair(Key, APInt()));
984 if (Pair.second) {
985 Pair.first->second = NewScale;
986 NewOps.push_back(Pair.first->first);
987 } else {
988 Pair.first->second += NewScale;
989 // The map already had an entry for this value, which may indicate
990 // a folding opportunity.
991 Interesting = true;
992 }
993 }
994 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
995 // Pull a buried constant out to the outside.
996 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
997 Interesting = true;
998 AccumulatedConstant += Scale * C->getValue()->getValue();
999 } else {
1000 // An ordinary operand. Update the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001001 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001002 M.insert(std::make_pair(Ops[i], APInt()));
1003 if (Pair.second) {
1004 Pair.first->second = Scale;
1005 NewOps.push_back(Pair.first->first);
1006 } else {
1007 Pair.first->second += Scale;
1008 // The map already had an entry for this value, which may indicate
1009 // a folding opportunity.
1010 Interesting = true;
1011 }
1012 }
1013 }
1014
1015 return Interesting;
1016}
1017
1018namespace {
1019 struct APIntCompare {
1020 bool operator()(const APInt &LHS, const APInt &RHS) const {
1021 return LHS.ult(RHS);
1022 }
1023 };
1024}
1025
Dan Gohmanc8a29272009-05-24 23:45:28 +00001026/// getAddExpr - Get a canonical add expression, or something simpler if
1027/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001028const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 assert(!Ops.empty() && "Cannot get empty add!");
1030 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001031#ifndef NDEBUG
1032 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1033 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1034 getEffectiveSCEVType(Ops[0]->getType()) &&
1035 "SCEVAddExpr operand types don't match!");
1036#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037
1038 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001039 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040
1041 // If there are any constants, fold them together.
1042 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001043 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 ++Idx;
1045 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001046 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001048 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1049 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001050 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001051 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001052 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 }
1054
1055 // If we are left with a constant zero being added, strip it off.
1056 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1057 Ops.erase(Ops.begin());
1058 --Idx;
1059 }
1060 }
1061
1062 if (Ops.size() == 1) return Ops[0];
1063
1064 // Okay, check to see if the same value occurs in the operand list twice. If
1065 // so, merge them together into an multiply expression. Since we sorted the
1066 // list, these values are required to be adjacent.
1067 const Type *Ty = Ops[0]->getType();
1068 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1069 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1070 // Found a match, merge the two values into a multiply, and add any
1071 // remaining values to the result.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001072 const SCEV* Two = getIntegerSCEV(2, Ty);
1073 const SCEV* Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 if (Ops.size() == 2)
1075 return Mul;
1076 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1077 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001078 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 }
1080
Dan Gohman45b3b542009-05-08 21:03:19 +00001081 // Check for truncates. If all the operands are truncated from the same
1082 // type, see if factoring out the truncate would permit the result to be
1083 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1084 // if the contents of the resulting outer trunc fold to something simple.
1085 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1086 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1087 const Type *DstType = Trunc->getType();
1088 const Type *SrcType = Trunc->getOperand()->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00001089 SmallVector<const SCEV*, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001090 bool Ok = true;
1091 // Check all the operands to see if they can be represented in the
1092 // source type of the truncate.
1093 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1094 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1095 if (T->getOperand()->getType() != SrcType) {
1096 Ok = false;
1097 break;
1098 }
1099 LargeOps.push_back(T->getOperand());
1100 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1101 // This could be either sign or zero extension, but sign extension
1102 // is much more likely to be foldable here.
1103 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1104 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001105 SmallVector<const SCEV*, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001106 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1107 if (const SCEVTruncateExpr *T =
1108 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1109 if (T->getOperand()->getType() != SrcType) {
1110 Ok = false;
1111 break;
1112 }
1113 LargeMulOps.push_back(T->getOperand());
1114 } else if (const SCEVConstant *C =
1115 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1116 // This could be either sign or zero extension, but sign extension
1117 // is much more likely to be foldable here.
1118 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1119 } else {
1120 Ok = false;
1121 break;
1122 }
1123 }
1124 if (Ok)
1125 LargeOps.push_back(getMulExpr(LargeMulOps));
1126 } else {
1127 Ok = false;
1128 break;
1129 }
1130 }
1131 if (Ok) {
1132 // Evaluate the expression in the larger type.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001133 const SCEV* Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001134 // If it folds to something simple, use it. Otherwise, don't.
1135 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1136 return getTruncateExpr(Fold, DstType);
1137 }
1138 }
1139
1140 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1142 ++Idx;
1143
1144 // If there are add operands they would be next.
1145 if (Idx < Ops.size()) {
1146 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001147 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 // If we have an add, expand the add operands onto the end of the operands
1149 // list.
1150 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1151 Ops.erase(Ops.begin()+Idx);
1152 DeletedAdd = true;
1153 }
1154
1155 // If we deleted at least one add, we added operands to the end of the list,
1156 // and they are not necessarily sorted. Recurse to resort and resimplify
1157 // any operands we just aquired.
1158 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001159 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 }
1161
1162 // Skip over the add expression until we get to a multiply.
1163 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1164 ++Idx;
1165
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001166 // Check to see if there are any folding opportunities present with
1167 // operands multiplied by constant values.
1168 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1169 uint64_t BitWidth = getTypeSizeInBits(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001170 DenseMap<const SCEV*, APInt> M;
1171 SmallVector<const SCEV*, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001172 APInt AccumulatedConstant(BitWidth, 0);
1173 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1174 Ops, APInt(BitWidth, 1), *this)) {
1175 // Some interesting folding opportunity is present, so its worthwhile to
1176 // re-generate the operands list. Group the operands by constant scale,
1177 // to avoid multiplying by the same constant scale multiple times.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001178 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1179 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001180 E = NewOps.end(); I != E; ++I)
1181 MulOpLists[M.find(*I)->second].push_back(*I);
1182 // Re-generate the operands list.
1183 Ops.clear();
1184 if (AccumulatedConstant != 0)
1185 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001186 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1187 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001188 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001189 Ops.push_back(getMulExpr(getConstant(I->first),
1190 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001191 if (Ops.empty())
1192 return getIntegerSCEV(0, Ty);
1193 if (Ops.size() == 1)
1194 return Ops[0];
1195 return getAddExpr(Ops);
1196 }
1197 }
1198
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001199 // If we are adding something to a multiply expression, make sure the
1200 // something is not already an operand of the multiply. If so, merge it into
1201 // the multiply.
1202 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001203 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001205 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001207 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001209 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 if (Mul->getNumOperands() != 2) {
1211 // If the multiply has more than two operands, we must get the
1212 // Y*Z term.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001213 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001215 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001217 const SCEV* One = getIntegerSCEV(1, Ty);
1218 const SCEV* AddOne = getAddExpr(InnerMul, One);
1219 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 if (Ops.size() == 2) return OuterMul;
1221 if (AddOp < Idx) {
1222 Ops.erase(Ops.begin()+AddOp);
1223 Ops.erase(Ops.begin()+Idx-1);
1224 } else {
1225 Ops.erase(Ops.begin()+Idx);
1226 Ops.erase(Ops.begin()+AddOp-1);
1227 }
1228 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001229 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 }
1231
1232 // Check this multiply against other multiplies being added together.
1233 for (unsigned OtherMulIdx = Idx+1;
1234 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1235 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001236 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 // If MulOp occurs in OtherMul, we can fold the two multiplies
1238 // together.
1239 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1240 OMulOp != e; ++OMulOp)
1241 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1242 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001243 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001245 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1246 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001248 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001250 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001252 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1253 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001255 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001257 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1258 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 if (Ops.size() == 2) return OuterMul;
1260 Ops.erase(Ops.begin()+Idx);
1261 Ops.erase(Ops.begin()+OtherMulIdx-1);
1262 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001263 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 }
1265 }
1266 }
1267 }
1268
1269 // If there are any add recurrences in the operands list, see if any other
1270 // added values are loop invariant. If so, we can fold them into the
1271 // recurrence.
1272 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1273 ++Idx;
1274
1275 // Scan over all recurrences, trying to fold loop invariants into them.
1276 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1277 // Scan all of the other operands to this add and add them to the vector if
1278 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001279 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001280 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1282 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1283 LIOps.push_back(Ops[i]);
1284 Ops.erase(Ops.begin()+i);
1285 --i; --e;
1286 }
1287
1288 // If we found some loop invariants, fold them into the recurrence.
1289 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001290 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291 LIOps.push_back(AddRec->getStart());
1292
Owen Andersonecd0cd72009-06-22 21:39:50 +00001293 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001294 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001295 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296
Owen Andersonecd0cd72009-06-22 21:39:50 +00001297 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298 // If all of the other operands were loop invariant, we are done.
1299 if (Ops.size() == 1) return NewRec;
1300
1301 // Otherwise, add the folded AddRec by the non-liv parts.
1302 for (unsigned i = 0;; ++i)
1303 if (Ops[i] == AddRec) {
1304 Ops[i] = NewRec;
1305 break;
1306 }
Dan Gohman89f85052007-10-22 18:31:58 +00001307 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308 }
1309
1310 // Okay, if there weren't any loop invariants to be folded, check to see if
1311 // there are multiple AddRec's with the same loop induction variable being
1312 // added together. If so, we can fold them.
1313 for (unsigned OtherIdx = Idx+1;
1314 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1315 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001316 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1318 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001319 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1320 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1322 if (i >= NewOps.size()) {
1323 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1324 OtherAddRec->op_end());
1325 break;
1326 }
Dan Gohman89f85052007-10-22 18:31:58 +00001327 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001329 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330
1331 if (Ops.size() == 2) return NewAddRec;
1332
1333 Ops.erase(Ops.begin()+Idx);
1334 Ops.erase(Ops.begin()+OtherIdx-1);
1335 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001336 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 }
1338 }
1339
1340 // Otherwise couldn't fold anything into this recurrence. Move onto the
1341 // next one.
1342 }
1343
1344 // Okay, it looks like we really DO need an add expr. Check to see if we
1345 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001346 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001347 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001348 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001349 if (Result == 0) Result = new SCEVAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 return Result;
1351}
1352
1353
Dan Gohmanc8a29272009-05-24 23:45:28 +00001354/// getMulExpr - Get a canonical multiply expression, or something simpler if
1355/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001356const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001358#ifndef NDEBUG
1359 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1360 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1361 getEffectiveSCEVType(Ops[0]->getType()) &&
1362 "SCEVMulExpr operand types don't match!");
1363#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364
1365 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001366 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367
1368 // If there are any constants, fold them together.
1369 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001370 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371
1372 // C1*(C2+V) -> C1*C2 + C1*V
1373 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001374 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001375 if (Add->getNumOperands() == 2 &&
1376 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001377 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1378 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001379
1380
1381 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001382 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 // We found two constants, fold them together!
Dan Gohman9bc642f2009-06-24 04:48:43 +00001384 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001385 RHSC->getValue()->getValue());
1386 Ops[0] = getConstant(Fold);
1387 Ops.erase(Ops.begin()+1); // Erase the folded element
1388 if (Ops.size() == 1) return Ops[0];
1389 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 }
1391
1392 // If we are left with a constant one being multiplied, strip it off.
1393 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1394 Ops.erase(Ops.begin());
1395 --Idx;
1396 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1397 // If we have a multiply of zero, it will always be zero.
1398 return Ops[0];
1399 }
1400 }
1401
1402 // Skip over the add expression until we get to a multiply.
1403 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1404 ++Idx;
1405
1406 if (Ops.size() == 1)
1407 return Ops[0];
1408
1409 // If there are mul operands inline them all into this expression.
1410 if (Idx < Ops.size()) {
1411 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001412 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413 // If we have an mul, expand the mul operands onto the end of the operands
1414 // list.
1415 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1416 Ops.erase(Ops.begin()+Idx);
1417 DeletedMul = true;
1418 }
1419
1420 // If we deleted at least one mul, we added operands to the end of the list,
1421 // and they are not necessarily sorted. Recurse to resort and resimplify
1422 // any operands we just aquired.
1423 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001424 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 }
1426
1427 // If there are any add recurrences in the operands list, see if any other
1428 // added values are loop invariant. If so, we can fold them into the
1429 // recurrence.
1430 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1431 ++Idx;
1432
1433 // Scan over all recurrences, trying to fold loop invariants into them.
1434 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1435 // Scan all of the other operands to this mul and add them to the vector if
1436 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001437 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001438 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1440 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1441 LIOps.push_back(Ops[i]);
1442 Ops.erase(Ops.begin()+i);
1443 --i; --e;
1444 }
1445
1446 // If we found some loop invariants, fold them into the recurrence.
1447 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001448 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Owen Andersonecd0cd72009-06-22 21:39:50 +00001449 SmallVector<const SCEV*, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 NewOps.reserve(AddRec->getNumOperands());
1451 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001452 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001454 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 } else {
1456 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001457 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001459 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460 }
1461 }
1462
Owen Andersonecd0cd72009-06-22 21:39:50 +00001463 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464
1465 // If all of the other operands were loop invariant, we are done.
1466 if (Ops.size() == 1) return NewRec;
1467
1468 // Otherwise, multiply the folded AddRec by the non-liv parts.
1469 for (unsigned i = 0;; ++i)
1470 if (Ops[i] == AddRec) {
1471 Ops[i] = NewRec;
1472 break;
1473 }
Dan Gohman89f85052007-10-22 18:31:58 +00001474 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475 }
1476
1477 // Okay, if there weren't any loop invariants to be folded, check to see if
1478 // there are multiple AddRec's with the same loop induction variable being
1479 // multiplied together. If so, we can fold them.
1480 for (unsigned OtherIdx = Idx+1;
1481 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1482 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001483 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1485 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001486 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001487 const SCEV* NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001488 G->getStart());
Owen Andersonecd0cd72009-06-22 21:39:50 +00001489 const SCEV* B = F->getStepRecurrence(*this);
1490 const SCEV* D = G->getStepRecurrence(*this);
1491 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001492 getMulExpr(G, B),
1493 getMulExpr(B, D));
Owen Andersonecd0cd72009-06-22 21:39:50 +00001494 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001495 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496 if (Ops.size() == 2) return NewAddRec;
1497
1498 Ops.erase(Ops.begin()+Idx);
1499 Ops.erase(Ops.begin()+OtherIdx-1);
1500 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001501 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001502 }
1503 }
1504
1505 // Otherwise couldn't fold anything into this recurrence. Move onto the
1506 // next one.
1507 }
1508
1509 // Okay, it looks like we really DO need an mul expr. Check to see if we
1510 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001511 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001512 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 SCEVOps)];
1514 if (Result == 0)
Owen Andersonb70139d2009-06-22 21:57:23 +00001515 Result = new SCEVMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 return Result;
1517}
1518
Dan Gohmanc8a29272009-05-24 23:45:28 +00001519/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1520/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001521const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1522 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001523 assert(getEffectiveSCEVType(LHS->getType()) ==
1524 getEffectiveSCEVType(RHS->getType()) &&
1525 "SCEVUDivExpr operand types don't match!");
1526
Dan Gohmanc76b5452009-05-04 22:02:23 +00001527 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001529 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001530 if (RHSC->isZero())
1531 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001533 // Determine if the division can be folded into the operands of
1534 // its operands.
1535 // TODO: Generalize this to non-constants by using known-bits information.
1536 const Type *Ty = LHS->getType();
1537 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1538 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1539 // For non-power-of-two values, effectively round the value up to the
1540 // nearest power of two.
1541 if (!RHSC->getValue()->getValue().isPowerOf2())
1542 ++MaxShiftAmt;
1543 const IntegerType *ExtTy =
1544 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1545 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1546 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1547 if (const SCEVConstant *Step =
1548 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1549 if (!Step->getValue()->getValue()
1550 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001551 getZeroExtendExpr(AR, ExtTy) ==
1552 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1553 getZeroExtendExpr(Step, ExtTy),
1554 AR->getLoop())) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001555 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001556 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1557 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1558 return getAddRecExpr(Operands, AR->getLoop());
1559 }
1560 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001561 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001562 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001563 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1564 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1565 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001566 // Find an operand that's safely divisible.
1567 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001568 const SCEV* Op = M->getOperand(i);
1569 const SCEV* Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001570 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001571 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1572 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001573 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001574 Operands[i] = Div;
1575 return getMulExpr(Operands);
1576 }
1577 }
Dan Gohman14374d32009-05-08 23:11:16 +00001578 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001579 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001580 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001581 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001582 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1583 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1584 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1585 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001586 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001587 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001588 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1589 break;
1590 Operands.push_back(Op);
1591 }
1592 if (Operands.size() == A->getNumOperands())
1593 return getAddExpr(Operands);
1594 }
Dan Gohman14374d32009-05-08 23:11:16 +00001595 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001596
1597 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001598 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599 Constant *LHSCV = LHSC->getValue();
1600 Constant *RHSCV = RHSC->getValue();
Dan Gohman55788cf2009-06-24 00:38:39 +00001601 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1602 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001603 }
1604 }
1605
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001606 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001607 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 return Result;
1609}
1610
1611
Dan Gohmanc8a29272009-05-24 23:45:28 +00001612/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1613/// Simplify the expression as much as possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001614const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1615 const SCEV* Step, const Loop *L) {
1616 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001617 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001618 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001619 if (StepChrec->getLoop() == L) {
1620 Operands.insert(Operands.end(), StepChrec->op_begin(),
1621 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001622 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001623 }
1624
1625 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001626 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001627}
1628
Dan Gohmanc8a29272009-05-24 23:45:28 +00001629/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1630/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001631const SCEV *
1632ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
1633 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001635#ifndef NDEBUG
1636 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1637 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1638 getEffectiveSCEVType(Operands[0]->getType()) &&
1639 "SCEVAddRecExpr operand types don't match!");
1640#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001641
Dan Gohman7b560c42008-06-18 16:23:07 +00001642 if (Operands.back()->isZero()) {
1643 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001644 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001645 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646
Dan Gohman42936882008-08-08 18:33:12 +00001647 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001648 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001649 const Loop* NestedLoop = NestedAR->getLoop();
1650 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001651 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001652 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001653 Operands[0] = NestedAR->getStart();
1654 NestedOperands[0] = getAddRecExpr(Operands, L);
1655 return getAddRecExpr(NestedOperands, NestedLoop);
1656 }
1657 }
1658
Dan Gohmanbff6b582009-05-04 22:30:44 +00001659 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001660 SCEVAddRecExpr *&Result = SCEVAddRecExprs[std::make_pair(L, SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001661 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001662 return Result;
1663}
1664
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001665const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1666 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001667 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001668 Ops.push_back(LHS);
1669 Ops.push_back(RHS);
1670 return getSMaxExpr(Ops);
1671}
1672
Owen Andersonecd0cd72009-06-22 21:39:50 +00001673const SCEV*
1674ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001675 assert(!Ops.empty() && "Cannot get empty smax!");
1676 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001677#ifndef NDEBUG
1678 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1679 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1680 getEffectiveSCEVType(Ops[0]->getType()) &&
1681 "SCEVSMaxExpr operand types don't match!");
1682#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001683
1684 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001685 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001686
1687 // If there are any constants, fold them together.
1688 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001689 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001690 ++Idx;
1691 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001692 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001693 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001694 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001695 APIntOps::smax(LHSC->getValue()->getValue(),
1696 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001697 Ops[0] = getConstant(Fold);
1698 Ops.erase(Ops.begin()+1); // Erase the folded element
1699 if (Ops.size() == 1) return Ops[0];
1700 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001701 }
1702
Dan Gohmand156c092009-06-24 14:46:22 +00001703 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001704 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1705 Ops.erase(Ops.begin());
1706 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001707 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1708 // If we have an smax with a constant maximum-int, it will always be
1709 // maximum-int.
1710 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001711 }
1712 }
1713
1714 if (Ops.size() == 1) return Ops[0];
1715
1716 // Find the first SMax
1717 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1718 ++Idx;
1719
1720 // Check to see if one of the operands is an SMax. If so, expand its operands
1721 // onto our operand list, and recurse to simplify.
1722 if (Idx < Ops.size()) {
1723 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001724 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001725 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1726 Ops.erase(Ops.begin()+Idx);
1727 DeletedSMax = true;
1728 }
1729
1730 if (DeletedSMax)
1731 return getSMaxExpr(Ops);
1732 }
1733
1734 // Okay, check to see if the same value occurs in the operand list twice. If
1735 // so, delete one. Since we sorted the list, these values are required to
1736 // be adjacent.
1737 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1738 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1739 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1740 --i; --e;
1741 }
1742
1743 if (Ops.size() == 1) return Ops[0];
1744
1745 assert(!Ops.empty() && "Reduced smax down to nothing!");
1746
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001747 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001748 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001749 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001750 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scSMaxExpr,
Nick Lewycky711640a2007-11-25 22:41:31 +00001751 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001752 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
Nick Lewycky711640a2007-11-25 22:41:31 +00001753 return Result;
1754}
1755
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001756const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1757 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001758 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001759 Ops.push_back(LHS);
1760 Ops.push_back(RHS);
1761 return getUMaxExpr(Ops);
1762}
1763
Owen Andersonecd0cd72009-06-22 21:39:50 +00001764const SCEV*
1765ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001766 assert(!Ops.empty() && "Cannot get empty umax!");
1767 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001768#ifndef NDEBUG
1769 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1770 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1771 getEffectiveSCEVType(Ops[0]->getType()) &&
1772 "SCEVUMaxExpr operand types don't match!");
1773#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001774
1775 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001776 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001777
1778 // If there are any constants, fold them together.
1779 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001780 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001781 ++Idx;
1782 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001783 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001784 // We found two constants, fold them together!
1785 ConstantInt *Fold = ConstantInt::get(
1786 APIntOps::umax(LHSC->getValue()->getValue(),
1787 RHSC->getValue()->getValue()));
1788 Ops[0] = getConstant(Fold);
1789 Ops.erase(Ops.begin()+1); // Erase the folded element
1790 if (Ops.size() == 1) return Ops[0];
1791 LHSC = cast<SCEVConstant>(Ops[0]);
1792 }
1793
Dan Gohmand156c092009-06-24 14:46:22 +00001794 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001795 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1796 Ops.erase(Ops.begin());
1797 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001798 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1799 // If we have an umax with a constant maximum-int, it will always be
1800 // maximum-int.
1801 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001802 }
1803 }
1804
1805 if (Ops.size() == 1) return Ops[0];
1806
1807 // Find the first UMax
1808 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1809 ++Idx;
1810
1811 // Check to see if one of the operands is a UMax. If so, expand its operands
1812 // onto our operand list, and recurse to simplify.
1813 if (Idx < Ops.size()) {
1814 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001815 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001816 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1817 Ops.erase(Ops.begin()+Idx);
1818 DeletedUMax = true;
1819 }
1820
1821 if (DeletedUMax)
1822 return getUMaxExpr(Ops);
1823 }
1824
1825 // Okay, check to see if the same value occurs in the operand list twice. If
1826 // so, delete one. Since we sorted the list, these values are required to
1827 // be adjacent.
1828 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1829 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1830 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1831 --i; --e;
1832 }
1833
1834 if (Ops.size() == 1) return Ops[0];
1835
1836 assert(!Ops.empty() && "Reduced umax down to nothing!");
1837
1838 // Okay, it looks like we really DO need a umax expr. Check to see if we
1839 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001840 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001841 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scUMaxExpr,
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001842 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001843 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001844 return Result;
1845}
1846
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001847const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1848 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001849 // ~smax(~x, ~y) == smin(x, y).
1850 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1851}
1852
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001853const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1854 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001855 // ~umax(~x, ~y) == umin(x, y)
1856 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1857}
1858
Owen Andersonecd0cd72009-06-22 21:39:50 +00001859const SCEV* ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001860 // Don't attempt to do anything other than create a SCEVUnknown object
1861 // here. createSCEV only calls getUnknown after checking for all other
1862 // interesting possibilities, and any other code that calls getUnknown
1863 // is doing so in order to hide a value from SCEV canonicalization.
1864
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001865 SCEVUnknown *&Result = SCEVUnknowns[V];
Owen Andersonb70139d2009-06-22 21:57:23 +00001866 if (Result == 0) Result = new SCEVUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867 return Result;
1868}
1869
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871// Basic SCEV Analysis and PHI Idiom Recognition Code
1872//
1873
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001874/// isSCEVable - Test if values of the given type are analyzable within
1875/// the SCEV framework. This primarily includes integer types, and it
1876/// can optionally include pointer types if the ScalarEvolution class
1877/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001878bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001879 // Integers are always SCEVable.
1880 if (Ty->isInteger())
1881 return true;
1882
1883 // Pointers are SCEVable if TargetData information is available
1884 // to provide pointer size information.
1885 if (isa<PointerType>(Ty))
1886 return TD != NULL;
1887
1888 // Otherwise it's not SCEVable.
1889 return false;
1890}
1891
1892/// getTypeSizeInBits - Return the size in bits of the specified type,
1893/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001894uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001895 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1896
1897 // If we have a TargetData, use it!
1898 if (TD)
1899 return TD->getTypeSizeInBits(Ty);
1900
1901 // Otherwise, we support only integer types.
1902 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1903 return Ty->getPrimitiveSizeInBits();
1904}
1905
1906/// getEffectiveSCEVType - Return a type with the same bitwidth as
1907/// the given type and which represents how SCEV will treat the given
1908/// type, for which isSCEVable must return true. For pointer types,
1909/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001910const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001911 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1912
1913 if (Ty->isInteger())
1914 return Ty;
1915
1916 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1917 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001918}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919
Owen Andersonecd0cd72009-06-22 21:39:50 +00001920const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001921 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001922}
1923
Dan Gohmand83d4af2009-05-04 22:20:30 +00001924/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001925/// computed.
1926bool ScalarEvolution::hasSCEV(Value *V) const {
1927 return Scalars.count(V);
1928}
1929
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001930/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1931/// expression and create a new one.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001932const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001933 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001934
Owen Andersonecd0cd72009-06-22 21:39:50 +00001935 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001936 if (I != Scalars.end()) return I->second;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001937 const SCEV* S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001938 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001939 return S;
1940}
1941
Dan Gohman984c78a2009-06-24 00:54:57 +00001942/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00001943/// specified signed integer value and return a SCEV for the constant.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001944const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001945 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
1946 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001947}
1948
1949/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1950///
Owen Andersonecd0cd72009-06-22 21:39:50 +00001951const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001952 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00001953 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001954
1955 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001956 Ty = getEffectiveSCEVType(Ty);
1957 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001958}
1959
1960/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Andersonecd0cd72009-06-22 21:39:50 +00001961const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001962 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00001963 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001964
1965 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001966 Ty = getEffectiveSCEVType(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001967 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001968 return getMinusSCEV(AllOnes, V);
1969}
1970
1971/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1972///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001973const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
1974 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001975 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001976 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001977}
1978
1979/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1980/// input value to the specified type. If the type must be extended, it is zero
1981/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001982const SCEV*
1983ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001984 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001985 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001986 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1987 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001988 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001989 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001990 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001991 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001992 return getTruncateExpr(V, Ty);
1993 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001994}
1995
1996/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1997/// input value to the specified type. If the type must be extended, it is sign
1998/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001999const SCEV*
2000ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002001 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002002 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002003 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2004 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002005 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002006 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002007 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002008 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002009 return getTruncateExpr(V, Ty);
2010 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002011}
2012
Dan Gohmanac959332009-05-13 03:46:30 +00002013/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2014/// input value to the specified type. If the type must be extended, it is zero
2015/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002016const SCEV*
2017ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002018 const Type *SrcTy = V->getType();
2019 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2020 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2021 "Cannot noop or zero extend with non-integer arguments!");
2022 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2023 "getNoopOrZeroExtend cannot truncate!");
2024 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2025 return V; // No conversion
2026 return getZeroExtendExpr(V, Ty);
2027}
2028
2029/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2030/// input value to the specified type. If the type must be extended, it is sign
2031/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002032const SCEV*
2033ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002034 const Type *SrcTy = V->getType();
2035 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2036 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2037 "Cannot noop or sign extend with non-integer arguments!");
2038 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2039 "getNoopOrSignExtend cannot truncate!");
2040 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2041 return V; // No conversion
2042 return getSignExtendExpr(V, Ty);
2043}
2044
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002045/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2046/// the input value to the specified type. If the type must be extended,
2047/// it is extended with unspecified bits. The conversion must not be
2048/// narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002049const SCEV*
2050ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002051 const Type *SrcTy = V->getType();
2052 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2053 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2054 "Cannot noop or any extend with non-integer arguments!");
2055 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2056 "getNoopOrAnyExtend cannot truncate!");
2057 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2058 return V; // No conversion
2059 return getAnyExtendExpr(V, Ty);
2060}
2061
Dan Gohmanac959332009-05-13 03:46:30 +00002062/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2063/// input value to the specified type. The conversion must not be widening.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002064const SCEV*
2065ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002066 const Type *SrcTy = V->getType();
2067 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2068 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2069 "Cannot truncate or noop with non-integer arguments!");
2070 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2071 "getTruncateOrNoop cannot extend!");
2072 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2073 return V; // No conversion
2074 return getTruncateExpr(V, Ty);
2075}
2076
Dan Gohman8e8b5232009-06-22 00:31:57 +00002077/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2078/// the types using zero-extension, and then perform a umax operation
2079/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002080const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2081 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002082 const SCEV* PromotedLHS = LHS;
2083 const SCEV* PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002084
2085 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2086 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2087 else
2088 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2089
2090 return getUMaxExpr(PromotedLHS, PromotedRHS);
2091}
2092
Dan Gohman9e62bb02009-06-22 15:03:27 +00002093/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2094/// the types using zero-extension, and then perform a umin operation
2095/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002096const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2097 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002098 const SCEV* PromotedLHS = LHS;
2099 const SCEV* PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002100
2101 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2102 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2103 else
2104 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2105
2106 return getUMinExpr(PromotedLHS, PromotedRHS);
2107}
2108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002109/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2110/// the specified instruction and replaces any references to the symbolic value
2111/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002112void
2113ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2114 const SCEV *SymName,
2115 const SCEV *NewVal) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002116 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002117 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002118 if (SI == Scalars.end()) return;
2119
Owen Andersonecd0cd72009-06-22 21:39:50 +00002120 const SCEV* NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002121 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002122 if (NV == SI->second) return; // No change.
2123
2124 SI->second = NV; // Update the scalars map!
2125
2126 // Any instruction values that use this instruction might also need to be
2127 // updated!
2128 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2129 UI != E; ++UI)
2130 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2131}
2132
2133/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2134/// a loop header, making it a potential recurrence, or it doesn't.
2135///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002136const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002137 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002138 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002139 if (L->getHeader() == PN->getParent()) {
2140 // If it lives in the loop header, it has two incoming values, one
2141 // from outside the loop, and one from inside.
2142 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2143 unsigned BackEdge = IncomingEdge^1;
2144
2145 // While we are analyzing this PHI node, handle its value symbolically.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002146 const SCEV* SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002147 assert(Scalars.find(PN) == Scalars.end() &&
2148 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002149 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002150
2151 // Using this symbolic name for the PHI, analyze the value coming around
2152 // the back-edge.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002153 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154
2155 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2156 // has a special value for the first iteration of the loop.
2157
2158 // If the value coming around the backedge is an add with the symbolic
2159 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002160 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161 // If there is a single occurrence of the symbolic value, replace it
2162 // with a recurrence.
2163 unsigned FoundIndex = Add->getNumOperands();
2164 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2165 if (Add->getOperand(i) == SymbolicName)
2166 if (FoundIndex == e) {
2167 FoundIndex = i;
2168 break;
2169 }
2170
2171 if (FoundIndex != Add->getNumOperands()) {
2172 // Create an add with everything but the specified operand.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002173 SmallVector<const SCEV*, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002174 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2175 if (i != FoundIndex)
2176 Ops.push_back(Add->getOperand(i));
Owen Andersonecd0cd72009-06-22 21:39:50 +00002177 const SCEV* Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178
2179 // This is not a valid addrec if the step amount is varying each
2180 // loop iteration, but is not itself an addrec in this loop.
2181 if (Accum->isLoopInvariant(L) ||
2182 (isa<SCEVAddRecExpr>(Accum) &&
2183 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002184 const SCEV *StartVal =
2185 getSCEV(PN->getIncomingValue(IncomingEdge));
2186 const SCEV *PHISCEV =
2187 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188
2189 // Okay, for the entire analysis of this edge we assumed the PHI
2190 // to be symbolic. We now need to go back and update all of the
2191 // entries for the scalars that use the PHI (except for the PHI
2192 // itself) to use the new analyzed value instead of the "symbolic"
2193 // value.
2194 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2195 return PHISCEV;
2196 }
2197 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002198 } else if (const SCEVAddRecExpr *AddRec =
2199 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002200 // Otherwise, this could be a loop like this:
2201 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2202 // In this case, j = {1,+,1} and BEValue is j.
2203 // Because the other in-value of i (0) fits the evolution of BEValue
2204 // i really is an addrec evolution.
2205 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002206 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002207
2208 // If StartVal = j.start - j.stride, we can use StartVal as the
2209 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002210 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002211 AddRec->getOperand(1))) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002212 const SCEV* PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002213 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002214
2215 // Okay, for the entire analysis of this edge we assumed the PHI
2216 // to be symbolic. We now need to go back and update all of the
2217 // entries for the scalars that use the PHI (except for the PHI
2218 // itself) to use the new analyzed value instead of the "symbolic"
2219 // value.
2220 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2221 return PHISCEV;
2222 }
2223 }
2224 }
2225
2226 return SymbolicName;
2227 }
2228
2229 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002230 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002231}
2232
Dan Gohman509cf4d2009-05-08 20:26:55 +00002233/// createNodeForGEP - Expand GEP instructions into add and multiply
2234/// operations. This allows them to be analyzed by regular SCEV code.
2235///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002236const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002237
2238 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002239 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002240 // Don't attempt to analyze GEPs over unsized objects.
2241 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2242 return getUnknown(GEP);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002243 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002244 gep_type_iterator GTI = gep_type_begin(GEP);
2245 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2246 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002247 I != E; ++I) {
2248 Value *Index = *I;
2249 // Compute the (potentially symbolic) offset in bytes for this index.
2250 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2251 // For a struct, add the member offset.
2252 const StructLayout &SL = *TD->getStructLayout(STy);
2253 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2254 uint64_t Offset = SL.getElementOffset(FieldNo);
2255 TotalOffset = getAddExpr(TotalOffset,
2256 getIntegerSCEV(Offset, IntPtrTy));
2257 } else {
2258 // For an array, add the element offset, explicitly scaled.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002259 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002260 if (!isa<PointerType>(LocalOffset->getType()))
2261 // Getelementptr indicies are signed.
2262 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2263 IntPtrTy);
2264 LocalOffset =
2265 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002266 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002267 IntPtrTy));
2268 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2269 }
2270 }
2271 return getAddExpr(getSCEV(Base), TotalOffset);
2272}
2273
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002274/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2275/// guaranteed to end in (at every loop iteration). It is, at the same time,
2276/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2277/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002278uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002279ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002280 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002281 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002282
Dan Gohmanc76b5452009-05-04 22:02:23 +00002283 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002284 return std::min(GetMinTrailingZeros(T->getOperand()),
2285 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002286
Dan Gohmanc76b5452009-05-04 22:02:23 +00002287 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002288 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2289 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2290 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002291 }
2292
Dan Gohmanc76b5452009-05-04 22:02:23 +00002293 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002294 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2295 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2296 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002297 }
2298
Dan Gohmanc76b5452009-05-04 22:02:23 +00002299 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002300 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002301 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002302 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002303 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002304 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 }
2306
Dan Gohmanc76b5452009-05-04 22:02:23 +00002307 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002308 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002309 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2310 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002311 for (unsigned i = 1, e = M->getNumOperands();
2312 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002313 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002314 BitWidth);
2315 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002317
Dan Gohmanc76b5452009-05-04 22:02:23 +00002318 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002319 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002320 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002321 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002322 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002323 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002325
Dan Gohmanc76b5452009-05-04 22:02:23 +00002326 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002327 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002328 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002329 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002330 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002331 return MinOpRes;
2332 }
2333
Dan Gohmanc76b5452009-05-04 22:02:23 +00002334 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002335 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002336 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002337 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002338 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002339 return MinOpRes;
2340 }
2341
Dan Gohman6e923a72009-06-19 23:29:04 +00002342 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2343 // For a SCEVUnknown, ask ValueTracking.
2344 unsigned BitWidth = getTypeSizeInBits(U->getType());
2345 APInt Mask = APInt::getAllOnesValue(BitWidth);
2346 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2347 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2348 return Zeros.countTrailingOnes();
2349 }
2350
2351 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002352 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002353}
2354
Dan Gohman6e923a72009-06-19 23:29:04 +00002355uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002356ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002357 // TODO: Handle other SCEV expression types here.
2358
2359 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2360 return C->getValue()->getValue().countLeadingZeros();
2361
2362 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2363 // A zero-extension cast adds zero bits.
2364 return GetMinLeadingZeros(C->getOperand()) +
2365 (getTypeSizeInBits(C->getType()) -
2366 getTypeSizeInBits(C->getOperand()->getType()));
2367 }
2368
2369 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2370 // For a SCEVUnknown, ask ValueTracking.
2371 unsigned BitWidth = getTypeSizeInBits(U->getType());
2372 APInt Mask = APInt::getAllOnesValue(BitWidth);
2373 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2374 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2375 return Zeros.countLeadingOnes();
2376 }
2377
2378 return 1;
2379}
2380
2381uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002382ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002383 // TODO: Handle other SCEV expression types here.
2384
2385 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2386 const APInt &A = C->getValue()->getValue();
2387 return A.isNegative() ? A.countLeadingOnes() :
2388 A.countLeadingZeros();
2389 }
2390
2391 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2392 // A sign-extension cast adds sign bits.
2393 return GetMinSignBits(C->getOperand()) +
2394 (getTypeSizeInBits(C->getType()) -
2395 getTypeSizeInBits(C->getOperand()->getType()));
2396 }
2397
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002398 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2399 unsigned BitWidth = getTypeSizeInBits(A->getType());
2400
2401 // Special case decrementing a value (ADD X, -1):
2402 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2403 if (CRHS->isAllOnesValue()) {
2404 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2405 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2406 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2407
2408 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2409 // sign bits set.
2410 if (LZ == BitWidth - 1)
2411 return BitWidth;
2412
2413 // If we are subtracting one from a positive number, there is no carry
2414 // out of the result.
2415 if (LZ > 0)
2416 return GetMinSignBits(OtherOpsAdd);
2417 }
2418
2419 // Add can have at most one carry bit. Thus we know that the output
2420 // is, at worst, one more bit than the inputs.
2421 unsigned Min = BitWidth;
2422 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2423 unsigned N = GetMinSignBits(A->getOperand(i));
2424 Min = std::min(Min, N) - 1;
2425 if (Min == 0) return 1;
2426 }
2427 return 1;
2428 }
2429
Dan Gohman6e923a72009-06-19 23:29:04 +00002430 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2431 // For a SCEVUnknown, ask ValueTracking.
2432 return ComputeNumSignBits(U->getValue(), TD);
2433 }
2434
2435 return 1;
2436}
2437
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002438/// createSCEV - We know that there is no SCEV for the specified value.
2439/// Analyze the expression.
2440///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002441const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002442 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002443 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002444
Dan Gohman3996f472008-06-22 19:56:46 +00002445 unsigned Opcode = Instruction::UserOp1;
2446 if (Instruction *I = dyn_cast<Instruction>(V))
2447 Opcode = I->getOpcode();
2448 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2449 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002450 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2451 return getConstant(CI);
2452 else if (isa<ConstantPointerNull>(V))
2453 return getIntegerSCEV(0, V->getType());
2454 else if (isa<UndefValue>(V))
2455 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002456 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002457 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002458
Dan Gohman3996f472008-06-22 19:56:46 +00002459 User *U = cast<User>(V);
2460 switch (Opcode) {
2461 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002462 return getAddExpr(getSCEV(U->getOperand(0)),
2463 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002464 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002465 return getMulExpr(getSCEV(U->getOperand(0)),
2466 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002467 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002468 return getUDivExpr(getSCEV(U->getOperand(0)),
2469 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002470 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002471 return getMinusSCEV(getSCEV(U->getOperand(0)),
2472 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002473 case Instruction::And:
2474 // For an expression like x&255 that merely masks off the high bits,
2475 // use zext(trunc(x)) as the SCEV expression.
2476 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002477 if (CI->isNullValue())
2478 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002479 if (CI->isAllOnesValue())
2480 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002481 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002482
2483 // Instcombine's ShrinkDemandedConstant may strip bits out of
2484 // constants, obscuring what would otherwise be a low-bits mask.
2485 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2486 // knew about to reconstruct a low-bits mask value.
2487 unsigned LZ = A.countLeadingZeros();
2488 unsigned BitWidth = A.getBitWidth();
2489 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2490 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2491 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2492
2493 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2494
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002495 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002496 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002497 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002498 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002499 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002500 }
2501 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002502
Dan Gohman3996f472008-06-22 19:56:46 +00002503 case Instruction::Or:
2504 // If the RHS of the Or is a constant, we may have something like:
2505 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2506 // optimizations will transparently handle this case.
2507 //
2508 // In order for this transformation to be safe, the LHS must be of the
2509 // form X*(2^n) and the Or constant must be less than 2^n.
2510 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002511 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002512 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002513 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002514 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002515 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002516 }
Dan Gohman3996f472008-06-22 19:56:46 +00002517 break;
2518 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002519 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002520 // If the RHS of the xor is a signbit, then this is just an add.
2521 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002522 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002523 return getAddExpr(getSCEV(U->getOperand(0)),
2524 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002525
2526 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002527 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002528 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002529
2530 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2531 // This is a variant of the check for xor with -1, and it handles
2532 // the case where instcombine has trimmed non-demanded bits out
2533 // of an xor with -1.
2534 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2535 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2536 if (BO->getOpcode() == Instruction::And &&
2537 LCI->getValue() == CI->getValue())
2538 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002539 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002540 const Type *UTy = U->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00002541 const SCEV* Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002542 const Type *Z0Ty = Z0->getType();
2543 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2544
2545 // If C is a low-bits mask, the zero extend is zerving to
2546 // mask off the high bits. Complement the operand and
2547 // re-apply the zext.
2548 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2549 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2550
2551 // If C is a single bit, it may be in the sign-bit position
2552 // before the zero-extend. In this case, represent the xor
2553 // using an add, which is equivalent, and re-apply the zext.
2554 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2555 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2556 Trunc.isSignBit())
2557 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2558 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002559 }
Dan Gohman3996f472008-06-22 19:56:46 +00002560 }
2561 break;
2562
2563 case Instruction::Shl:
2564 // Turn shift left of a constant amount into a multiply.
2565 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2566 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2567 Constant *X = ConstantInt::get(
2568 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002569 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002570 }
2571 break;
2572
Nick Lewycky7fd27892008-07-07 06:15:49 +00002573 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002574 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002575 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2576 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2577 Constant *X = ConstantInt::get(
2578 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002579 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002580 }
2581 break;
2582
Dan Gohman53bf64a2009-04-21 02:26:00 +00002583 case Instruction::AShr:
2584 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2585 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2586 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2587 if (L->getOpcode() == Instruction::Shl &&
2588 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002589 unsigned BitWidth = getTypeSizeInBits(U->getType());
2590 uint64_t Amt = BitWidth - CI->getZExtValue();
2591 if (Amt == BitWidth)
2592 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2593 if (Amt > BitWidth)
2594 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002595 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002596 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002597 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002598 U->getType());
2599 }
2600 break;
2601
Dan Gohman3996f472008-06-22 19:56:46 +00002602 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002603 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002604
2605 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002606 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002607
2608 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002609 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002610
2611 case Instruction::BitCast:
2612 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002613 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002614 return getSCEV(U->getOperand(0));
2615 break;
2616
Dan Gohman01c2ee72009-04-16 03:18:22 +00002617 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002618 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002619 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002620 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002621
2622 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002623 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002624 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2625 U->getType());
2626
Dan Gohman509cf4d2009-05-08 20:26:55 +00002627 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002628 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002629 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002630
Dan Gohman3996f472008-06-22 19:56:46 +00002631 case Instruction::PHI:
2632 return createNodeForPHI(cast<PHINode>(U));
2633
2634 case Instruction::Select:
2635 // This could be a smax or umax that was lowered earlier.
2636 // Try to recover it.
2637 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2638 Value *LHS = ICI->getOperand(0);
2639 Value *RHS = ICI->getOperand(1);
2640 switch (ICI->getPredicate()) {
2641 case ICmpInst::ICMP_SLT:
2642 case ICmpInst::ICMP_SLE:
2643 std::swap(LHS, RHS);
2644 // fall through
2645 case ICmpInst::ICMP_SGT:
2646 case ICmpInst::ICMP_SGE:
2647 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002648 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002649 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002650 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002651 break;
2652 case ICmpInst::ICMP_ULT:
2653 case ICmpInst::ICMP_ULE:
2654 std::swap(LHS, RHS);
2655 // fall through
2656 case ICmpInst::ICMP_UGT:
2657 case ICmpInst::ICMP_UGE:
2658 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002659 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002660 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002661 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002662 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002663 case ICmpInst::ICMP_NE:
2664 // n != 0 ? n : 1 -> umax(n, 1)
2665 if (LHS == U->getOperand(1) &&
2666 isa<ConstantInt>(U->getOperand(2)) &&
2667 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2668 isa<ConstantInt>(RHS) &&
2669 cast<ConstantInt>(RHS)->isZero())
2670 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2671 break;
2672 case ICmpInst::ICMP_EQ:
2673 // n == 0 ? 1 : n -> umax(n, 1)
2674 if (LHS == U->getOperand(2) &&
2675 isa<ConstantInt>(U->getOperand(1)) &&
2676 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2677 isa<ConstantInt>(RHS) &&
2678 cast<ConstantInt>(RHS)->isZero())
2679 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2680 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002681 default:
2682 break;
2683 }
2684 }
2685
2686 default: // We cannot analyze this expression.
2687 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002688 }
2689
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002690 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002691}
2692
2693
2694
2695//===----------------------------------------------------------------------===//
2696// Iteration Count Computation Code
2697//
2698
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002699/// getBackedgeTakenCount - If the specified loop has a predictable
2700/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2701/// object. The backedge-taken count is the number of times the loop header
2702/// will be branched to from within the loop. This is one less than the
2703/// trip count of the loop, since it doesn't count the first iteration,
2704/// when the header is branched to from outside the loop.
2705///
2706/// Note that it is not valid to call this method on a loop without a
2707/// loop-invariant backedge-taken count (see
2708/// hasLoopInvariantBackedgeTakenCount).
2709///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002710const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002711 return getBackedgeTakenInfo(L).Exact;
2712}
2713
2714/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2715/// return the least SCEV value that is known never to be less than the
2716/// actual backedge taken count.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002717const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002718 return getBackedgeTakenInfo(L).Max;
2719}
2720
2721const ScalarEvolution::BackedgeTakenInfo &
2722ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002723 // Initially insert a CouldNotCompute for this loop. If the insertion
2724 // succeeds, procede to actually compute a backedge-taken count and
2725 // update the value. The temporary CouldNotCompute value tells SCEV
2726 // code elsewhere that it shouldn't attempt to request a new
2727 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002728 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002729 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2730 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002731 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002732 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002733 assert(ItCount.Exact->isLoopInvariant(L) &&
2734 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735 "Computed trip count isn't loop invariant for loop!");
2736 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002737
Dan Gohmana9dba962009-04-27 20:16:15 +00002738 // Update the value in the map.
2739 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002740 } else {
2741 if (ItCount.Max != CouldNotCompute)
2742 // Update the value in the map.
2743 Pair.first->second = ItCount;
2744 if (isa<PHINode>(L->getHeader()->begin()))
2745 // Only count loops that have phi nodes as not being computable.
2746 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002747 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002748
2749 // Now that we know more about the trip count for this loop, forget any
2750 // existing SCEV values for PHI nodes in this loop since they are only
2751 // conservative estimates made without the benefit
2752 // of trip count information.
2753 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002754 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002756 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002757}
2758
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002759/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002760/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002761/// ScalarEvolution's ability to compute a trip count, or if the loop
2762/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002763void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002764 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002765 forgetLoopPHIs(L);
2766}
2767
2768/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2769/// PHI nodes in the given loop. This is used when the trip count of
2770/// the loop may have changed.
2771void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002772 BasicBlock *Header = L->getHeader();
2773
Dan Gohman9fd4a002009-05-12 01:27:58 +00002774 // Push all Loop-header PHIs onto the Worklist stack, except those
2775 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2776 // a PHI either means that it has an unrecognized structure, or it's
2777 // a PHI that's in the progress of being computed by createNodeForPHI.
2778 // In the former case, additional loop trip count information isn't
2779 // going to change anything. In the later case, createNodeForPHI will
2780 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002781 SmallVector<Instruction *, 16> Worklist;
2782 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002783 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002784 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2785 Scalars.find((Value*)I);
Dan Gohman9fd4a002009-05-12 01:27:58 +00002786 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2787 Worklist.push_back(PN);
2788 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002789
2790 while (!Worklist.empty()) {
2791 Instruction *I = Worklist.pop_back_val();
2792 if (Scalars.erase(I))
2793 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2794 UI != UE; ++UI)
2795 Worklist.push_back(cast<Instruction>(UI));
2796 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002797}
2798
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002799/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2800/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002801ScalarEvolution::BackedgeTakenInfo
2802ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002803 SmallVector<BasicBlock*, 8> ExitingBlocks;
2804 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002805
Dan Gohman8e8b5232009-06-22 00:31:57 +00002806 // Examine all exits and pick the most conservative values.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002807 const SCEV* BECount = CouldNotCompute;
2808 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002809 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002810 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2811 BackedgeTakenInfo NewBTI =
2812 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813
Dan Gohman8e8b5232009-06-22 00:31:57 +00002814 if (NewBTI.Exact == CouldNotCompute) {
2815 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002816 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002817 CouldNotComputeBECount = true;
2818 BECount = CouldNotCompute;
2819 } else if (!CouldNotComputeBECount) {
2820 if (BECount == CouldNotCompute)
2821 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002822 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00002823 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002824 }
Dan Gohman423ed6c2009-06-24 01:18:18 +00002825 if (MaxBECount == CouldNotCompute)
2826 MaxBECount = NewBTI.Max;
2827 else if (NewBTI.Max != CouldNotCompute)
2828 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002829 }
2830
2831 return BackedgeTakenInfo(BECount, MaxBECount);
2832}
2833
2834/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2835/// of the specified loop will execute if it exits via the specified block.
2836ScalarEvolution::BackedgeTakenInfo
2837ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2838 BasicBlock *ExitingBlock) {
2839
2840 // Okay, we've chosen an exiting block. See what condition causes us to
2841 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002842 //
2843 // FIXME: we should be able to handle switch instructions (with a single exit)
2844 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002845 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002846 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00002847
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002848 // At this point, we know we have a conditional branch that determines whether
2849 // the loop is exited. However, we don't know if the branch is executed each
2850 // time through the loop. If not, then the execution count of the branch will
2851 // not be equal to the trip count of the loop.
2852 //
2853 // Currently we check for this by checking to see if the Exit branch goes to
2854 // the loop header. If so, we know it will always execute the same number of
2855 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00002856 // loop header. This is common for un-rotated loops.
2857 //
2858 // If both of those tests fail, walk up the unique predecessor chain to the
2859 // header, stopping if there is an edge that doesn't exit the loop. If the
2860 // header is reached, the execution count of the branch will be equal to the
2861 // trip count of the loop.
2862 //
2863 // More extensive analysis could be done to handle more cases here.
2864 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002865 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2866 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00002867 ExitBr->getParent() != L->getHeader()) {
2868 // The simple checks failed, try climbing the unique predecessor chain
2869 // up to the header.
2870 bool Ok = false;
2871 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
2872 BasicBlock *Pred = BB->getUniquePredecessor();
2873 if (!Pred)
2874 return CouldNotCompute;
2875 TerminatorInst *PredTerm = Pred->getTerminator();
2876 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
2877 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
2878 if (PredSucc == BB)
2879 continue;
2880 // If the predecessor has a successor that isn't BB and isn't
2881 // outside the loop, assume the worst.
2882 if (L->contains(PredSucc))
2883 return CouldNotCompute;
2884 }
2885 if (Pred == L->getHeader()) {
2886 Ok = true;
2887 break;
2888 }
2889 BB = Pred;
2890 }
2891 if (!Ok)
2892 return CouldNotCompute;
2893 }
2894
2895 // Procede to the next level to examine the exit condition expression.
2896 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
2897 ExitBr->getSuccessor(0),
2898 ExitBr->getSuccessor(1));
2899}
2900
2901/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
2902/// backedge of the specified loop will execute if its exit condition
2903/// were a conditional branch of ExitCond, TBB, and FBB.
2904ScalarEvolution::BackedgeTakenInfo
2905ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
2906 Value *ExitCond,
2907 BasicBlock *TBB,
2908 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00002909 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002910 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
2911 if (BO->getOpcode() == Instruction::And) {
2912 // Recurse on the operands of the and.
2913 BackedgeTakenInfo BTI0 =
2914 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2915 BackedgeTakenInfo BTI1 =
2916 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002917 const SCEV* BECount = CouldNotCompute;
2918 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002919 if (L->contains(TBB)) {
2920 // Both conditions must be true for the loop to continue executing.
2921 // Choose the less conservative count.
Dan Gohman2cc450e2009-06-22 23:28:56 +00002922 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2923 BECount = CouldNotCompute;
Dan Gohmanac958b32009-06-22 15:09:28 +00002924 else
2925 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002926 if (BTI0.Max == CouldNotCompute)
2927 MaxBECount = BTI1.Max;
2928 else if (BTI1.Max == CouldNotCompute)
2929 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00002930 else
2931 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002932 } else {
2933 // Both conditions must be true for the loop to exit.
2934 assert(L->contains(FBB) && "Loop block has no successor in loop!");
2935 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2936 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2937 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2938 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2939 }
2940
2941 return BackedgeTakenInfo(BECount, MaxBECount);
2942 }
2943 if (BO->getOpcode() == Instruction::Or) {
2944 // Recurse on the operands of the or.
2945 BackedgeTakenInfo BTI0 =
2946 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2947 BackedgeTakenInfo BTI1 =
2948 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002949 const SCEV* BECount = CouldNotCompute;
2950 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002951 if (L->contains(FBB)) {
2952 // Both conditions must be false for the loop to continue executing.
2953 // Choose the less conservative count.
Dan Gohman2cc450e2009-06-22 23:28:56 +00002954 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2955 BECount = CouldNotCompute;
Dan Gohmanac958b32009-06-22 15:09:28 +00002956 else
2957 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002958 if (BTI0.Max == CouldNotCompute)
2959 MaxBECount = BTI1.Max;
2960 else if (BTI1.Max == CouldNotCompute)
2961 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00002962 else
2963 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002964 } else {
2965 // Both conditions must be false for the loop to exit.
2966 assert(L->contains(TBB) && "Loop block has no successor in loop!");
2967 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2968 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2969 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2970 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2971 }
2972
2973 return BackedgeTakenInfo(BECount, MaxBECount);
2974 }
2975 }
2976
2977 // With an icmp, it may be feasible to compute an exact backedge-taken count.
2978 // Procede to the next level to examine the icmp.
2979 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
2980 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981
Eli Friedman459d7292009-05-09 12:32:42 +00002982 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002983 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
2984}
2985
2986/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
2987/// backedge of the specified loop will execute if its exit condition
2988/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
2989ScalarEvolution::BackedgeTakenInfo
2990ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
2991 ICmpInst *ExitCond,
2992 BasicBlock *TBB,
2993 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002994
2995 // If the condition was exit on true, convert the condition to exit on false
2996 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002997 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998 Cond = ExitCond->getPredicate();
2999 else
3000 Cond = ExitCond->getInversePredicate();
3001
3002 // Handle common loops like: for (X = "string"; *X; ++X)
3003 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3004 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003005 const SCEV* ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003006 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003007 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3008 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3009 return BackedgeTakenInfo(ItCnt,
3010 isa<SCEVConstant>(ItCnt) ? ItCnt :
3011 getConstant(APInt::getMaxValue(BitWidth)-1));
3012 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 }
3014
Owen Andersonecd0cd72009-06-22 21:39:50 +00003015 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3016 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017
3018 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003019 LHS = getSCEVAtScope(LHS, L);
3020 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021
Dan Gohman9bc642f2009-06-24 04:48:43 +00003022 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003023 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003024 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3025 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003026 std::swap(LHS, RHS);
3027 Cond = ICmpInst::getSwappedPredicate(Cond);
3028 }
3029
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003030 // If we have a comparison of a chrec against a constant, try to use value
3031 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003032 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3033 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003034 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003035 // Form the constant range.
3036 ConstantRange CompRange(
3037 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038
Owen Andersonecd0cd72009-06-22 21:39:50 +00003039 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003040 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003041 }
3042
3043 switch (Cond) {
3044 case ICmpInst::ICMP_NE: { // while (X != Y)
3045 // Convert to: while (X-Y != 0)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003046 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3048 break;
3049 }
3050 case ICmpInst::ICMP_EQ: {
3051 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003052 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003053 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3054 break;
3055 }
3056 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003057 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3058 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003059 break;
3060 }
3061 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003062 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3063 getNotSCEV(RHS), L, true);
3064 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003065 break;
3066 }
3067 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003068 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3069 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003070 break;
3071 }
3072 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003073 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3074 getNotSCEV(RHS), L, false);
3075 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003076 break;
3077 }
3078 default:
3079#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003080 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003081 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003082 errs() << "[unsigned] ";
3083 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003084 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003085 << " " << *RHS << "\n";
3086#endif
3087 break;
3088 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003089 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003090 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003091}
3092
3093static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003094EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3095 ScalarEvolution &SE) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003096 const SCEV* InVal = SE.getConstant(C);
3097 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003098 assert(isa<SCEVConstant>(Val) &&
3099 "Evaluation of SCEV at constant didn't fold correctly?");
3100 return cast<SCEVConstant>(Val)->getValue();
3101}
3102
3103/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3104/// and a GEP expression (missing the pointer index) indexing into it, return
3105/// the addressed element of the initializer or null if the index expression is
3106/// invalid.
3107static Constant *
3108GetAddressedElementFromGlobal(GlobalVariable *GV,
3109 const std::vector<ConstantInt*> &Indices) {
3110 Constant *Init = GV->getInitializer();
3111 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3112 uint64_t Idx = Indices[i]->getZExtValue();
3113 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3114 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3115 Init = cast<Constant>(CS->getOperand(Idx));
3116 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3117 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3118 Init = cast<Constant>(CA->getOperand(Idx));
3119 } else if (isa<ConstantAggregateZero>(Init)) {
3120 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3121 assert(Idx < STy->getNumElements() && "Bad struct index!");
3122 Init = Constant::getNullValue(STy->getElementType(Idx));
3123 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3124 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3125 Init = Constant::getNullValue(ATy->getElementType());
3126 } else {
3127 assert(0 && "Unknown constant aggregate type!");
3128 }
3129 return 0;
3130 } else {
3131 return 0; // Unknown initializer type
3132 }
3133 }
3134 return Init;
3135}
3136
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003137/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3138/// 'icmp op load X, cst', try to see if we can compute the backedge
3139/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003140const SCEV *
3141ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3142 LoadInst *LI,
3143 Constant *RHS,
3144 const Loop *L,
3145 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00003146 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147
3148 // Check to see if the loaded pointer is a getelementptr of a global.
3149 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00003150 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151
3152 // Make sure that it is really a constant global we are gepping, with an
3153 // initializer, and make sure the first IDX is really 0.
3154 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3155 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3156 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3157 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00003158 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159
3160 // Okay, we allow one non-constant index into the GEP instruction.
3161 Value *VarIdx = 0;
3162 std::vector<ConstantInt*> Indexes;
3163 unsigned VarIdxNum = 0;
3164 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3165 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3166 Indexes.push_back(CI);
3167 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00003168 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003169 VarIdx = GEP->getOperand(i);
3170 VarIdxNum = i-2;
3171 Indexes.push_back(0);
3172 }
3173
3174 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3175 // Check to see if X is a loop variant variable value now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003176 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003177 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003178
3179 // We can only recognize very limited forms of loop index expressions, in
3180 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003181 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003182 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3183 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3184 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00003185 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003186
3187 unsigned MaxSteps = MaxBruteForceIterations;
3188 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3189 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003190 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003191 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003192
3193 // Form the GEP offset.
3194 Indexes[VarIdxNum] = Val;
3195
3196 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3197 if (Result == 0) break; // Cannot compute!
3198
3199 // Evaluate the condition for this iteration.
3200 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3201 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3202 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3203#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003204 errs() << "\n***\n*** Computed loop count " << *ItCst
3205 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3206 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207#endif
3208 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003209 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003210 }
3211 }
Dan Gohman0c850912009-06-06 14:37:11 +00003212 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213}
3214
3215
3216/// CanConstantFold - Return true if we can constant fold an instruction of the
3217/// specified type, assuming that all operands were constants.
3218static bool CanConstantFold(const Instruction *I) {
3219 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3220 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3221 return true;
3222
3223 if (const CallInst *CI = dyn_cast<CallInst>(I))
3224 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003225 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226 return false;
3227}
3228
3229/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3230/// in the loop that V is derived from. We allow arbitrary operations along the
3231/// way, but the operands of an operation must either be constants or a value
3232/// derived from a constant PHI. If this expression does not fit with these
3233/// constraints, return null.
3234static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3235 // If this is not an instruction, or if this is an instruction outside of the
3236 // loop, it can't be derived from a loop PHI.
3237 Instruction *I = dyn_cast<Instruction>(V);
3238 if (I == 0 || !L->contains(I->getParent())) return 0;
3239
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003240 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003241 if (L->getHeader() == I->getParent())
3242 return PN;
3243 else
3244 // We don't currently keep track of the control flow needed to evaluate
3245 // PHIs, so we cannot handle PHIs inside of loops.
3246 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003247 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003248
3249 // If we won't be able to constant fold this expression even if the operands
3250 // are constants, return early.
3251 if (!CanConstantFold(I)) return 0;
3252
3253 // Otherwise, we can evaluate this instruction if all of its operands are
3254 // constant or derived from a PHI node themselves.
3255 PHINode *PHI = 0;
3256 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3257 if (!(isa<Constant>(I->getOperand(Op)) ||
3258 isa<GlobalValue>(I->getOperand(Op)))) {
3259 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3260 if (P == 0) return 0; // Not evolving from PHI
3261 if (PHI == 0)
3262 PHI = P;
3263 else if (PHI != P)
3264 return 0; // Evolving from multiple different PHIs.
3265 }
3266
3267 // This is a expression evolving from a constant PHI!
3268 return PHI;
3269}
3270
3271/// EvaluateExpression - Given an expression that passes the
3272/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3273/// in the loop has the value PHIVal. If we can't fold this expression for some
3274/// reason, return null.
3275static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3276 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003277 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003278 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003279 Instruction *I = cast<Instruction>(V);
3280
3281 std::vector<Constant*> Operands;
3282 Operands.resize(I->getNumOperands());
3283
3284 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3285 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3286 if (Operands[i] == 0) return 0;
3287 }
3288
Chris Lattnerd6e56912007-12-10 22:53:04 +00003289 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3290 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3291 &Operands[0], Operands.size());
3292 else
3293 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3294 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295}
3296
3297/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3298/// in the header of its containing loop, we know the loop executes a
3299/// constant number of times, and the PHI node is just a recurrence
3300/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003301Constant *
3302ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3303 const APInt& BEs,
3304 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305 std::map<PHINode*, Constant*>::iterator I =
3306 ConstantEvolutionLoopExitValue.find(PN);
3307 if (I != ConstantEvolutionLoopExitValue.end())
3308 return I->second;
3309
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003310 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003311 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3312
3313 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3314
3315 // Since the loop is canonicalized, the PHI node must have two entries. One
3316 // entry must be a constant (coming in from outside of the loop), and the
3317 // second must be derived from the same PHI.
3318 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3319 Constant *StartCST =
3320 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3321 if (StartCST == 0)
3322 return RetVal = 0; // Must be a constant.
3323
3324 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3325 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3326 if (PN2 != PN)
3327 return RetVal = 0; // Not derived from same PHI.
3328
3329 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003330 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003331 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3332
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003333 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003334 unsigned IterationNum = 0;
3335 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3336 if (IterationNum == NumIterations)
3337 return RetVal = PHIVal; // Got exit value!
3338
3339 // Compute the value of the PHI node for the next iteration.
3340 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3341 if (NextPHI == PHIVal)
3342 return RetVal = NextPHI; // Stopped evolving!
3343 if (NextPHI == 0)
3344 return 0; // Couldn't evaluate!
3345 PHIVal = NextPHI;
3346 }
3347}
3348
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003349/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003350/// constant number of times (the condition evolves only from constants),
3351/// try to evaluate a few iterations of the loop until we get the exit
3352/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00003353/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003354const SCEV *
3355ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3356 Value *Cond,
3357 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003358 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003359 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003360
3361 // Since the loop is canonicalized, the PHI node must have two entries. One
3362 // entry must be a constant (coming in from outside of the loop), and the
3363 // second must be derived from the same PHI.
3364 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3365 Constant *StartCST =
3366 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00003367 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003368
3369 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3370 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003371 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003372
3373 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3374 // the loop symbolically to determine when the condition gets a value of
3375 // "ExitWhen".
3376 unsigned IterationNum = 0;
3377 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3378 for (Constant *PHIVal = StartCST;
3379 IterationNum != MaxIterations; ++IterationNum) {
3380 ConstantInt *CondVal =
3381 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3382
3383 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003384 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003385
3386 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3387 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3388 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003389 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003390 }
3391
3392 // Compute the value of the PHI node for the next iteration.
3393 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3394 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00003395 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003396 PHIVal = NextPHI;
3397 }
3398
3399 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003400 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003401}
3402
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003403/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3404/// at the specified scope in the program. The L value specifies a loop
3405/// nest to evaluate the expression at, where null is the top-level or a
3406/// specified loop is immediately inside of the loop.
3407///
3408/// This method can be used to compute the exit value for a variable defined
3409/// in a loop by querying what the value will hold in the parent loop.
3410///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003411/// In the case that a relevant loop exit value cannot be computed, the
3412/// original value V is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003413const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003414 // FIXME: this should be turned into a virtual method on SCEV!
3415
3416 if (isa<SCEVConstant>(V)) return V;
3417
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003418 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003420 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003422 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3424 if (PHINode *PN = dyn_cast<PHINode>(I))
3425 if (PN->getParent() == LI->getHeader()) {
3426 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003427 // to see if the loop that contains it has a known backedge-taken
3428 // count. If so, we may be able to force computation of the exit
3429 // value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003430 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003431 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003432 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003433 // Okay, we know how many times the containing loop executes. If
3434 // this is a constant evolving PHI node, get the final value at
3435 // the specified iteration number.
3436 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003437 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003438 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003439 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003440 }
3441 }
3442
3443 // Okay, this is an expression that we cannot symbolically evaluate
3444 // into a SCEV. Check to see if it's possible to symbolically evaluate
3445 // the arguments into constants, and if so, try to constant propagate the
3446 // result. This is particularly useful for computing loop exit values.
3447 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003448 // Check to see if we've folded this instruction at this loop before.
3449 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3450 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3451 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3452 if (!Pair.second)
3453 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3454
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455 std::vector<Constant*> Operands;
3456 Operands.reserve(I->getNumOperands());
3457 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3458 Value *Op = I->getOperand(i);
3459 if (Constant *C = dyn_cast<Constant>(Op)) {
3460 Operands.push_back(C);
3461 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003462 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003463 // non-integer and non-pointer, don't even try to analyze them
3464 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003465 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003466 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003467
Owen Andersonecd0cd72009-06-22 21:39:50 +00003468 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003469 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003470 Constant *C = SC->getValue();
3471 if (C->getType() != Op->getType())
3472 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3473 Op->getType(),
3474 false),
3475 C, Op->getType());
3476 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003477 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003478 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3479 if (C->getType() != Op->getType())
3480 C =
3481 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3482 Op->getType(),
3483 false),
3484 C, Op->getType());
3485 Operands.push_back(C);
3486 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003487 return V;
3488 } else {
3489 return V;
3490 }
3491 }
3492 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003493
Chris Lattnerd6e56912007-12-10 22:53:04 +00003494 Constant *C;
3495 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3496 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3497 &Operands[0], Operands.size());
3498 else
3499 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3500 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003501 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003502 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003503 }
3504 }
3505
3506 // This is some other type of SCEVUnknown, just return it.
3507 return V;
3508 }
3509
Dan Gohmanc76b5452009-05-04 22:02:23 +00003510 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003511 // Avoid performing the look-up in the common case where the specified
3512 // expression has no loop-variant portions.
3513 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003514 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003515 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 // Okay, at least one of these operands is loop variant but might be
3517 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003518 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3519 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520 NewOps.push_back(OpAtScope);
3521
3522 for (++i; i != e; ++i) {
3523 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524 NewOps.push_back(OpAtScope);
3525 }
3526 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003527 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003528 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003529 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003530 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003531 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003532 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003533 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003534 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003535 }
3536 }
3537 // If we got here, all operands are loop invariant.
3538 return Comm;
3539 }
3540
Dan Gohmanc76b5452009-05-04 22:02:23 +00003541 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003542 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3543 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003544 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3545 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003546 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547 }
3548
3549 // If this is a loop recurrence for a loop that does not contain L, then we
3550 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003551 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3553 // To evaluate this recurrence, we need to know how many times the AddRec
3554 // loop iterates. Compute this now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003555 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003556 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557
Eli Friedman7489ec92008-08-04 23:49:06 +00003558 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003559 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003560 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003561 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003562 }
3563
Dan Gohmanc76b5452009-05-04 22:02:23 +00003564 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003565 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003566 if (Op == Cast->getOperand())
3567 return Cast; // must be loop invariant
3568 return getZeroExtendExpr(Op, Cast->getType());
3569 }
3570
Dan Gohmanc76b5452009-05-04 22:02:23 +00003571 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003572 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003573 if (Op == Cast->getOperand())
3574 return Cast; // must be loop invariant
3575 return getSignExtendExpr(Op, Cast->getType());
3576 }
3577
Dan Gohmanc76b5452009-05-04 22:02:23 +00003578 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003579 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003580 if (Op == Cast->getOperand())
3581 return Cast; // must be loop invariant
3582 return getTruncateExpr(Op, Cast->getType());
3583 }
3584
3585 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003586 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003587}
3588
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003589/// getSCEVAtScope - This is a convenience function which does
3590/// getSCEVAtScope(getSCEV(V), L).
Owen Andersonecd0cd72009-06-22 21:39:50 +00003591const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003592 return getSCEVAtScope(getSCEV(V), L);
3593}
3594
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003595/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3596/// following equation:
3597///
3598/// A * X = B (mod N)
3599///
3600/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3601/// A and B isn't important.
3602///
3603/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003604static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003605 ScalarEvolution &SE) {
3606 uint32_t BW = A.getBitWidth();
3607 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3608 assert(A != 0 && "A must be non-zero.");
3609
3610 // 1. D = gcd(A, N)
3611 //
3612 // The gcd of A and N may have only one prime factor: 2. The number of
3613 // trailing zeros in A is its multiplicity
3614 uint32_t Mult2 = A.countTrailingZeros();
3615 // D = 2^Mult2
3616
3617 // 2. Check if B is divisible by D.
3618 //
3619 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3620 // is not less than multiplicity of this prime factor for D.
3621 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003622 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003623
3624 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3625 // modulo (N / D).
3626 //
3627 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3628 // bit width during computations.
3629 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3630 APInt Mod(BW + 1, 0);
3631 Mod.set(BW - Mult2); // Mod = N / D
3632 APInt I = AD.multiplicativeInverse(Mod);
3633
3634 // 4. Compute the minimum unsigned root of the equation:
3635 // I * (B / D) mod (N / D)
3636 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3637
3638 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3639 // bits.
3640 return SE.getConstant(Result.trunc(BW));
3641}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003642
3643/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3644/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3645/// might be the same) or two SCEVCouldNotCompute objects.
3646///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003647static std::pair<const SCEV*,const SCEV*>
Dan Gohman89f85052007-10-22 18:31:58 +00003648SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003649 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003650 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3651 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3652 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003653
3654 // We currently can only solve this if the coefficients are constants.
3655 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003656 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003657 return std::make_pair(CNC, CNC);
3658 }
3659
3660 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3661 const APInt &L = LC->getValue()->getValue();
3662 const APInt &M = MC->getValue()->getValue();
3663 const APInt &N = NC->getValue()->getValue();
3664 APInt Two(BitWidth, 2);
3665 APInt Four(BitWidth, 4);
3666
Dan Gohman9bc642f2009-06-24 04:48:43 +00003667 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003668 using namespace APIntOps;
3669 const APInt& C = L;
3670 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3671 // The B coefficient is M-N/2
3672 APInt B(M);
3673 B -= sdiv(N,Two);
3674
3675 // The A coefficient is N/2
3676 APInt A(N.sdiv(Two));
3677
3678 // Compute the B^2-4ac term.
3679 APInt SqrtTerm(B);
3680 SqrtTerm *= B;
3681 SqrtTerm -= Four * (A * C);
3682
3683 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3684 // integer value or else APInt::sqrt() will assert.
3685 APInt SqrtVal(SqrtTerm.sqrt());
3686
Dan Gohman9bc642f2009-06-24 04:48:43 +00003687 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003688 // The divisions must be performed as signed divisions.
3689 APInt NegB(-B);
3690 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003691 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003692 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003693 return std::make_pair(CNC, CNC);
3694 }
3695
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3697 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3698
Dan Gohman9bc642f2009-06-24 04:48:43 +00003699 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00003700 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003701 } // end APIntOps namespace
3702}
3703
3704/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003705/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003706const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003708 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003709 // If the value is already zero, the branch will execute zero times.
3710 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003711 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003712 }
3713
Dan Gohmanbff6b582009-05-04 22:30:44 +00003714 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003715 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003716 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003717
3718 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003719 // If this is an affine expression, the execution count of this branch is
3720 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003721 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003722 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003723 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003724 // equivalent to:
3725 //
3726 // Step*N = -Start (mod 2^BW)
3727 //
3728 // where BW is the common bit width of Start and Step.
3729
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003731 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3732 L->getParentLoop());
3733 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3734 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003735
Dan Gohmanc76b5452009-05-04 22:02:23 +00003736 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003737 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003738
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003739 // First, handle unitary steps.
3740 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003741 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003742 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3743 return Start; // N = Start (as unsigned)
3744
3745 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003746 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003747 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003748 -StartC->getValue()->getValue(),
3749 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003750 }
3751 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3752 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3753 // the quadratic equation to solve it.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003754 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003755 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003756 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3757 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003758 if (R1) {
3759#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003760 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3761 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003762#endif
3763 // Pick the smallest positive root value.
3764 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00003765 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003766 R1->getValue(), R2->getValue()))) {
3767 if (CB->getZExtValue() == false)
3768 std::swap(R1, R2); // R1 is the minimum root now.
3769
3770 // We can only use this value if the chrec ends up with an exact zero
3771 // value at this index. When solving for "X*X != 5", for example, we
3772 // should not accept a root of 2.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003773 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003774 if (Val->isZero())
3775 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003776 }
3777 }
3778 }
3779
Dan Gohman0c850912009-06-06 14:37:11 +00003780 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003781}
3782
3783/// HowFarToNonZero - Return the number of times a backedge checking the
3784/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003785/// CouldNotCompute
Owen Andersonecd0cd72009-06-22 21:39:50 +00003786const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003787 // Loops that look like: while (X == 0) are very strange indeed. We don't
3788 // handle them yet except for the trivial case. This could be expanded in the
3789 // future as needed.
3790
3791 // If the value is a constant, check to see if it is known to be non-zero
3792 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003793 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003794 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003795 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003796 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003797 }
3798
3799 // We could implement others, but I really doubt anyone writes loops like
3800 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003801 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003802}
3803
Dan Gohmanab157b22009-05-18 15:36:09 +00003804/// getLoopPredecessor - If the given loop's header has exactly one unique
3805/// predecessor outside the loop, return it. Otherwise return null.
3806///
3807BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3808 BasicBlock *Header = L->getHeader();
3809 BasicBlock *Pred = 0;
3810 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3811 PI != E; ++PI)
3812 if (!L->contains(*PI)) {
3813 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3814 Pred = *PI;
3815 }
3816 return Pred;
3817}
3818
Dan Gohman1cddf972008-09-15 22:18:04 +00003819/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3820/// (which may not be an immediate predecessor) which has exactly one
3821/// successor from which BB is reachable, or null if no such block is
3822/// found.
3823///
3824BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003825ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003826 // If the block has a unique predecessor, then there is no path from the
3827 // predecessor to the block that does not go through the direct edge
3828 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003829 if (BasicBlock *Pred = BB->getSinglePredecessor())
3830 return Pred;
3831
3832 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003833 // If the header has a unique predecessor outside the loop, it must be
3834 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003835 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003836 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003837
3838 return 0;
3839}
3840
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003841/// HasSameValue - SCEV structural equivalence is usually sufficient for
3842/// testing whether two expressions are equal, however for the purposes of
3843/// looking for a condition guarding a loop, it can be useful to be a little
3844/// more general, since a front-end may have replicated the controlling
3845/// expression.
3846///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003847static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003848 // Quick check to see if they are the same SCEV.
3849 if (A == B) return true;
3850
3851 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3852 // two different instructions with the same value. Check for this case.
3853 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3854 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3855 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3856 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3857 if (AI->isIdenticalTo(BI))
3858 return true;
3859
3860 // Otherwise assume they may have a different value.
3861 return false;
3862}
3863
Dan Gohmancacd2012009-02-12 22:19:27 +00003864/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003865/// a conditional between LHS and RHS. This is used to help avoid max
3866/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003867bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003868 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003869 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003870 // Interpret a null as meaning no loop, where there is obviously no guard
3871 // (interprocedural conditions notwithstanding).
3872 if (!L) return false;
3873
Dan Gohmanab157b22009-05-18 15:36:09 +00003874 BasicBlock *Predecessor = getLoopPredecessor(L);
3875 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003876
Dan Gohmanab157b22009-05-18 15:36:09 +00003877 // Starting at the loop predecessor, climb up the predecessor chain, as long
3878 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003879 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003880 for (; Predecessor;
3881 PredecessorDest = Predecessor,
3882 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003883
3884 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003885 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003886 if (!LoopEntryPredicate ||
3887 LoopEntryPredicate->isUnconditional())
3888 continue;
3889
Dan Gohman423ed6c2009-06-24 01:18:18 +00003890 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
3891 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003892 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003893 }
3894
Dan Gohmanab678fb2008-08-12 20:17:31 +00003895 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003896}
3897
Dan Gohman423ed6c2009-06-24 01:18:18 +00003898/// isNecessaryCond - Test whether the given CondValue value is a condition
3899/// which is at least as strict as the one described by Pred, LHS, and RHS.
3900bool ScalarEvolution::isNecessaryCond(Value *CondValue,
3901 ICmpInst::Predicate Pred,
3902 const SCEV *LHS, const SCEV *RHS,
3903 bool Inverse) {
3904 // Recursivly handle And and Or conditions.
3905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
3906 if (BO->getOpcode() == Instruction::And) {
3907 if (!Inverse)
3908 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
3909 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
3910 } else if (BO->getOpcode() == Instruction::Or) {
3911 if (Inverse)
3912 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
3913 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
3914 }
3915 }
3916
3917 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
3918 if (!ICI) return false;
3919
3920 // Now that we found a conditional branch that dominates the loop, check to
3921 // see if it is the comparison we are looking for.
3922 Value *PreCondLHS = ICI->getOperand(0);
3923 Value *PreCondRHS = ICI->getOperand(1);
3924 ICmpInst::Predicate Cond;
3925 if (Inverse)
3926 Cond = ICI->getInversePredicate();
3927 else
3928 Cond = ICI->getPredicate();
3929
3930 if (Cond == Pred)
3931 ; // An exact match.
3932 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3933 ; // The actual condition is beyond sufficient.
3934 else
3935 // Check a few special cases.
3936 switch (Cond) {
3937 case ICmpInst::ICMP_UGT:
3938 if (Pred == ICmpInst::ICMP_ULT) {
3939 std::swap(PreCondLHS, PreCondRHS);
3940 Cond = ICmpInst::ICMP_ULT;
3941 break;
3942 }
3943 return false;
3944 case ICmpInst::ICMP_SGT:
3945 if (Pred == ICmpInst::ICMP_SLT) {
3946 std::swap(PreCondLHS, PreCondRHS);
3947 Cond = ICmpInst::ICMP_SLT;
3948 break;
3949 }
3950 return false;
3951 case ICmpInst::ICMP_NE:
3952 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3953 // so check for this case by checking if the NE is comparing against
3954 // a minimum or maximum constant.
3955 if (!ICmpInst::isTrueWhenEqual(Pred))
3956 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3957 const APInt &A = CI->getValue();
3958 switch (Pred) {
3959 case ICmpInst::ICMP_SLT:
3960 if (A.isMaxSignedValue()) break;
3961 return false;
3962 case ICmpInst::ICMP_SGT:
3963 if (A.isMinSignedValue()) break;
3964 return false;
3965 case ICmpInst::ICMP_ULT:
3966 if (A.isMaxValue()) break;
3967 return false;
3968 case ICmpInst::ICMP_UGT:
3969 if (A.isMinValue()) break;
3970 return false;
3971 default:
3972 return false;
3973 }
3974 Cond = ICmpInst::ICMP_NE;
3975 // NE is symmetric but the original comparison may not be. Swap
3976 // the operands if necessary so that they match below.
3977 if (isa<SCEVConstant>(LHS))
3978 std::swap(PreCondLHS, PreCondRHS);
3979 break;
3980 }
3981 return false;
3982 default:
3983 // We weren't able to reconcile the condition.
3984 return false;
3985 }
3986
3987 if (!PreCondLHS->getType()->isInteger()) return false;
3988
3989 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
3990 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
3991 return (HasSameValue(LHS, PreCondLHSSCEV) &&
3992 HasSameValue(RHS, PreCondRHSSCEV)) ||
3993 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
3994 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
3995}
3996
Dan Gohmand2b62c42009-06-21 23:46:38 +00003997/// getBECount - Subtract the end and start values and divide by the step,
3998/// rounding up, to get the number of times the backedge is executed. Return
3999/// CouldNotCompute if an intermediate computation overflows.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004000const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
4001 const SCEV* End,
4002 const SCEV* Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004003 const Type *Ty = Start->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00004004 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
4005 const SCEV* Diff = getMinusSCEV(End, Start);
4006 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004007
4008 // Add an adjustment to the difference between End and Start so that
4009 // the division will effectively round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004010 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004011
4012 // Check Add for unsigned overflow.
4013 // TODO: More sophisticated things could be done here.
4014 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
Owen Andersonecd0cd72009-06-22 21:39:50 +00004015 const SCEV* OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004016 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4017 getZeroExtendExpr(RoundUp, WideTy));
4018 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4019 return CouldNotCompute;
4020
4021 return getUDivExpr(Add, Step);
4022}
4023
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004024/// HowManyLessThans - Return the number of times a backedge containing the
4025/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004026/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004027ScalarEvolution::BackedgeTakenInfo
4028ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4029 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004030 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00004031 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004032
Dan Gohmanbff6b582009-05-04 22:30:44 +00004033 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004034 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00004035 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004036
4037 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004038 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004039 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004040 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004041
4042 // TODO: handle non-constant strides.
4043 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4044 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00004045 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004046 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004047 // With unit stride, the iteration never steps past the limit value.
4048 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4049 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4050 // Test whether a positive iteration iteration can step past the limit
4051 // value and past the maximum value for its type in a single step.
4052 if (isSigned) {
4053 APInt Max = APInt::getSignedMaxValue(BitWidth);
4054 if ((Max - CStep->getValue()->getValue())
4055 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00004056 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004057 } else {
4058 APInt Max = APInt::getMaxValue(BitWidth);
4059 if ((Max - CStep->getValue()->getValue())
4060 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00004061 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004062 }
4063 } else
4064 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00004065 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004066 } else
4067 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00004068 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004069
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004070 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4071 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4072 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004073 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004074
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004075 // First, we get the value of the LHS in the first iteration: n
Owen Andersonecd0cd72009-06-22 21:39:50 +00004076 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004077
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004078 // Determine the minimum constant start value.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004079 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004080 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4081 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004082
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004083 // If we know that the condition is true in order to enter the loop,
4084 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004085 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4086 // the division must round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004087 const SCEV* End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004088 if (!isLoopGuardedByCond(L,
4089 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4090 getMinusSCEV(Start, Step), RHS))
4091 End = isSigned ? getSMaxExpr(RHS, Start)
4092 : getUMaxExpr(RHS, Start);
4093
4094 // Determine the maximum constant end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004095 const SCEV* MaxEnd =
Dan Gohman92369c32009-06-20 00:32:22 +00004096 isa<SCEVConstant>(End) ? End :
4097 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4098 .ashr(GetMinSignBits(End) - 1) :
4099 APInt::getMaxValue(BitWidth)
4100 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004101
4102 // Finally, we subtract these two values and divide, rounding up, to get
4103 // the number of times the backedge is executed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004104 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004105
4106 // The maximum backedge count is similar, except using the minimum start
4107 // value and the maximum end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004108 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004109
4110 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004111 }
4112
Dan Gohman0c850912009-06-06 14:37:11 +00004113 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004114}
4115
4116/// getNumIterationsInRange - Return the number of iterations of this loop that
4117/// produce values in the specified constant range. Another way of looking at
4118/// this is that it returns the first iteration number where the value is not in
4119/// the condition, thus computing the exit count. If the iteration count can't
4120/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004121const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004122 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004123 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004124 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004125
4126 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004127 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128 if (!SC->getValue()->isZero()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00004129 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004130 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004131 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004132 if (const SCEVAddRecExpr *ShiftedAddRec =
4133 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004134 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004135 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004136 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004137 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004138 }
4139
4140 // The only time we can solve this is when we have all constant indices.
4141 // Otherwise, we cannot determine the overflow conditions.
4142 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4143 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004144 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004145
4146
4147 // Okay at this point we know that all elements of the chrec are constants and
4148 // that the start element is zero.
4149
4150 // First check to see if the range contains zero. If not, the first
4151 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004152 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004153 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004154 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004155
4156 if (isAffine()) {
4157 // If this is an affine expression then we have this situation:
4158 // Solve {0,+,A} in Range === Ax in Range
4159
4160 // We know that zero is in the range. If A is positive then we know that
4161 // the upper value of the range must be the first possible exit value.
4162 // If A is negative then the lower of the range is the last possible loop
4163 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004164 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004165 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4166 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4167
4168 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004169 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004170 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
4171
4172 // Evaluate at the exit value. If we really did fall out of the valid
4173 // range, then we computed our trip count, otherwise wrap around or other
4174 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004175 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004176 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004177 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004178
4179 // Ensure that the previous value is in the range. This is a sanity check.
4180 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004181 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004182 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004183 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004184 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004185 } else if (isQuadratic()) {
4186 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4187 // quadratic equation to solve it. To do this, we must frame our problem in
4188 // terms of figuring out when zero is crossed, instead of when
4189 // Range.getUpper() is crossed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004190 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004191 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Andersonecd0cd72009-06-22 21:39:50 +00004192 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193
4194 // Next, solve the constructed addrec
Owen Andersonecd0cd72009-06-22 21:39:50 +00004195 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004196 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004197 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4198 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004199 if (R1) {
4200 // Pick the smallest positive root value.
4201 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00004202 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004203 R1->getValue(), R2->getValue()))) {
4204 if (CB->getZExtValue() == false)
4205 std::swap(R1, R2); // R1 is the minimum root now.
4206
4207 // Make sure the root is not off by one. The returned iteration should
4208 // not be in the range, but the previous one should be. When solving
4209 // for "X*X < 5", for example, we should not return a root of 2.
4210 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004211 R1->getValue(),
4212 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004213 if (Range.contains(R1Val->getValue())) {
4214 // The next iteration must be out of the range...
4215 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
4216
Dan Gohman89f85052007-10-22 18:31:58 +00004217 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004218 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004219 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004220 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004221 }
4222
4223 // If R1 was not in the range, then it is a good return value. Make
4224 // sure that R1-1 WAS in the range though, just in case.
4225 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004226 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004227 if (Range.contains(R1Val->getValue()))
4228 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004229 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004230 }
4231 }
4232 }
4233
Dan Gohman0ad08b02009-04-18 17:58:19 +00004234 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004235}
4236
4237
4238
4239//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004240// SCEVCallbackVH Class Implementation
4241//===----------------------------------------------------------------------===//
4242
Dan Gohman999d14e2009-05-19 19:22:47 +00004243void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004244 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4245 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4246 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004247 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4248 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004249 SE->Scalars.erase(getValPtr());
4250 // this now dangles!
4251}
4252
Dan Gohman999d14e2009-05-19 19:22:47 +00004253void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004254 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4255
4256 // Forget all the expressions associated with users of the old value,
4257 // so that future queries will recompute the expressions using the new
4258 // value.
4259 SmallVector<User *, 16> Worklist;
4260 Value *Old = getValPtr();
4261 bool DeleteOld = false;
4262 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4263 UI != UE; ++UI)
4264 Worklist.push_back(*UI);
4265 while (!Worklist.empty()) {
4266 User *U = Worklist.pop_back_val();
4267 // Deleting the Old value will cause this to dangle. Postpone
4268 // that until everything else is done.
4269 if (U == Old) {
4270 DeleteOld = true;
4271 continue;
4272 }
4273 if (PHINode *PN = dyn_cast<PHINode>(U))
4274 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004275 if (Instruction *I = dyn_cast<Instruction>(U))
4276 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004277 if (SE->Scalars.erase(U))
4278 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4279 UI != UE; ++UI)
4280 Worklist.push_back(*UI);
4281 }
4282 if (DeleteOld) {
4283 if (PHINode *PN = dyn_cast<PHINode>(Old))
4284 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004285 if (Instruction *I = dyn_cast<Instruction>(Old))
4286 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004287 SE->Scalars.erase(Old);
4288 // this now dangles!
4289 }
4290 // this may dangle!
4291}
4292
Dan Gohman999d14e2009-05-19 19:22:47 +00004293ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004294 : CallbackVH(V), SE(se) {}
4295
4296//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004297// ScalarEvolution Class Implementation
4298//===----------------------------------------------------------------------===//
4299
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004300ScalarEvolution::ScalarEvolution()
Owen Andersonb70139d2009-06-22 21:57:23 +00004301 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004302}
4303
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004304bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004305 this->F = &F;
4306 LI = &getAnalysis<LoopInfo>();
4307 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004308 return false;
4309}
4310
4311void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004312 Scalars.clear();
4313 BackedgeTakenCounts.clear();
4314 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004315 ValuesAtScopes.clear();
Dan Gohman9bc642f2009-06-24 04:48:43 +00004316
Owen Andersonc48fbfe2009-06-22 18:25:46 +00004317 for (std::map<ConstantInt*, SCEVConstant*>::iterator
4318 I = SCEVConstants.begin(), E = SCEVConstants.end(); I != E; ++I)
4319 delete I->second;
4320 for (std::map<std::pair<const SCEV*, const Type*>,
4321 SCEVTruncateExpr*>::iterator I = SCEVTruncates.begin(),
4322 E = SCEVTruncates.end(); I != E; ++I)
4323 delete I->second;
4324 for (std::map<std::pair<const SCEV*, const Type*>,
4325 SCEVZeroExtendExpr*>::iterator I = SCEVZeroExtends.begin(),
4326 E = SCEVZeroExtends.end(); I != E; ++I)
4327 delete I->second;
4328 for (std::map<std::pair<unsigned, std::vector<const SCEV*> >,
4329 SCEVCommutativeExpr*>::iterator I = SCEVCommExprs.begin(),
4330 E = SCEVCommExprs.end(); I != E; ++I)
4331 delete I->second;
4332 for (std::map<std::pair<const SCEV*, const SCEV*>, SCEVUDivExpr*>::iterator
4333 I = SCEVUDivs.begin(), E = SCEVUDivs.end(); I != E; ++I)
4334 delete I->second;
4335 for (std::map<std::pair<const SCEV*, const Type*>,
4336 SCEVSignExtendExpr*>::iterator I = SCEVSignExtends.begin(),
4337 E = SCEVSignExtends.end(); I != E; ++I)
4338 delete I->second;
4339 for (std::map<std::pair<const Loop *, std::vector<const SCEV*> >,
4340 SCEVAddRecExpr*>::iterator I = SCEVAddRecExprs.begin(),
4341 E = SCEVAddRecExprs.end(); I != E; ++I)
4342 delete I->second;
4343 for (std::map<Value*, SCEVUnknown*>::iterator I = SCEVUnknowns.begin(),
4344 E = SCEVUnknowns.end(); I != E; ++I)
4345 delete I->second;
Dan Gohman9bc642f2009-06-24 04:48:43 +00004346
Owen Andersonc48fbfe2009-06-22 18:25:46 +00004347 SCEVConstants.clear();
4348 SCEVTruncates.clear();
4349 SCEVZeroExtends.clear();
4350 SCEVCommExprs.clear();
4351 SCEVUDivs.clear();
4352 SCEVSignExtends.clear();
4353 SCEVAddRecExprs.clear();
4354 SCEVUnknowns.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004355}
4356
4357void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4358 AU.setPreservesAll();
4359 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004360}
4361
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004362bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004363 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004364}
4365
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004366static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004367 const Loop *L) {
4368 // Print all inner loops first
4369 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4370 PrintLoopInfo(OS, SE, *I);
4371
Nick Lewyckye5da1912008-01-02 02:49:20 +00004372 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004373
Devang Patel02451fa2007-08-21 00:31:24 +00004374 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004375 L->getExitBlocks(ExitBlocks);
4376 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004377 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004378
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004379 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4380 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004381 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004382 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004383 }
4384
Nick Lewyckye5da1912008-01-02 02:49:20 +00004385 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004386 OS << "Loop " << L->getHeader()->getName() << ": ";
4387
4388 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4389 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4390 } else {
4391 OS << "Unpredictable max backedge-taken count. ";
4392 }
4393
4394 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395}
4396
Dan Gohman13058cc2009-04-21 00:47:46 +00004397void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004398 // ScalarEvolution's implementaiton of the print method is to print
4399 // out SCEV values of all instructions that are interesting. Doing
4400 // this potentially causes it to create new SCEV objects though,
4401 // which technically conflicts with the const qualifier. This isn't
4402 // observable from outside the class though (the hasSCEV function
4403 // notwithstanding), so casting away the const isn't dangerous.
4404 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004405
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004406 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004407 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004408 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004409 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004410 OS << " --> ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004411 const SCEV* SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004412 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004413
Dan Gohman8db598a2009-06-19 17:49:54 +00004414 const Loop *L = LI->getLoopFor((*I).getParent());
4415
Owen Andersonecd0cd72009-06-22 21:39:50 +00004416 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004417 if (AtUse != SV) {
4418 OS << " --> ";
4419 AtUse->print(OS);
4420 }
4421
4422 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004423 OS << "\t\t" "Exits: ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004424 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004425 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 OS << "<<Unknown>>";
4427 } else {
4428 OS << *ExitValue;
4429 }
4430 }
4431
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004432 OS << "\n";
4433 }
4434
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004435 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4436 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4437 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004438}
Dan Gohman13058cc2009-04-21 00:47:46 +00004439
4440void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4441 raw_os_ostream OS(o);
4442 print(OS, M);
4443}