blob: dcb179afd233a0b4017c9ca51cfd71ea23fae18a [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();
Dan Gohman08c4c072009-06-26 22:36:20 +00001654 // AddRecs require their operands be loop-invariant with respect to their
1655 // loops. Don't perform this transformation if it would break this
1656 // requirement.
1657 bool AllInvariant = true;
1658 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1659 if (!Operands[i]->isLoopInvariant(L)) {
1660 AllInvariant = false;
1661 break;
1662 }
1663 if (AllInvariant) {
1664 NestedOperands[0] = getAddRecExpr(Operands, L);
1665 AllInvariant = true;
1666 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1667 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1668 AllInvariant = false;
1669 break;
1670 }
1671 if (AllInvariant)
1672 // Ok, both add recurrences are valid after the transformation.
1673 return getAddRecExpr(NestedOperands, NestedLoop);
1674 }
1675 // Reset Operands to its original state.
1676 Operands[0] = NestedAR;
Dan Gohman42936882008-08-08 18:33:12 +00001677 }
1678 }
1679
Dan Gohmanbff6b582009-05-04 22:30:44 +00001680 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001681 SCEVAddRecExpr *&Result = SCEVAddRecExprs[std::make_pair(L, SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001682 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683 return Result;
1684}
1685
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001686const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1687 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001688 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001689 Ops.push_back(LHS);
1690 Ops.push_back(RHS);
1691 return getSMaxExpr(Ops);
1692}
1693
Owen Andersonecd0cd72009-06-22 21:39:50 +00001694const SCEV*
1695ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001696 assert(!Ops.empty() && "Cannot get empty smax!");
1697 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001698#ifndef NDEBUG
1699 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1700 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1701 getEffectiveSCEVType(Ops[0]->getType()) &&
1702 "SCEVSMaxExpr operand types don't match!");
1703#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001704
1705 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001706 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001707
1708 // If there are any constants, fold them together.
1709 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001710 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001711 ++Idx;
1712 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001713 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001714 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001715 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001716 APIntOps::smax(LHSC->getValue()->getValue(),
1717 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001718 Ops[0] = getConstant(Fold);
1719 Ops.erase(Ops.begin()+1); // Erase the folded element
1720 if (Ops.size() == 1) return Ops[0];
1721 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001722 }
1723
Dan Gohmand156c092009-06-24 14:46:22 +00001724 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001725 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1726 Ops.erase(Ops.begin());
1727 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001728 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1729 // If we have an smax with a constant maximum-int, it will always be
1730 // maximum-int.
1731 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001732 }
1733 }
1734
1735 if (Ops.size() == 1) return Ops[0];
1736
1737 // Find the first SMax
1738 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1739 ++Idx;
1740
1741 // Check to see if one of the operands is an SMax. If so, expand its operands
1742 // onto our operand list, and recurse to simplify.
1743 if (Idx < Ops.size()) {
1744 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001745 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001746 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1747 Ops.erase(Ops.begin()+Idx);
1748 DeletedSMax = true;
1749 }
1750
1751 if (DeletedSMax)
1752 return getSMaxExpr(Ops);
1753 }
1754
1755 // Okay, check to see if the same value occurs in the operand list twice. If
1756 // so, delete one. Since we sorted the list, these values are required to
1757 // be adjacent.
1758 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1759 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1760 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1761 --i; --e;
1762 }
1763
1764 if (Ops.size() == 1) return Ops[0];
1765
1766 assert(!Ops.empty() && "Reduced smax down to nothing!");
1767
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001768 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001769 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001770 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001771 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scSMaxExpr,
Nick Lewycky711640a2007-11-25 22:41:31 +00001772 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001773 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
Nick Lewycky711640a2007-11-25 22:41:31 +00001774 return Result;
1775}
1776
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001777const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1778 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001779 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001780 Ops.push_back(LHS);
1781 Ops.push_back(RHS);
1782 return getUMaxExpr(Ops);
1783}
1784
Owen Andersonecd0cd72009-06-22 21:39:50 +00001785const SCEV*
1786ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001787 assert(!Ops.empty() && "Cannot get empty umax!");
1788 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001789#ifndef NDEBUG
1790 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1791 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1792 getEffectiveSCEVType(Ops[0]->getType()) &&
1793 "SCEVUMaxExpr operand types don't match!");
1794#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001795
1796 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001797 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001798
1799 // If there are any constants, fold them together.
1800 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001801 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001802 ++Idx;
1803 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001804 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001805 // We found two constants, fold them together!
1806 ConstantInt *Fold = ConstantInt::get(
1807 APIntOps::umax(LHSC->getValue()->getValue(),
1808 RHSC->getValue()->getValue()));
1809 Ops[0] = getConstant(Fold);
1810 Ops.erase(Ops.begin()+1); // Erase the folded element
1811 if (Ops.size() == 1) return Ops[0];
1812 LHSC = cast<SCEVConstant>(Ops[0]);
1813 }
1814
Dan Gohmand156c092009-06-24 14:46:22 +00001815 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001816 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1817 Ops.erase(Ops.begin());
1818 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001819 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1820 // If we have an umax with a constant maximum-int, it will always be
1821 // maximum-int.
1822 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001823 }
1824 }
1825
1826 if (Ops.size() == 1) return Ops[0];
1827
1828 // Find the first UMax
1829 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1830 ++Idx;
1831
1832 // Check to see if one of the operands is a UMax. If so, expand its operands
1833 // onto our operand list, and recurse to simplify.
1834 if (Idx < Ops.size()) {
1835 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001836 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001837 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1838 Ops.erase(Ops.begin()+Idx);
1839 DeletedUMax = true;
1840 }
1841
1842 if (DeletedUMax)
1843 return getUMaxExpr(Ops);
1844 }
1845
1846 // Okay, check to see if the same value occurs in the operand list twice. If
1847 // so, delete one. Since we sorted the list, these values are required to
1848 // be adjacent.
1849 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1850 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1851 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1852 --i; --e;
1853 }
1854
1855 if (Ops.size() == 1) return Ops[0];
1856
1857 assert(!Ops.empty() && "Reduced umax down to nothing!");
1858
1859 // Okay, it looks like we really DO need a umax expr. Check to see if we
1860 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001861 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001862 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scUMaxExpr,
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001863 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001864 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001865 return Result;
1866}
1867
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001868const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1869 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001870 // ~smax(~x, ~y) == smin(x, y).
1871 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1872}
1873
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001874const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1875 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001876 // ~umax(~x, ~y) == umin(x, y)
1877 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1878}
1879
Owen Andersonecd0cd72009-06-22 21:39:50 +00001880const SCEV* ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001881 // Don't attempt to do anything other than create a SCEVUnknown object
1882 // here. createSCEV only calls getUnknown after checking for all other
1883 // interesting possibilities, and any other code that calls getUnknown
1884 // is doing so in order to hide a value from SCEV canonicalization.
1885
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001886 SCEVUnknown *&Result = SCEVUnknowns[V];
Owen Andersonb70139d2009-06-22 21:57:23 +00001887 if (Result == 0) Result = new SCEVUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888 return Result;
1889}
1890
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001891//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892// Basic SCEV Analysis and PHI Idiom Recognition Code
1893//
1894
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001895/// isSCEVable - Test if values of the given type are analyzable within
1896/// the SCEV framework. This primarily includes integer types, and it
1897/// can optionally include pointer types if the ScalarEvolution class
1898/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001899bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001900 // Integers are always SCEVable.
1901 if (Ty->isInteger())
1902 return true;
1903
1904 // Pointers are SCEVable if TargetData information is available
1905 // to provide pointer size information.
1906 if (isa<PointerType>(Ty))
1907 return TD != NULL;
1908
1909 // Otherwise it's not SCEVable.
1910 return false;
1911}
1912
1913/// getTypeSizeInBits - Return the size in bits of the specified type,
1914/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001915uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001916 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1917
1918 // If we have a TargetData, use it!
1919 if (TD)
1920 return TD->getTypeSizeInBits(Ty);
1921
1922 // Otherwise, we support only integer types.
1923 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1924 return Ty->getPrimitiveSizeInBits();
1925}
1926
1927/// getEffectiveSCEVType - Return a type with the same bitwidth as
1928/// the given type and which represents how SCEV will treat the given
1929/// type, for which isSCEVable must return true. For pointer types,
1930/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001931const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001932 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1933
1934 if (Ty->isInteger())
1935 return Ty;
1936
1937 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1938 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001939}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001940
Owen Andersonecd0cd72009-06-22 21:39:50 +00001941const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001942 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001943}
1944
Dan Gohmand83d4af2009-05-04 22:20:30 +00001945/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001946/// computed.
1947bool ScalarEvolution::hasSCEV(Value *V) const {
1948 return Scalars.count(V);
1949}
1950
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001951/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1952/// expression and create a new one.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001953const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001954 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001955
Owen Andersonecd0cd72009-06-22 21:39:50 +00001956 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001957 if (I != Scalars.end()) return I->second;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001958 const SCEV* S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001959 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001960 return S;
1961}
1962
Dan Gohman984c78a2009-06-24 00:54:57 +00001963/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00001964/// specified signed integer value and return a SCEV for the constant.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001965const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001966 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
1967 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001968}
1969
1970/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1971///
Owen Andersonecd0cd72009-06-22 21:39:50 +00001972const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001973 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00001974 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001975
1976 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001977 Ty = getEffectiveSCEVType(Ty);
1978 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001979}
1980
1981/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Andersonecd0cd72009-06-22 21:39:50 +00001982const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001983 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00001984 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001985
1986 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001987 Ty = getEffectiveSCEVType(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001988 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001989 return getMinusSCEV(AllOnes, V);
1990}
1991
1992/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1993///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001994const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
1995 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001996 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001997 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001998}
1999
2000/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2001/// input value to the specified type. If the type must be extended, it is zero
2002/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002003const SCEV*
2004ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002005 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002006 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002007 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2008 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002009 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002010 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002011 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002012 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002013 return getTruncateExpr(V, Ty);
2014 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002015}
2016
2017/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2018/// input value to the specified type. If the type must be extended, it is sign
2019/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002020const SCEV*
2021ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002022 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002023 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002024 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2025 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002026 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002027 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002028 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002029 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002030 return getTruncateExpr(V, Ty);
2031 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002032}
2033
Dan Gohmanac959332009-05-13 03:46:30 +00002034/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2035/// input value to the specified type. If the type must be extended, it is zero
2036/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002037const SCEV*
2038ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002039 const Type *SrcTy = V->getType();
2040 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2041 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2042 "Cannot noop or zero extend with non-integer arguments!");
2043 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2044 "getNoopOrZeroExtend cannot truncate!");
2045 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2046 return V; // No conversion
2047 return getZeroExtendExpr(V, Ty);
2048}
2049
2050/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2051/// input value to the specified type. If the type must be extended, it is sign
2052/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002053const SCEV*
2054ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002055 const Type *SrcTy = V->getType();
2056 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2057 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2058 "Cannot noop or sign extend with non-integer arguments!");
2059 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2060 "getNoopOrSignExtend cannot truncate!");
2061 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2062 return V; // No conversion
2063 return getSignExtendExpr(V, Ty);
2064}
2065
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002066/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2067/// the input value to the specified type. If the type must be extended,
2068/// it is extended with unspecified bits. The conversion must not be
2069/// narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002070const SCEV*
2071ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002072 const Type *SrcTy = V->getType();
2073 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2074 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2075 "Cannot noop or any extend with non-integer arguments!");
2076 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2077 "getNoopOrAnyExtend cannot truncate!");
2078 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2079 return V; // No conversion
2080 return getAnyExtendExpr(V, Ty);
2081}
2082
Dan Gohmanac959332009-05-13 03:46:30 +00002083/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2084/// input value to the specified type. The conversion must not be widening.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002085const SCEV*
2086ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002087 const Type *SrcTy = V->getType();
2088 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2089 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2090 "Cannot truncate or noop with non-integer arguments!");
2091 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2092 "getTruncateOrNoop cannot extend!");
2093 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2094 return V; // No conversion
2095 return getTruncateExpr(V, Ty);
2096}
2097
Dan Gohman8e8b5232009-06-22 00:31:57 +00002098/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2099/// the types using zero-extension, and then perform a umax operation
2100/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002101const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2102 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002103 const SCEV* PromotedLHS = LHS;
2104 const SCEV* PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002105
2106 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2107 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2108 else
2109 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2110
2111 return getUMaxExpr(PromotedLHS, PromotedRHS);
2112}
2113
Dan Gohman9e62bb02009-06-22 15:03:27 +00002114/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2115/// the types using zero-extension, and then perform a umin operation
2116/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002117const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2118 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002119 const SCEV* PromotedLHS = LHS;
2120 const SCEV* PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002121
2122 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2123 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2124 else
2125 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2126
2127 return getUMinExpr(PromotedLHS, PromotedRHS);
2128}
2129
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2131/// the specified instruction and replaces any references to the symbolic value
2132/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002133void
2134ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2135 const SCEV *SymName,
2136 const SCEV *NewVal) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002137 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002138 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002139 if (SI == Scalars.end()) return;
2140
Owen Andersonecd0cd72009-06-22 21:39:50 +00002141 const SCEV* NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002142 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002143 if (NV == SI->second) return; // No change.
2144
2145 SI->second = NV; // Update the scalars map!
2146
2147 // Any instruction values that use this instruction might also need to be
2148 // updated!
2149 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2150 UI != E; ++UI)
2151 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2152}
2153
2154/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2155/// a loop header, making it a potential recurrence, or it doesn't.
2156///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002157const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002158 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002159 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002160 if (L->getHeader() == PN->getParent()) {
2161 // If it lives in the loop header, it has two incoming values, one
2162 // from outside the loop, and one from inside.
2163 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2164 unsigned BackEdge = IncomingEdge^1;
2165
2166 // While we are analyzing this PHI node, handle its value symbolically.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002167 const SCEV* SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168 assert(Scalars.find(PN) == Scalars.end() &&
2169 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002170 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002171
2172 // Using this symbolic name for the PHI, analyze the value coming around
2173 // the back-edge.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002174 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175
2176 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2177 // has a special value for the first iteration of the loop.
2178
2179 // If the value coming around the backedge is an add with the symbolic
2180 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002181 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002182 // If there is a single occurrence of the symbolic value, replace it
2183 // with a recurrence.
2184 unsigned FoundIndex = Add->getNumOperands();
2185 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2186 if (Add->getOperand(i) == SymbolicName)
2187 if (FoundIndex == e) {
2188 FoundIndex = i;
2189 break;
2190 }
2191
2192 if (FoundIndex != Add->getNumOperands()) {
2193 // Create an add with everything but the specified operand.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002194 SmallVector<const SCEV*, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002195 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2196 if (i != FoundIndex)
2197 Ops.push_back(Add->getOperand(i));
Owen Andersonecd0cd72009-06-22 21:39:50 +00002198 const SCEV* Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002199
2200 // This is not a valid addrec if the step amount is varying each
2201 // loop iteration, but is not itself an addrec in this loop.
2202 if (Accum->isLoopInvariant(L) ||
2203 (isa<SCEVAddRecExpr>(Accum) &&
2204 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002205 const SCEV *StartVal =
2206 getSCEV(PN->getIncomingValue(IncomingEdge));
2207 const SCEV *PHISCEV =
2208 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209
2210 // Okay, for the entire analysis of this edge we assumed the PHI
2211 // to be symbolic. We now need to go back and update all of the
2212 // entries for the scalars that use the PHI (except for the PHI
2213 // itself) to use the new analyzed value instead of the "symbolic"
2214 // value.
2215 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2216 return PHISCEV;
2217 }
2218 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002219 } else if (const SCEVAddRecExpr *AddRec =
2220 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221 // Otherwise, this could be a loop like this:
2222 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2223 // In this case, j = {1,+,1} and BEValue is j.
2224 // Because the other in-value of i (0) fits the evolution of BEValue
2225 // i really is an addrec evolution.
2226 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002227 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002228
2229 // If StartVal = j.start - j.stride, we can use StartVal as the
2230 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002231 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002232 AddRec->getOperand(1))) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002233 const SCEV* PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002234 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235
2236 // Okay, for the entire analysis of this edge we assumed the PHI
2237 // to be symbolic. We now need to go back and update all of the
2238 // entries for the scalars that use the PHI (except for the PHI
2239 // itself) to use the new analyzed value instead of the "symbolic"
2240 // value.
2241 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2242 return PHISCEV;
2243 }
2244 }
2245 }
2246
2247 return SymbolicName;
2248 }
2249
2250 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002251 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002252}
2253
Dan Gohman509cf4d2009-05-08 20:26:55 +00002254/// createNodeForGEP - Expand GEP instructions into add and multiply
2255/// operations. This allows them to be analyzed by regular SCEV code.
2256///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002257const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002258
2259 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002260 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002261 // Don't attempt to analyze GEPs over unsized objects.
2262 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2263 return getUnknown(GEP);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002264 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002265 gep_type_iterator GTI = gep_type_begin(GEP);
2266 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2267 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002268 I != E; ++I) {
2269 Value *Index = *I;
2270 // Compute the (potentially symbolic) offset in bytes for this index.
2271 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2272 // For a struct, add the member offset.
2273 const StructLayout &SL = *TD->getStructLayout(STy);
2274 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2275 uint64_t Offset = SL.getElementOffset(FieldNo);
2276 TotalOffset = getAddExpr(TotalOffset,
2277 getIntegerSCEV(Offset, IntPtrTy));
2278 } else {
2279 // For an array, add the element offset, explicitly scaled.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002280 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002281 if (!isa<PointerType>(LocalOffset->getType()))
2282 // Getelementptr indicies are signed.
2283 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2284 IntPtrTy);
2285 LocalOffset =
2286 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002287 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002288 IntPtrTy));
2289 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2290 }
2291 }
2292 return getAddExpr(getSCEV(Base), TotalOffset);
2293}
2294
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002295/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2296/// guaranteed to end in (at every loop iteration). It is, at the same time,
2297/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2298/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002299uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002300ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002301 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002302 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303
Dan Gohmanc76b5452009-05-04 22:02:23 +00002304 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002305 return std::min(GetMinTrailingZeros(T->getOperand()),
2306 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002307
Dan Gohmanc76b5452009-05-04 22:02:23 +00002308 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002309 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2310 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2311 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002312 }
2313
Dan Gohmanc76b5452009-05-04 22:02:23 +00002314 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002315 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2316 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2317 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002318 }
2319
Dan Gohmanc76b5452009-05-04 22:02:23 +00002320 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002321 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002322 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002323 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002324 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002325 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002326 }
2327
Dan Gohmanc76b5452009-05-04 22:02:23 +00002328 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002329 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002330 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2331 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002332 for (unsigned i = 1, e = M->getNumOperands();
2333 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002334 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002335 BitWidth);
2336 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002337 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002338
Dan Gohmanc76b5452009-05-04 22:02:23 +00002339 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002340 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002341 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002342 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002343 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002344 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002345 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002346
Dan Gohmanc76b5452009-05-04 22:02:23 +00002347 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002348 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002349 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002350 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002351 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002352 return MinOpRes;
2353 }
2354
Dan Gohmanc76b5452009-05-04 22:02:23 +00002355 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002356 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002357 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002358 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002359 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002360 return MinOpRes;
2361 }
2362
Dan Gohman6e923a72009-06-19 23:29:04 +00002363 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2364 // For a SCEVUnknown, ask ValueTracking.
2365 unsigned BitWidth = getTypeSizeInBits(U->getType());
2366 APInt Mask = APInt::getAllOnesValue(BitWidth);
2367 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2368 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2369 return Zeros.countTrailingOnes();
2370 }
2371
2372 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002373 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002374}
2375
Dan Gohman6e923a72009-06-19 23:29:04 +00002376uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002377ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002378 // TODO: Handle other SCEV expression types here.
2379
2380 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2381 return C->getValue()->getValue().countLeadingZeros();
2382
2383 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2384 // A zero-extension cast adds zero bits.
2385 return GetMinLeadingZeros(C->getOperand()) +
2386 (getTypeSizeInBits(C->getType()) -
2387 getTypeSizeInBits(C->getOperand()->getType()));
2388 }
2389
2390 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2391 // For a SCEVUnknown, ask ValueTracking.
2392 unsigned BitWidth = getTypeSizeInBits(U->getType());
2393 APInt Mask = APInt::getAllOnesValue(BitWidth);
2394 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2395 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2396 return Zeros.countLeadingOnes();
2397 }
2398
2399 return 1;
2400}
2401
2402uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002403ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002404 // TODO: Handle other SCEV expression types here.
2405
2406 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2407 const APInt &A = C->getValue()->getValue();
2408 return A.isNegative() ? A.countLeadingOnes() :
2409 A.countLeadingZeros();
2410 }
2411
2412 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2413 // A sign-extension cast adds sign bits.
2414 return GetMinSignBits(C->getOperand()) +
2415 (getTypeSizeInBits(C->getType()) -
2416 getTypeSizeInBits(C->getOperand()->getType()));
2417 }
2418
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002419 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2420 unsigned BitWidth = getTypeSizeInBits(A->getType());
2421
2422 // Special case decrementing a value (ADD X, -1):
2423 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2424 if (CRHS->isAllOnesValue()) {
2425 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2426 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2427 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2428
2429 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2430 // sign bits set.
2431 if (LZ == BitWidth - 1)
2432 return BitWidth;
2433
2434 // If we are subtracting one from a positive number, there is no carry
2435 // out of the result.
2436 if (LZ > 0)
2437 return GetMinSignBits(OtherOpsAdd);
2438 }
2439
2440 // Add can have at most one carry bit. Thus we know that the output
2441 // is, at worst, one more bit than the inputs.
2442 unsigned Min = BitWidth;
2443 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2444 unsigned N = GetMinSignBits(A->getOperand(i));
2445 Min = std::min(Min, N) - 1;
2446 if (Min == 0) return 1;
2447 }
2448 return 1;
2449 }
2450
Dan Gohman6e923a72009-06-19 23:29:04 +00002451 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2452 // For a SCEVUnknown, ask ValueTracking.
2453 return ComputeNumSignBits(U->getValue(), TD);
2454 }
2455
2456 return 1;
2457}
2458
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459/// createSCEV - We know that there is no SCEV for the specified value.
2460/// Analyze the expression.
2461///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002462const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002463 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002464 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002465
Dan Gohman3996f472008-06-22 19:56:46 +00002466 unsigned Opcode = Instruction::UserOp1;
2467 if (Instruction *I = dyn_cast<Instruction>(V))
2468 Opcode = I->getOpcode();
2469 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2470 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002471 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2472 return getConstant(CI);
2473 else if (isa<ConstantPointerNull>(V))
2474 return getIntegerSCEV(0, V->getType());
2475 else if (isa<UndefValue>(V))
2476 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002477 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002478 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002479
Dan Gohman3996f472008-06-22 19:56:46 +00002480 User *U = cast<User>(V);
2481 switch (Opcode) {
2482 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002483 return getAddExpr(getSCEV(U->getOperand(0)),
2484 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002485 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002486 return getMulExpr(getSCEV(U->getOperand(0)),
2487 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002488 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002489 return getUDivExpr(getSCEV(U->getOperand(0)),
2490 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002491 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002492 return getMinusSCEV(getSCEV(U->getOperand(0)),
2493 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002494 case Instruction::And:
2495 // For an expression like x&255 that merely masks off the high bits,
2496 // use zext(trunc(x)) as the SCEV expression.
2497 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002498 if (CI->isNullValue())
2499 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002500 if (CI->isAllOnesValue())
2501 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002502 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002503
2504 // Instcombine's ShrinkDemandedConstant may strip bits out of
2505 // constants, obscuring what would otherwise be a low-bits mask.
2506 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2507 // knew about to reconstruct a low-bits mask value.
2508 unsigned LZ = A.countLeadingZeros();
2509 unsigned BitWidth = A.getBitWidth();
2510 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2511 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2512 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2513
2514 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2515
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002516 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002517 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002518 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002519 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002520 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002521 }
2522 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002523
Dan Gohman3996f472008-06-22 19:56:46 +00002524 case Instruction::Or:
2525 // If the RHS of the Or is a constant, we may have something like:
2526 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2527 // optimizations will transparently handle this case.
2528 //
2529 // In order for this transformation to be safe, the LHS must be of the
2530 // form X*(2^n) and the Or constant must be less than 2^n.
2531 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002532 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002533 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002534 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002535 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002536 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002537 }
Dan Gohman3996f472008-06-22 19:56:46 +00002538 break;
2539 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002540 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002541 // If the RHS of the xor is a signbit, then this is just an add.
2542 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002543 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002544 return getAddExpr(getSCEV(U->getOperand(0)),
2545 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002546
2547 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002548 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002549 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002550
2551 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2552 // This is a variant of the check for xor with -1, and it handles
2553 // the case where instcombine has trimmed non-demanded bits out
2554 // of an xor with -1.
2555 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2556 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2557 if (BO->getOpcode() == Instruction::And &&
2558 LCI->getValue() == CI->getValue())
2559 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002560 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002561 const Type *UTy = U->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00002562 const SCEV* Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002563 const Type *Z0Ty = Z0->getType();
2564 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2565
2566 // If C is a low-bits mask, the zero extend is zerving to
2567 // mask off the high bits. Complement the operand and
2568 // re-apply the zext.
2569 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2570 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2571
2572 // If C is a single bit, it may be in the sign-bit position
2573 // before the zero-extend. In this case, represent the xor
2574 // using an add, which is equivalent, and re-apply the zext.
2575 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2576 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2577 Trunc.isSignBit())
2578 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2579 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002580 }
Dan Gohman3996f472008-06-22 19:56:46 +00002581 }
2582 break;
2583
2584 case Instruction::Shl:
2585 // Turn shift left of a constant amount into a multiply.
2586 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2587 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2588 Constant *X = ConstantInt::get(
2589 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002590 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002591 }
2592 break;
2593
Nick Lewycky7fd27892008-07-07 06:15:49 +00002594 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002595 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002596 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2597 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2598 Constant *X = ConstantInt::get(
2599 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002600 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002601 }
2602 break;
2603
Dan Gohman53bf64a2009-04-21 02:26:00 +00002604 case Instruction::AShr:
2605 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2606 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2607 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2608 if (L->getOpcode() == Instruction::Shl &&
2609 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002610 unsigned BitWidth = getTypeSizeInBits(U->getType());
2611 uint64_t Amt = BitWidth - CI->getZExtValue();
2612 if (Amt == BitWidth)
2613 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2614 if (Amt > BitWidth)
2615 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002616 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002617 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002618 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002619 U->getType());
2620 }
2621 break;
2622
Dan Gohman3996f472008-06-22 19:56:46 +00002623 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002624 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002625
2626 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002627 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002628
2629 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002630 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002631
2632 case Instruction::BitCast:
2633 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002634 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002635 return getSCEV(U->getOperand(0));
2636 break;
2637
Dan Gohman01c2ee72009-04-16 03:18:22 +00002638 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002639 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002640 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002641 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002642
2643 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002644 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002645 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2646 U->getType());
2647
Dan Gohman509cf4d2009-05-08 20:26:55 +00002648 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002649 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002650 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002651
Dan Gohman3996f472008-06-22 19:56:46 +00002652 case Instruction::PHI:
2653 return createNodeForPHI(cast<PHINode>(U));
2654
2655 case Instruction::Select:
2656 // This could be a smax or umax that was lowered earlier.
2657 // Try to recover it.
2658 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2659 Value *LHS = ICI->getOperand(0);
2660 Value *RHS = ICI->getOperand(1);
2661 switch (ICI->getPredicate()) {
2662 case ICmpInst::ICMP_SLT:
2663 case ICmpInst::ICMP_SLE:
2664 std::swap(LHS, RHS);
2665 // fall through
2666 case ICmpInst::ICMP_SGT:
2667 case ICmpInst::ICMP_SGE:
2668 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002669 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002670 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002671 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002672 break;
2673 case ICmpInst::ICMP_ULT:
2674 case ICmpInst::ICMP_ULE:
2675 std::swap(LHS, RHS);
2676 // fall through
2677 case ICmpInst::ICMP_UGT:
2678 case ICmpInst::ICMP_UGE:
2679 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002680 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002681 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002682 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002683 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002684 case ICmpInst::ICMP_NE:
2685 // n != 0 ? n : 1 -> umax(n, 1)
2686 if (LHS == U->getOperand(1) &&
2687 isa<ConstantInt>(U->getOperand(2)) &&
2688 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2689 isa<ConstantInt>(RHS) &&
2690 cast<ConstantInt>(RHS)->isZero())
2691 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2692 break;
2693 case ICmpInst::ICMP_EQ:
2694 // n == 0 ? 1 : n -> umax(n, 1)
2695 if (LHS == U->getOperand(2) &&
2696 isa<ConstantInt>(U->getOperand(1)) &&
2697 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2698 isa<ConstantInt>(RHS) &&
2699 cast<ConstantInt>(RHS)->isZero())
2700 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2701 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002702 default:
2703 break;
2704 }
2705 }
2706
2707 default: // We cannot analyze this expression.
2708 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002709 }
2710
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002711 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002712}
2713
2714
2715
2716//===----------------------------------------------------------------------===//
2717// Iteration Count Computation Code
2718//
2719
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002720/// getBackedgeTakenCount - If the specified loop has a predictable
2721/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2722/// object. The backedge-taken count is the number of times the loop header
2723/// will be branched to from within the loop. This is one less than the
2724/// trip count of the loop, since it doesn't count the first iteration,
2725/// when the header is branched to from outside the loop.
2726///
2727/// Note that it is not valid to call this method on a loop without a
2728/// loop-invariant backedge-taken count (see
2729/// hasLoopInvariantBackedgeTakenCount).
2730///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002731const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002732 return getBackedgeTakenInfo(L).Exact;
2733}
2734
2735/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2736/// return the least SCEV value that is known never to be less than the
2737/// actual backedge taken count.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002738const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002739 return getBackedgeTakenInfo(L).Max;
2740}
2741
2742const ScalarEvolution::BackedgeTakenInfo &
2743ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002744 // Initially insert a CouldNotCompute for this loop. If the insertion
2745 // succeeds, procede to actually compute a backedge-taken count and
2746 // update the value. The temporary CouldNotCompute value tells SCEV
2747 // code elsewhere that it shouldn't attempt to request a new
2748 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002749 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002750 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2751 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002752 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002753 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002754 assert(ItCount.Exact->isLoopInvariant(L) &&
2755 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002756 "Computed trip count isn't loop invariant for loop!");
2757 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002758
Dan Gohmana9dba962009-04-27 20:16:15 +00002759 // Update the value in the map.
2760 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002761 } else {
2762 if (ItCount.Max != CouldNotCompute)
2763 // Update the value in the map.
2764 Pair.first->second = ItCount;
2765 if (isa<PHINode>(L->getHeader()->begin()))
2766 // Only count loops that have phi nodes as not being computable.
2767 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002769
2770 // Now that we know more about the trip count for this loop, forget any
2771 // existing SCEV values for PHI nodes in this loop since they are only
2772 // conservative estimates made without the benefit
2773 // of trip count information.
2774 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002775 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002776 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002777 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002778}
2779
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002780/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002781/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002782/// ScalarEvolution's ability to compute a trip count, or if the loop
2783/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002784void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002785 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002786 forgetLoopPHIs(L);
2787}
2788
2789/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2790/// PHI nodes in the given loop. This is used when the trip count of
2791/// the loop may have changed.
2792void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002793 BasicBlock *Header = L->getHeader();
2794
Dan Gohman9fd4a002009-05-12 01:27:58 +00002795 // Push all Loop-header PHIs onto the Worklist stack, except those
2796 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2797 // a PHI either means that it has an unrecognized structure, or it's
2798 // a PHI that's in the progress of being computed by createNodeForPHI.
2799 // In the former case, additional loop trip count information isn't
2800 // going to change anything. In the later case, createNodeForPHI will
2801 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002802 SmallVector<Instruction *, 16> Worklist;
2803 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002804 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002805 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2806 Scalars.find((Value*)I);
Dan Gohman9fd4a002009-05-12 01:27:58 +00002807 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2808 Worklist.push_back(PN);
2809 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002810
2811 while (!Worklist.empty()) {
2812 Instruction *I = Worklist.pop_back_val();
2813 if (Scalars.erase(I))
2814 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2815 UI != UE; ++UI)
2816 Worklist.push_back(cast<Instruction>(UI));
2817 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002818}
2819
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002820/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2821/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002822ScalarEvolution::BackedgeTakenInfo
2823ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002824 SmallVector<BasicBlock*, 8> ExitingBlocks;
2825 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002826
Dan Gohman8e8b5232009-06-22 00:31:57 +00002827 // Examine all exits and pick the most conservative values.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002828 const SCEV* BECount = CouldNotCompute;
2829 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002830 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002831 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2832 BackedgeTakenInfo NewBTI =
2833 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002834
Dan Gohman8e8b5232009-06-22 00:31:57 +00002835 if (NewBTI.Exact == CouldNotCompute) {
2836 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002837 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002838 CouldNotComputeBECount = true;
2839 BECount = CouldNotCompute;
2840 } else if (!CouldNotComputeBECount) {
2841 if (BECount == CouldNotCompute)
2842 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002843 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00002844 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002845 }
Dan Gohman423ed6c2009-06-24 01:18:18 +00002846 if (MaxBECount == CouldNotCompute)
2847 MaxBECount = NewBTI.Max;
2848 else if (NewBTI.Max != CouldNotCompute)
2849 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002850 }
2851
2852 return BackedgeTakenInfo(BECount, MaxBECount);
2853}
2854
2855/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2856/// of the specified loop will execute if it exits via the specified block.
2857ScalarEvolution::BackedgeTakenInfo
2858ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2859 BasicBlock *ExitingBlock) {
2860
2861 // Okay, we've chosen an exiting block. See what condition causes us to
2862 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863 //
2864 // FIXME: we should be able to handle switch instructions (with a single exit)
2865 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002866 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00002868
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869 // At this point, we know we have a conditional branch that determines whether
2870 // the loop is exited. However, we don't know if the branch is executed each
2871 // time through the loop. If not, then the execution count of the branch will
2872 // not be equal to the trip count of the loop.
2873 //
2874 // Currently we check for this by checking to see if the Exit branch goes to
2875 // the loop header. If so, we know it will always execute the same number of
2876 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00002877 // loop header. This is common for un-rotated loops.
2878 //
2879 // If both of those tests fail, walk up the unique predecessor chain to the
2880 // header, stopping if there is an edge that doesn't exit the loop. If the
2881 // header is reached, the execution count of the branch will be equal to the
2882 // trip count of the loop.
2883 //
2884 // More extensive analysis could be done to handle more cases here.
2885 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2887 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00002888 ExitBr->getParent() != L->getHeader()) {
2889 // The simple checks failed, try climbing the unique predecessor chain
2890 // up to the header.
2891 bool Ok = false;
2892 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
2893 BasicBlock *Pred = BB->getUniquePredecessor();
2894 if (!Pred)
2895 return CouldNotCompute;
2896 TerminatorInst *PredTerm = Pred->getTerminator();
2897 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
2898 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
2899 if (PredSucc == BB)
2900 continue;
2901 // If the predecessor has a successor that isn't BB and isn't
2902 // outside the loop, assume the worst.
2903 if (L->contains(PredSucc))
2904 return CouldNotCompute;
2905 }
2906 if (Pred == L->getHeader()) {
2907 Ok = true;
2908 break;
2909 }
2910 BB = Pred;
2911 }
2912 if (!Ok)
2913 return CouldNotCompute;
2914 }
2915
2916 // Procede to the next level to examine the exit condition expression.
2917 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
2918 ExitBr->getSuccessor(0),
2919 ExitBr->getSuccessor(1));
2920}
2921
2922/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
2923/// backedge of the specified loop will execute if its exit condition
2924/// were a conditional branch of ExitCond, TBB, and FBB.
2925ScalarEvolution::BackedgeTakenInfo
2926ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
2927 Value *ExitCond,
2928 BasicBlock *TBB,
2929 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00002930 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002931 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
2932 if (BO->getOpcode() == Instruction::And) {
2933 // Recurse on the operands of the and.
2934 BackedgeTakenInfo BTI0 =
2935 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2936 BackedgeTakenInfo BTI1 =
2937 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002938 const SCEV* BECount = CouldNotCompute;
2939 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002940 if (L->contains(TBB)) {
2941 // Both conditions must be true for the loop to continue executing.
2942 // Choose the less conservative count.
Dan Gohman2cc450e2009-06-22 23:28:56 +00002943 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2944 BECount = CouldNotCompute;
Dan Gohmanac958b32009-06-22 15:09:28 +00002945 else
2946 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002947 if (BTI0.Max == CouldNotCompute)
2948 MaxBECount = BTI1.Max;
2949 else if (BTI1.Max == CouldNotCompute)
2950 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00002951 else
2952 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002953 } else {
2954 // Both conditions must be true for the loop to exit.
2955 assert(L->contains(FBB) && "Loop block has no successor in loop!");
2956 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2957 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2958 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2959 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2960 }
2961
2962 return BackedgeTakenInfo(BECount, MaxBECount);
2963 }
2964 if (BO->getOpcode() == Instruction::Or) {
2965 // Recurse on the operands of the or.
2966 BackedgeTakenInfo BTI0 =
2967 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2968 BackedgeTakenInfo BTI1 =
2969 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002970 const SCEV* BECount = CouldNotCompute;
2971 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002972 if (L->contains(FBB)) {
2973 // Both conditions must be false for the loop to continue executing.
2974 // Choose the less conservative count.
Dan Gohman2cc450e2009-06-22 23:28:56 +00002975 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2976 BECount = CouldNotCompute;
Dan Gohmanac958b32009-06-22 15:09:28 +00002977 else
2978 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002979 if (BTI0.Max == CouldNotCompute)
2980 MaxBECount = BTI1.Max;
2981 else if (BTI1.Max == CouldNotCompute)
2982 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00002983 else
2984 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002985 } else {
2986 // Both conditions must be false for the loop to exit.
2987 assert(L->contains(TBB) && "Loop block has no successor in loop!");
2988 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2989 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2990 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2991 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2992 }
2993
2994 return BackedgeTakenInfo(BECount, MaxBECount);
2995 }
2996 }
2997
2998 // With an icmp, it may be feasible to compute an exact backedge-taken count.
2999 // Procede to the next level to examine the icmp.
3000 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3001 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003002
Eli Friedman459d7292009-05-09 12:32:42 +00003003 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00003004 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3005}
3006
3007/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3008/// backedge of the specified loop will execute if its exit condition
3009/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3010ScalarEvolution::BackedgeTakenInfo
3011ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3012 ICmpInst *ExitCond,
3013 BasicBlock *TBB,
3014 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003015
3016 // If the condition was exit on true, convert the condition to exit on false
3017 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00003018 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003019 Cond = ExitCond->getPredicate();
3020 else
3021 Cond = ExitCond->getInversePredicate();
3022
3023 // Handle common loops like: for (X = "string"; *X; ++X)
3024 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3025 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003026 const SCEV* ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003027 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00003028 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3029 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3030 return BackedgeTakenInfo(ItCnt,
3031 isa<SCEVConstant>(ItCnt) ? ItCnt :
3032 getConstant(APInt::getMaxValue(BitWidth)-1));
3033 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003034 }
3035
Owen Andersonecd0cd72009-06-22 21:39:50 +00003036 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3037 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038
3039 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003040 LHS = getSCEVAtScope(LHS, L);
3041 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003042
Dan Gohman9bc642f2009-06-24 04:48:43 +00003043 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003044 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003045 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3046 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 std::swap(LHS, RHS);
3048 Cond = ICmpInst::getSwappedPredicate(Cond);
3049 }
3050
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051 // If we have a comparison of a chrec against a constant, try to use value
3052 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003053 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3054 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003055 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003056 // Form the constant range.
3057 ConstantRange CompRange(
3058 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003059
Owen Andersonecd0cd72009-06-22 21:39:50 +00003060 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003061 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003062 }
3063
3064 switch (Cond) {
3065 case ICmpInst::ICMP_NE: { // while (X != Y)
3066 // Convert to: while (X-Y != 0)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003067 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003068 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3069 break;
3070 }
3071 case ICmpInst::ICMP_EQ: {
3072 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003073 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003074 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3075 break;
3076 }
3077 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003078 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3079 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003080 break;
3081 }
3082 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003083 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3084 getNotSCEV(RHS), L, true);
3085 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003086 break;
3087 }
3088 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003089 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3090 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003091 break;
3092 }
3093 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003094 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3095 getNotSCEV(RHS), L, false);
3096 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097 break;
3098 }
3099 default:
3100#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003101 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003102 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003103 errs() << "[unsigned] ";
3104 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003105 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003106 << " " << *RHS << "\n";
3107#endif
3108 break;
3109 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003110 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003111 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003112}
3113
3114static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003115EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3116 ScalarEvolution &SE) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003117 const SCEV* InVal = SE.getConstant(C);
3118 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003119 assert(isa<SCEVConstant>(Val) &&
3120 "Evaluation of SCEV at constant didn't fold correctly?");
3121 return cast<SCEVConstant>(Val)->getValue();
3122}
3123
3124/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3125/// and a GEP expression (missing the pointer index) indexing into it, return
3126/// the addressed element of the initializer or null if the index expression is
3127/// invalid.
3128static Constant *
3129GetAddressedElementFromGlobal(GlobalVariable *GV,
3130 const std::vector<ConstantInt*> &Indices) {
3131 Constant *Init = GV->getInitializer();
3132 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3133 uint64_t Idx = Indices[i]->getZExtValue();
3134 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3135 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3136 Init = cast<Constant>(CS->getOperand(Idx));
3137 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3138 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3139 Init = cast<Constant>(CA->getOperand(Idx));
3140 } else if (isa<ConstantAggregateZero>(Init)) {
3141 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3142 assert(Idx < STy->getNumElements() && "Bad struct index!");
3143 Init = Constant::getNullValue(STy->getElementType(Idx));
3144 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3145 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3146 Init = Constant::getNullValue(ATy->getElementType());
3147 } else {
3148 assert(0 && "Unknown constant aggregate type!");
3149 }
3150 return 0;
3151 } else {
3152 return 0; // Unknown initializer type
3153 }
3154 }
3155 return Init;
3156}
3157
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003158/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3159/// 'icmp op load X, cst', try to see if we can compute the backedge
3160/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003161const SCEV *
3162ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3163 LoadInst *LI,
3164 Constant *RHS,
3165 const Loop *L,
3166 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00003167 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168
3169 // Check to see if the loaded pointer is a getelementptr of a global.
3170 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00003171 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003172
3173 // Make sure that it is really a constant global we are gepping, with an
3174 // initializer, and make sure the first IDX is really 0.
3175 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3176 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3177 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3178 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00003179 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003180
3181 // Okay, we allow one non-constant index into the GEP instruction.
3182 Value *VarIdx = 0;
3183 std::vector<ConstantInt*> Indexes;
3184 unsigned VarIdxNum = 0;
3185 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3186 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3187 Indexes.push_back(CI);
3188 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00003189 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003190 VarIdx = GEP->getOperand(i);
3191 VarIdxNum = i-2;
3192 Indexes.push_back(0);
3193 }
3194
3195 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3196 // Check to see if X is a loop variant variable value now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003197 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003198 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003199
3200 // We can only recognize very limited forms of loop index expressions, in
3201 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003202 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3204 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3205 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00003206 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207
3208 unsigned MaxSteps = MaxBruteForceIterations;
3209 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3210 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003211 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003212 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213
3214 // Form the GEP offset.
3215 Indexes[VarIdxNum] = Val;
3216
3217 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3218 if (Result == 0) break; // Cannot compute!
3219
3220 // Evaluate the condition for this iteration.
3221 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3222 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3223 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3224#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003225 errs() << "\n***\n*** Computed loop count " << *ItCst
3226 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3227 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003228#endif
3229 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003230 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003231 }
3232 }
Dan Gohman0c850912009-06-06 14:37:11 +00003233 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003234}
3235
3236
3237/// CanConstantFold - Return true if we can constant fold an instruction of the
3238/// specified type, assuming that all operands were constants.
3239static bool CanConstantFold(const Instruction *I) {
3240 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3241 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3242 return true;
3243
3244 if (const CallInst *CI = dyn_cast<CallInst>(I))
3245 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003246 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003247 return false;
3248}
3249
3250/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3251/// in the loop that V is derived from. We allow arbitrary operations along the
3252/// way, but the operands of an operation must either be constants or a value
3253/// derived from a constant PHI. If this expression does not fit with these
3254/// constraints, return null.
3255static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3256 // If this is not an instruction, or if this is an instruction outside of the
3257 // loop, it can't be derived from a loop PHI.
3258 Instruction *I = dyn_cast<Instruction>(V);
3259 if (I == 0 || !L->contains(I->getParent())) return 0;
3260
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003261 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003262 if (L->getHeader() == I->getParent())
3263 return PN;
3264 else
3265 // We don't currently keep track of the control flow needed to evaluate
3266 // PHIs, so we cannot handle PHIs inside of loops.
3267 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003268 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003269
3270 // If we won't be able to constant fold this expression even if the operands
3271 // are constants, return early.
3272 if (!CanConstantFold(I)) return 0;
3273
3274 // Otherwise, we can evaluate this instruction if all of its operands are
3275 // constant or derived from a PHI node themselves.
3276 PHINode *PHI = 0;
3277 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3278 if (!(isa<Constant>(I->getOperand(Op)) ||
3279 isa<GlobalValue>(I->getOperand(Op)))) {
3280 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3281 if (P == 0) return 0; // Not evolving from PHI
3282 if (PHI == 0)
3283 PHI = P;
3284 else if (PHI != P)
3285 return 0; // Evolving from multiple different PHIs.
3286 }
3287
3288 // This is a expression evolving from a constant PHI!
3289 return PHI;
3290}
3291
3292/// EvaluateExpression - Given an expression that passes the
3293/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3294/// in the loop has the value PHIVal. If we can't fold this expression for some
3295/// reason, return null.
3296static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3297 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003298 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003299 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003300 Instruction *I = cast<Instruction>(V);
3301
3302 std::vector<Constant*> Operands;
3303 Operands.resize(I->getNumOperands());
3304
3305 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3306 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3307 if (Operands[i] == 0) return 0;
3308 }
3309
Chris Lattnerd6e56912007-12-10 22:53:04 +00003310 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3311 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3312 &Operands[0], Operands.size());
3313 else
3314 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3315 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003316}
3317
3318/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3319/// in the header of its containing loop, we know the loop executes a
3320/// constant number of times, and the PHI node is just a recurrence
3321/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003322Constant *
3323ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3324 const APInt& BEs,
3325 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003326 std::map<PHINode*, Constant*>::iterator I =
3327 ConstantEvolutionLoopExitValue.find(PN);
3328 if (I != ConstantEvolutionLoopExitValue.end())
3329 return I->second;
3330
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003331 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003332 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3333
3334 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3335
3336 // Since the loop is canonicalized, the PHI node must have two entries. One
3337 // entry must be a constant (coming in from outside of the loop), and the
3338 // second must be derived from the same PHI.
3339 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3340 Constant *StartCST =
3341 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3342 if (StartCST == 0)
3343 return RetVal = 0; // Must be a constant.
3344
3345 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3346 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3347 if (PN2 != PN)
3348 return RetVal = 0; // Not derived from same PHI.
3349
3350 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003351 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003352 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3353
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003354 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003355 unsigned IterationNum = 0;
3356 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3357 if (IterationNum == NumIterations)
3358 return RetVal = PHIVal; // Got exit value!
3359
3360 // Compute the value of the PHI node for the next iteration.
3361 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3362 if (NextPHI == PHIVal)
3363 return RetVal = NextPHI; // Stopped evolving!
3364 if (NextPHI == 0)
3365 return 0; // Couldn't evaluate!
3366 PHIVal = NextPHI;
3367 }
3368}
3369
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003370/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003371/// constant number of times (the condition evolves only from constants),
3372/// try to evaluate a few iterations of the loop until we get the exit
3373/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00003374/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003375const SCEV *
3376ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3377 Value *Cond,
3378 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003379 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003380 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003381
3382 // Since the loop is canonicalized, the PHI node must have two entries. One
3383 // entry must be a constant (coming in from outside of the loop), and the
3384 // second must be derived from the same PHI.
3385 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3386 Constant *StartCST =
3387 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00003388 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003389
3390 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3391 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003392 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393
3394 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3395 // the loop symbolically to determine when the condition gets a value of
3396 // "ExitWhen".
3397 unsigned IterationNum = 0;
3398 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3399 for (Constant *PHIVal = StartCST;
3400 IterationNum != MaxIterations; ++IterationNum) {
3401 ConstantInt *CondVal =
3402 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3403
3404 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003405 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406
3407 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3408 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3409 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003410 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411 }
3412
3413 // Compute the value of the PHI node for the next iteration.
3414 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3415 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00003416 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 PHIVal = NextPHI;
3418 }
3419
3420 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003421 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003422}
3423
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003424/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3425/// at the specified scope in the program. The L value specifies a loop
3426/// nest to evaluate the expression at, where null is the top-level or a
3427/// specified loop is immediately inside of the loop.
3428///
3429/// This method can be used to compute the exit value for a variable defined
3430/// in a loop by querying what the value will hold in the parent loop.
3431///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003432/// In the case that a relevant loop exit value cannot be computed, the
3433/// original value V is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003434const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003435 // FIXME: this should be turned into a virtual method on SCEV!
3436
3437 if (isa<SCEVConstant>(V)) return V;
3438
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003439 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003440 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003441 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003443 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3445 if (PHINode *PN = dyn_cast<PHINode>(I))
3446 if (PN->getParent() == LI->getHeader()) {
3447 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003448 // to see if the loop that contains it has a known backedge-taken
3449 // count. If so, we may be able to force computation of the exit
3450 // value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003451 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003452 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003453 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003454 // Okay, we know how many times the containing loop executes. If
3455 // this is a constant evolving PHI node, get the final value at
3456 // the specified iteration number.
3457 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003458 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003459 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003460 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461 }
3462 }
3463
3464 // Okay, this is an expression that we cannot symbolically evaluate
3465 // into a SCEV. Check to see if it's possible to symbolically evaluate
3466 // the arguments into constants, and if so, try to constant propagate the
3467 // result. This is particularly useful for computing loop exit values.
3468 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003469 // Check to see if we've folded this instruction at this loop before.
3470 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3471 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3472 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3473 if (!Pair.second)
3474 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3475
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003476 std::vector<Constant*> Operands;
3477 Operands.reserve(I->getNumOperands());
3478 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3479 Value *Op = I->getOperand(i);
3480 if (Constant *C = dyn_cast<Constant>(Op)) {
3481 Operands.push_back(C);
3482 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003483 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003484 // non-integer and non-pointer, don't even try to analyze them
3485 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003486 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003487 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003488
Owen Andersonecd0cd72009-06-22 21:39:50 +00003489 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003490 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003491 Constant *C = SC->getValue();
3492 if (C->getType() != Op->getType())
3493 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3494 Op->getType(),
3495 false),
3496 C, Op->getType());
3497 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003498 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003499 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3500 if (C->getType() != Op->getType())
3501 C =
3502 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3503 Op->getType(),
3504 false),
3505 C, Op->getType());
3506 Operands.push_back(C);
3507 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003508 return V;
3509 } else {
3510 return V;
3511 }
3512 }
3513 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003514
Chris Lattnerd6e56912007-12-10 22:53:04 +00003515 Constant *C;
3516 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3517 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3518 &Operands[0], Operands.size());
3519 else
3520 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3521 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003522 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003523 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524 }
3525 }
3526
3527 // This is some other type of SCEVUnknown, just return it.
3528 return V;
3529 }
3530
Dan Gohmanc76b5452009-05-04 22:02:23 +00003531 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003532 // Avoid performing the look-up in the common case where the specified
3533 // expression has no loop-variant portions.
3534 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003535 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003536 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003537 // Okay, at least one of these operands is loop variant but might be
3538 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003539 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3540 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003541 NewOps.push_back(OpAtScope);
3542
3543 for (++i; i != e; ++i) {
3544 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003545 NewOps.push_back(OpAtScope);
3546 }
3547 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003548 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003549 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003550 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003551 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003552 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003553 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003554 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003555 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003556 }
3557 }
3558 // If we got here, all operands are loop invariant.
3559 return Comm;
3560 }
3561
Dan Gohmanc76b5452009-05-04 22:02:23 +00003562 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003563 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3564 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003565 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3566 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003567 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003568 }
3569
3570 // If this is a loop recurrence for a loop that does not contain L, then we
3571 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003572 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003573 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3574 // To evaluate this recurrence, we need to know how many times the AddRec
3575 // loop iterates. Compute this now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003576 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003577 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578
Eli Friedman7489ec92008-08-04 23:49:06 +00003579 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003580 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003581 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003582 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003583 }
3584
Dan Gohmanc76b5452009-05-04 22:02:23 +00003585 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003586 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003587 if (Op == Cast->getOperand())
3588 return Cast; // must be loop invariant
3589 return getZeroExtendExpr(Op, Cast->getType());
3590 }
3591
Dan Gohmanc76b5452009-05-04 22:02:23 +00003592 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003593 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003594 if (Op == Cast->getOperand())
3595 return Cast; // must be loop invariant
3596 return getSignExtendExpr(Op, Cast->getType());
3597 }
3598
Dan Gohmanc76b5452009-05-04 22:02:23 +00003599 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003600 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003601 if (Op == Cast->getOperand())
3602 return Cast; // must be loop invariant
3603 return getTruncateExpr(Op, Cast->getType());
3604 }
3605
3606 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003607 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003608}
3609
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003610/// getSCEVAtScope - This is a convenience function which does
3611/// getSCEVAtScope(getSCEV(V), L).
Owen Andersonecd0cd72009-06-22 21:39:50 +00003612const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003613 return getSCEVAtScope(getSCEV(V), L);
3614}
3615
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003616/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3617/// following equation:
3618///
3619/// A * X = B (mod N)
3620///
3621/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3622/// A and B isn't important.
3623///
3624/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003625static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003626 ScalarEvolution &SE) {
3627 uint32_t BW = A.getBitWidth();
3628 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3629 assert(A != 0 && "A must be non-zero.");
3630
3631 // 1. D = gcd(A, N)
3632 //
3633 // The gcd of A and N may have only one prime factor: 2. The number of
3634 // trailing zeros in A is its multiplicity
3635 uint32_t Mult2 = A.countTrailingZeros();
3636 // D = 2^Mult2
3637
3638 // 2. Check if B is divisible by D.
3639 //
3640 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3641 // is not less than multiplicity of this prime factor for D.
3642 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003643 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003644
3645 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3646 // modulo (N / D).
3647 //
3648 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3649 // bit width during computations.
3650 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3651 APInt Mod(BW + 1, 0);
3652 Mod.set(BW - Mult2); // Mod = N / D
3653 APInt I = AD.multiplicativeInverse(Mod);
3654
3655 // 4. Compute the minimum unsigned root of the equation:
3656 // I * (B / D) mod (N / D)
3657 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3658
3659 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3660 // bits.
3661 return SE.getConstant(Result.trunc(BW));
3662}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003663
3664/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3665/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3666/// might be the same) or two SCEVCouldNotCompute objects.
3667///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003668static std::pair<const SCEV*,const SCEV*>
Dan Gohman89f85052007-10-22 18:31:58 +00003669SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003670 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003671 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3672 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3673 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003674
3675 // We currently can only solve this if the coefficients are constants.
3676 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003677 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003678 return std::make_pair(CNC, CNC);
3679 }
3680
3681 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3682 const APInt &L = LC->getValue()->getValue();
3683 const APInt &M = MC->getValue()->getValue();
3684 const APInt &N = NC->getValue()->getValue();
3685 APInt Two(BitWidth, 2);
3686 APInt Four(BitWidth, 4);
3687
Dan Gohman9bc642f2009-06-24 04:48:43 +00003688 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003689 using namespace APIntOps;
3690 const APInt& C = L;
3691 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3692 // The B coefficient is M-N/2
3693 APInt B(M);
3694 B -= sdiv(N,Two);
3695
3696 // The A coefficient is N/2
3697 APInt A(N.sdiv(Two));
3698
3699 // Compute the B^2-4ac term.
3700 APInt SqrtTerm(B);
3701 SqrtTerm *= B;
3702 SqrtTerm -= Four * (A * C);
3703
3704 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3705 // integer value or else APInt::sqrt() will assert.
3706 APInt SqrtVal(SqrtTerm.sqrt());
3707
Dan Gohman9bc642f2009-06-24 04:48:43 +00003708 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003709 // The divisions must be performed as signed divisions.
3710 APInt NegB(-B);
3711 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003712 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003713 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003714 return std::make_pair(CNC, CNC);
3715 }
3716
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003717 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3718 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3719
Dan Gohman9bc642f2009-06-24 04:48:43 +00003720 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00003721 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003722 } // end APIntOps namespace
3723}
3724
3725/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003726/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003727const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003728 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003729 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730 // If the value is already zero, the branch will execute zero times.
3731 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003732 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003733 }
3734
Dan Gohmanbff6b582009-05-04 22:30:44 +00003735 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003737 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003738
3739 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003740 // If this is an affine expression, the execution count of this branch is
3741 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003742 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003743 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003744 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003745 // equivalent to:
3746 //
3747 // Step*N = -Start (mod 2^BW)
3748 //
3749 // where BW is the common bit width of Start and Step.
3750
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003751 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003752 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3753 L->getParentLoop());
3754 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3755 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003756
Dan Gohmanc76b5452009-05-04 22:02:23 +00003757 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003758 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003759
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003760 // First, handle unitary steps.
3761 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003762 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003763 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3764 return Start; // N = Start (as unsigned)
3765
3766 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003767 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003768 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003769 -StartC->getValue()->getValue(),
3770 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003771 }
3772 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3773 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3774 // the quadratic equation to solve it.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003775 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003776 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003777 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3778 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003779 if (R1) {
3780#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003781 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3782 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003783#endif
3784 // Pick the smallest positive root value.
3785 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00003786 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003787 R1->getValue(), R2->getValue()))) {
3788 if (CB->getZExtValue() == false)
3789 std::swap(R1, R2); // R1 is the minimum root now.
3790
3791 // We can only use this value if the chrec ends up with an exact zero
3792 // value at this index. When solving for "X*X != 5", for example, we
3793 // should not accept a root of 2.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003794 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003795 if (Val->isZero())
3796 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003797 }
3798 }
3799 }
3800
Dan Gohman0c850912009-06-06 14:37:11 +00003801 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003802}
3803
3804/// HowFarToNonZero - Return the number of times a backedge checking the
3805/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003806/// CouldNotCompute
Owen Andersonecd0cd72009-06-22 21:39:50 +00003807const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003808 // Loops that look like: while (X == 0) are very strange indeed. We don't
3809 // handle them yet except for the trivial case. This could be expanded in the
3810 // future as needed.
3811
3812 // If the value is a constant, check to see if it is known to be non-zero
3813 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003814 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003815 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003816 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003817 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003818 }
3819
3820 // We could implement others, but I really doubt anyone writes loops like
3821 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003822 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003823}
3824
Dan Gohmanab157b22009-05-18 15:36:09 +00003825/// getLoopPredecessor - If the given loop's header has exactly one unique
3826/// predecessor outside the loop, return it. Otherwise return null.
3827///
3828BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3829 BasicBlock *Header = L->getHeader();
3830 BasicBlock *Pred = 0;
3831 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3832 PI != E; ++PI)
3833 if (!L->contains(*PI)) {
3834 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3835 Pred = *PI;
3836 }
3837 return Pred;
3838}
3839
Dan Gohman1cddf972008-09-15 22:18:04 +00003840/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3841/// (which may not be an immediate predecessor) which has exactly one
3842/// successor from which BB is reachable, or null if no such block is
3843/// found.
3844///
3845BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003846ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003847 // If the block has a unique predecessor, then there is no path from the
3848 // predecessor to the block that does not go through the direct edge
3849 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003850 if (BasicBlock *Pred = BB->getSinglePredecessor())
3851 return Pred;
3852
3853 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003854 // If the header has a unique predecessor outside the loop, it must be
3855 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003856 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003857 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003858
3859 return 0;
3860}
3861
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003862/// HasSameValue - SCEV structural equivalence is usually sufficient for
3863/// testing whether two expressions are equal, however for the purposes of
3864/// looking for a condition guarding a loop, it can be useful to be a little
3865/// more general, since a front-end may have replicated the controlling
3866/// expression.
3867///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003868static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003869 // Quick check to see if they are the same SCEV.
3870 if (A == B) return true;
3871
3872 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3873 // two different instructions with the same value. Check for this case.
3874 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3875 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3876 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3877 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3878 if (AI->isIdenticalTo(BI))
3879 return true;
3880
3881 // Otherwise assume they may have a different value.
3882 return false;
3883}
3884
Dan Gohmancacd2012009-02-12 22:19:27 +00003885/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003886/// a conditional between LHS and RHS. This is used to help avoid max
3887/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003888bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003889 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003890 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003891 // Interpret a null as meaning no loop, where there is obviously no guard
3892 // (interprocedural conditions notwithstanding).
3893 if (!L) return false;
3894
Dan Gohmanab157b22009-05-18 15:36:09 +00003895 BasicBlock *Predecessor = getLoopPredecessor(L);
3896 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003897
Dan Gohmanab157b22009-05-18 15:36:09 +00003898 // Starting at the loop predecessor, climb up the predecessor chain, as long
3899 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003900 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003901 for (; Predecessor;
3902 PredecessorDest = Predecessor,
3903 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003904
3905 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003906 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003907 if (!LoopEntryPredicate ||
3908 LoopEntryPredicate->isUnconditional())
3909 continue;
3910
Dan Gohman423ed6c2009-06-24 01:18:18 +00003911 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
3912 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003913 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003914 }
3915
Dan Gohmanab678fb2008-08-12 20:17:31 +00003916 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003917}
3918
Dan Gohman423ed6c2009-06-24 01:18:18 +00003919/// isNecessaryCond - Test whether the given CondValue value is a condition
3920/// which is at least as strict as the one described by Pred, LHS, and RHS.
3921bool ScalarEvolution::isNecessaryCond(Value *CondValue,
3922 ICmpInst::Predicate Pred,
3923 const SCEV *LHS, const SCEV *RHS,
3924 bool Inverse) {
3925 // Recursivly handle And and Or conditions.
3926 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
3927 if (BO->getOpcode() == Instruction::And) {
3928 if (!Inverse)
3929 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
3930 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
3931 } else if (BO->getOpcode() == Instruction::Or) {
3932 if (Inverse)
3933 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
3934 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
3935 }
3936 }
3937
3938 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
3939 if (!ICI) return false;
3940
3941 // Now that we found a conditional branch that dominates the loop, check to
3942 // see if it is the comparison we are looking for.
3943 Value *PreCondLHS = ICI->getOperand(0);
3944 Value *PreCondRHS = ICI->getOperand(1);
3945 ICmpInst::Predicate Cond;
3946 if (Inverse)
3947 Cond = ICI->getInversePredicate();
3948 else
3949 Cond = ICI->getPredicate();
3950
3951 if (Cond == Pred)
3952 ; // An exact match.
3953 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3954 ; // The actual condition is beyond sufficient.
3955 else
3956 // Check a few special cases.
3957 switch (Cond) {
3958 case ICmpInst::ICMP_UGT:
3959 if (Pred == ICmpInst::ICMP_ULT) {
3960 std::swap(PreCondLHS, PreCondRHS);
3961 Cond = ICmpInst::ICMP_ULT;
3962 break;
3963 }
3964 return false;
3965 case ICmpInst::ICMP_SGT:
3966 if (Pred == ICmpInst::ICMP_SLT) {
3967 std::swap(PreCondLHS, PreCondRHS);
3968 Cond = ICmpInst::ICMP_SLT;
3969 break;
3970 }
3971 return false;
3972 case ICmpInst::ICMP_NE:
3973 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3974 // so check for this case by checking if the NE is comparing against
3975 // a minimum or maximum constant.
3976 if (!ICmpInst::isTrueWhenEqual(Pred))
3977 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3978 const APInt &A = CI->getValue();
3979 switch (Pred) {
3980 case ICmpInst::ICMP_SLT:
3981 if (A.isMaxSignedValue()) break;
3982 return false;
3983 case ICmpInst::ICMP_SGT:
3984 if (A.isMinSignedValue()) break;
3985 return false;
3986 case ICmpInst::ICMP_ULT:
3987 if (A.isMaxValue()) break;
3988 return false;
3989 case ICmpInst::ICMP_UGT:
3990 if (A.isMinValue()) break;
3991 return false;
3992 default:
3993 return false;
3994 }
3995 Cond = ICmpInst::ICMP_NE;
3996 // NE is symmetric but the original comparison may not be. Swap
3997 // the operands if necessary so that they match below.
3998 if (isa<SCEVConstant>(LHS))
3999 std::swap(PreCondLHS, PreCondRHS);
4000 break;
4001 }
4002 return false;
4003 default:
4004 // We weren't able to reconcile the condition.
4005 return false;
4006 }
4007
4008 if (!PreCondLHS->getType()->isInteger()) return false;
4009
4010 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
4011 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
4012 return (HasSameValue(LHS, PreCondLHSSCEV) &&
4013 HasSameValue(RHS, PreCondRHSSCEV)) ||
4014 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
4015 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
4016}
4017
Dan Gohmand2b62c42009-06-21 23:46:38 +00004018/// getBECount - Subtract the end and start values and divide by the step,
4019/// rounding up, to get the number of times the backedge is executed. Return
4020/// CouldNotCompute if an intermediate computation overflows.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004021const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
4022 const SCEV* End,
4023 const SCEV* Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00004024 const Type *Ty = Start->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00004025 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
4026 const SCEV* Diff = getMinusSCEV(End, Start);
4027 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004028
4029 // Add an adjustment to the difference between End and Start so that
4030 // the division will effectively round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004031 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004032
4033 // Check Add for unsigned overflow.
4034 // TODO: More sophisticated things could be done here.
4035 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
Owen Andersonecd0cd72009-06-22 21:39:50 +00004036 const SCEV* OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004037 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4038 getZeroExtendExpr(RoundUp, WideTy));
4039 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4040 return CouldNotCompute;
4041
4042 return getUDivExpr(Add, Step);
4043}
4044
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004045/// HowManyLessThans - Return the number of times a backedge containing the
4046/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004047/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004048ScalarEvolution::BackedgeTakenInfo
4049ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4050 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004051 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00004052 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004053
Dan Gohmanbff6b582009-05-04 22:30:44 +00004054 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004055 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00004056 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004057
4058 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004059 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004060 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004061 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004062
4063 // TODO: handle non-constant strides.
4064 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4065 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00004066 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004067 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004068 // With unit stride, the iteration never steps past the limit value.
4069 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4070 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4071 // Test whether a positive iteration iteration can step past the limit
4072 // value and past the maximum value for its type in a single step.
4073 if (isSigned) {
4074 APInt Max = APInt::getSignedMaxValue(BitWidth);
4075 if ((Max - CStep->getValue()->getValue())
4076 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00004077 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004078 } else {
4079 APInt Max = APInt::getMaxValue(BitWidth);
4080 if ((Max - CStep->getValue()->getValue())
4081 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00004082 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004083 }
4084 } else
4085 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00004086 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004087 } else
4088 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00004089 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004091 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4092 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4093 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004094 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004095
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004096 // First, we get the value of the LHS in the first iteration: n
Owen Andersonecd0cd72009-06-22 21:39:50 +00004097 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004098
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004099 // Determine the minimum constant start value.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004100 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004101 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4102 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004103
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004104 // If we know that the condition is true in order to enter the loop,
4105 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004106 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4107 // the division must round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004108 const SCEV* End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004109 if (!isLoopGuardedByCond(L,
4110 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4111 getMinusSCEV(Start, Step), RHS))
4112 End = isSigned ? getSMaxExpr(RHS, Start)
4113 : getUMaxExpr(RHS, Start);
4114
4115 // Determine the maximum constant end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004116 const SCEV* MaxEnd =
Dan Gohman92369c32009-06-20 00:32:22 +00004117 isa<SCEVConstant>(End) ? End :
4118 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4119 .ashr(GetMinSignBits(End) - 1) :
4120 APInt::getMaxValue(BitWidth)
4121 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004122
4123 // Finally, we subtract these two values and divide, rounding up, to get
4124 // the number of times the backedge is executed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004125 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004126
4127 // The maximum backedge count is similar, except using the minimum start
4128 // value and the maximum end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004129 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004130
4131 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004132 }
4133
Dan Gohman0c850912009-06-06 14:37:11 +00004134 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135}
4136
4137/// getNumIterationsInRange - Return the number of iterations of this loop that
4138/// produce values in the specified constant range. Another way of looking at
4139/// this is that it returns the first iteration number where the value is not in
4140/// the condition, thus computing the exit count. If the iteration count can't
4141/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004142const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004143 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004144 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004145 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146
4147 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004148 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004149 if (!SC->getValue()->isZero()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00004150 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004151 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004152 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004153 if (const SCEVAddRecExpr *ShiftedAddRec =
4154 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004155 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004156 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004157 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004158 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004159 }
4160
4161 // The only time we can solve this is when we have all constant indices.
4162 // Otherwise, we cannot determine the overflow conditions.
4163 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4164 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004165 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004166
4167
4168 // Okay at this point we know that all elements of the chrec are constants and
4169 // that the start element is zero.
4170
4171 // First check to see if the range contains zero. If not, the first
4172 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004173 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004174 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004175 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004176
4177 if (isAffine()) {
4178 // If this is an affine expression then we have this situation:
4179 // Solve {0,+,A} in Range === Ax in Range
4180
4181 // We know that zero is in the range. If A is positive then we know that
4182 // the upper value of the range must be the first possible exit value.
4183 // If A is negative then the lower of the range is the last possible loop
4184 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004185 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004186 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4187 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4188
4189 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004190 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004191 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
4192
4193 // Evaluate at the exit value. If we really did fall out of the valid
4194 // range, then we computed our trip count, otherwise wrap around or other
4195 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004196 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004197 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004198 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004199
4200 // Ensure that the previous value is in the range. This is a sanity check.
4201 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004202 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004203 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004204 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004205 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 } else if (isQuadratic()) {
4207 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4208 // quadratic equation to solve it. To do this, we must frame our problem in
4209 // terms of figuring out when zero is crossed, instead of when
4210 // Range.getUpper() is crossed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004211 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004212 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Andersonecd0cd72009-06-22 21:39:50 +00004213 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004214
4215 // Next, solve the constructed addrec
Owen Andersonecd0cd72009-06-22 21:39:50 +00004216 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004217 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004218 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4219 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004220 if (R1) {
4221 // Pick the smallest positive root value.
4222 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00004223 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004224 R1->getValue(), R2->getValue()))) {
4225 if (CB->getZExtValue() == false)
4226 std::swap(R1, R2); // R1 is the minimum root now.
4227
4228 // Make sure the root is not off by one. The returned iteration should
4229 // not be in the range, but the previous one should be. When solving
4230 // for "X*X < 5", for example, we should not return a root of 2.
4231 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004232 R1->getValue(),
4233 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004234 if (Range.contains(R1Val->getValue())) {
4235 // The next iteration must be out of the range...
4236 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
4237
Dan Gohman89f85052007-10-22 18:31:58 +00004238 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004239 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004240 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004241 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004242 }
4243
4244 // If R1 was not in the range, then it is a good return value. Make
4245 // sure that R1-1 WAS in the range though, just in case.
4246 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004247 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004248 if (Range.contains(R1Val->getValue()))
4249 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004250 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004251 }
4252 }
4253 }
4254
Dan Gohman0ad08b02009-04-18 17:58:19 +00004255 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004256}
4257
4258
4259
4260//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004261// SCEVCallbackVH Class Implementation
4262//===----------------------------------------------------------------------===//
4263
Dan Gohman999d14e2009-05-19 19:22:47 +00004264void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004265 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4266 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4267 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004268 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4269 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004270 SE->Scalars.erase(getValPtr());
4271 // this now dangles!
4272}
4273
Dan Gohman999d14e2009-05-19 19:22:47 +00004274void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004275 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4276
4277 // Forget all the expressions associated with users of the old value,
4278 // so that future queries will recompute the expressions using the new
4279 // value.
4280 SmallVector<User *, 16> Worklist;
4281 Value *Old = getValPtr();
4282 bool DeleteOld = false;
4283 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4284 UI != UE; ++UI)
4285 Worklist.push_back(*UI);
4286 while (!Worklist.empty()) {
4287 User *U = Worklist.pop_back_val();
4288 // Deleting the Old value will cause this to dangle. Postpone
4289 // that until everything else is done.
4290 if (U == Old) {
4291 DeleteOld = true;
4292 continue;
4293 }
4294 if (PHINode *PN = dyn_cast<PHINode>(U))
4295 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004296 if (Instruction *I = dyn_cast<Instruction>(U))
4297 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004298 if (SE->Scalars.erase(U))
4299 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4300 UI != UE; ++UI)
4301 Worklist.push_back(*UI);
4302 }
4303 if (DeleteOld) {
4304 if (PHINode *PN = dyn_cast<PHINode>(Old))
4305 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004306 if (Instruction *I = dyn_cast<Instruction>(Old))
4307 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004308 SE->Scalars.erase(Old);
4309 // this now dangles!
4310 }
4311 // this may dangle!
4312}
4313
Dan Gohman999d14e2009-05-19 19:22:47 +00004314ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004315 : CallbackVH(V), SE(se) {}
4316
4317//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004318// ScalarEvolution Class Implementation
4319//===----------------------------------------------------------------------===//
4320
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004321ScalarEvolution::ScalarEvolution()
Owen Andersonb70139d2009-06-22 21:57:23 +00004322 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004323}
4324
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004325bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004326 this->F = &F;
4327 LI = &getAnalysis<LoopInfo>();
4328 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004329 return false;
4330}
4331
4332void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004333 Scalars.clear();
4334 BackedgeTakenCounts.clear();
4335 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004336 ValuesAtScopes.clear();
Dan Gohman9bc642f2009-06-24 04:48:43 +00004337
Owen Andersonc48fbfe2009-06-22 18:25:46 +00004338 for (std::map<ConstantInt*, SCEVConstant*>::iterator
4339 I = SCEVConstants.begin(), E = SCEVConstants.end(); I != E; ++I)
4340 delete I->second;
4341 for (std::map<std::pair<const SCEV*, const Type*>,
4342 SCEVTruncateExpr*>::iterator I = SCEVTruncates.begin(),
4343 E = SCEVTruncates.end(); I != E; ++I)
4344 delete I->second;
4345 for (std::map<std::pair<const SCEV*, const Type*>,
4346 SCEVZeroExtendExpr*>::iterator I = SCEVZeroExtends.begin(),
4347 E = SCEVZeroExtends.end(); I != E; ++I)
4348 delete I->second;
4349 for (std::map<std::pair<unsigned, std::vector<const SCEV*> >,
4350 SCEVCommutativeExpr*>::iterator I = SCEVCommExprs.begin(),
4351 E = SCEVCommExprs.end(); I != E; ++I)
4352 delete I->second;
4353 for (std::map<std::pair<const SCEV*, const SCEV*>, SCEVUDivExpr*>::iterator
4354 I = SCEVUDivs.begin(), E = SCEVUDivs.end(); I != E; ++I)
4355 delete I->second;
4356 for (std::map<std::pair<const SCEV*, const Type*>,
4357 SCEVSignExtendExpr*>::iterator I = SCEVSignExtends.begin(),
4358 E = SCEVSignExtends.end(); I != E; ++I)
4359 delete I->second;
4360 for (std::map<std::pair<const Loop *, std::vector<const SCEV*> >,
4361 SCEVAddRecExpr*>::iterator I = SCEVAddRecExprs.begin(),
4362 E = SCEVAddRecExprs.end(); I != E; ++I)
4363 delete I->second;
4364 for (std::map<Value*, SCEVUnknown*>::iterator I = SCEVUnknowns.begin(),
4365 E = SCEVUnknowns.end(); I != E; ++I)
4366 delete I->second;
Dan Gohman9bc642f2009-06-24 04:48:43 +00004367
Owen Andersonc48fbfe2009-06-22 18:25:46 +00004368 SCEVConstants.clear();
4369 SCEVTruncates.clear();
4370 SCEVZeroExtends.clear();
4371 SCEVCommExprs.clear();
4372 SCEVUDivs.clear();
4373 SCEVSignExtends.clear();
4374 SCEVAddRecExprs.clear();
4375 SCEVUnknowns.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004376}
4377
4378void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4379 AU.setPreservesAll();
4380 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004381}
4382
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004383bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004384 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004385}
4386
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004387static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004388 const Loop *L) {
4389 // Print all inner loops first
4390 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4391 PrintLoopInfo(OS, SE, *I);
4392
Nick Lewyckye5da1912008-01-02 02:49:20 +00004393 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004394
Devang Patel02451fa2007-08-21 00:31:24 +00004395 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004396 L->getExitBlocks(ExitBlocks);
4397 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004398 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004399
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004400 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4401 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004402 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004403 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004404 }
4405
Nick Lewyckye5da1912008-01-02 02:49:20 +00004406 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004407 OS << "Loop " << L->getHeader()->getName() << ": ";
4408
4409 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4410 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4411 } else {
4412 OS << "Unpredictable max backedge-taken count. ";
4413 }
4414
4415 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416}
4417
Dan Gohman13058cc2009-04-21 00:47:46 +00004418void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004419 // ScalarEvolution's implementaiton of the print method is to print
4420 // out SCEV values of all instructions that are interesting. Doing
4421 // this potentially causes it to create new SCEV objects though,
4422 // which technically conflicts with the const qualifier. This isn't
4423 // observable from outside the class though (the hasSCEV function
4424 // notwithstanding), so casting away the const isn't dangerous.
4425 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004427 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004428 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004429 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004430 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004431 OS << " --> ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004432 const SCEV* SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004433 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004434
Dan Gohman8db598a2009-06-19 17:49:54 +00004435 const Loop *L = LI->getLoopFor((*I).getParent());
4436
Owen Andersonecd0cd72009-06-22 21:39:50 +00004437 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004438 if (AtUse != SV) {
4439 OS << " --> ";
4440 AtUse->print(OS);
4441 }
4442
4443 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004444 OS << "\t\t" "Exits: ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004445 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004446 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 OS << "<<Unknown>>";
4448 } else {
4449 OS << *ExitValue;
4450 }
4451 }
4452
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004453 OS << "\n";
4454 }
4455
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004456 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4457 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4458 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004459}
Dan Gohman13058cc2009-04-21 00:47:46 +00004460
4461void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4462 raw_os_ostream OS(o);
4463 print(OS, M);
4464}