blob: 7f6321792572c867644738e9e01c394544040e58 [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
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// 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"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079#include "llvm/Support/InstIterator.h"
80#include "llvm/Support/ManagedStatic.h"
81#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085#include <ostream>
86#include <algorithm>
87#include <cmath>
88using namespace llvm;
89
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman089efff2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
103 cl::init(100));
104
Dan Gohman089efff2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107char ScalarEvolution::ID = 0;
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
116SCEV::~SCEV() {}
117void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125}
126
Dan Gohman7b560c42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000135SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
139 return false;
140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return 0;
145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000154 const SCEVHandle &Conc,
155 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 return this;
157}
158
Dan Gohman13058cc2009-04-21 00:47:46 +0000159void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
165}
166
167
168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value. Don't use a SCEVHandle here, or else the object will
170// never be deleted!
171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
172
173
174SCEVConstant::~SCEVConstant() {
175 SCEVConstants->erase(V);
176}
177
Dan Gohman89f85052007-10-22 18:31:58 +0000178SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 SCEVConstant *&R = (*SCEVConstants)[V];
180 if (R == 0) R = new SCEVConstant(V);
181 return R;
182}
183
Dan Gohman89f85052007-10-22 18:31:58 +0000184SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186}
187
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
189
Dan Gohman13058cc2009-04-21 00:47:46 +0000190void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 WriteAsOperand(OS, V, false);
192}
193
Dan Gohman2a381532009-04-21 01:25:57 +0000194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195 const SCEVHandle &op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
197
198SCEVCastExpr::~SCEVCastExpr() {}
199
200bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201 return Op->dominates(BB, DT);
202}
203
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205// particular input. Don't use a SCEVHandle here, or else the object will
206// never be deleted!
207static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
208 SCEVTruncateExpr*> > SCEVTruncates;
209
210SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000211 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215}
216
217SCEVTruncateExpr::~SCEVTruncateExpr() {
218 SCEVTruncates->erase(std::make_pair(Op, Ty));
219}
220
Dan Gohman13058cc2009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 OS << "(truncate " << *Op << " to " << *Ty << ")";
223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000232 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
240}
241
Dan Gohman13058cc2009-04-21 00:47:46 +0000242void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
244}
245
246// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247// particular input. Don't use a SCEVHandle here, or else the object will never
248// be deleted!
249static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
250 SCEVSignExtendExpr*> > SCEVSignExtends;
251
252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000253 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257}
258
259SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
261}
262
Dan Gohman13058cc2009-04-21 00:47:46 +0000263void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 OS << "(signextend " << *Op << " to " << *Ty << ")";
265}
266
267// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268// particular input. Don't use a SCEVHandle here, or else the object will never
269// be deleted!
270static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
271 SCEVCommutativeExpr*> > SCEVCommExprs;
272
273SCEVCommutativeExpr::~SCEVCommutativeExpr() {
274 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
275 std::vector<SCEV*>(Operands.begin(),
276 Operands.end())));
277}
278
Dan Gohman13058cc2009-04-21 00:47:46 +0000279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
286}
287
288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 if (H != getOperand(i)) {
296 std::vector<SCEVHandle> NewOps;
297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304
305 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000306 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000308 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 else
314 assert(0 && "Unknown commutative expr!");
315 }
316 }
317 return this;
318}
319
Evan Cheng98c073b2009-02-17 00:13:06 +0000320bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
324 }
325 return true;
326}
327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000333 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337}
338
Evan Cheng98c073b2009-02-17 00:13:06 +0000339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
Dan Gohman13058cc2009-04-21 00:47:46 +0000343void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000344 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345}
346
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348 return LHS->getType();
349}
350
351// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352// particular input. Don't use a SCEVHandle here, or else the object will never
353// be deleted!
354static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355 SCEVAddRecExpr*> > SCEVAddRecExprs;
356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
358 SCEVAddRecExprs->erase(std::make_pair(L,
359 std::vector<SCEV*>(Operands.begin(),
360 Operands.end())));
361}
362
Evan Cheng98c073b2009-02-17 00:13:06 +0000363bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365 if (!getOperand(i)->dominates(BB, DT))
366 return false;
367 }
368 return true;
369}
370
371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372SCEVHandle SCEVAddRecExpr::
373replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000374 const SCEVHandle &Conc,
375 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000377 SCEVHandle H =
378 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 if (H != getOperand(i)) {
380 std::vector<SCEVHandle> NewOps;
381 NewOps.reserve(getNumOperands());
382 for (unsigned j = 0; j != i; ++j)
383 NewOps.push_back(getOperand(j));
384 NewOps.push_back(H);
385 for (++i; i != e; ++i)
386 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000387 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388
Dan Gohman89f85052007-10-22 18:31:58 +0000389 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 }
391 }
392 return this;
393}
394
395
396bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
397 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
398 // contain L and if the start is invariant.
399 return !QueryLoop->contains(L->getHeader()) &&
400 getOperand(0)->isLoopInvariant(QueryLoop);
401}
402
403
Dan Gohman13058cc2009-04-21 00:47:46 +0000404void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 OS << "{" << *Operands[0];
406 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
407 OS << ",+," << *Operands[i];
408 OS << "}<" << L->getHeader()->getName() + ">";
409}
410
411// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
412// value. Don't use a SCEVHandle here, or else the object will never be
413// deleted!
414static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
415
416SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
417
418bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
419 // All non-instruction values are loop invariant. All instructions are loop
420 // invariant if they are not contained in the specified loop.
421 if (Instruction *I = dyn_cast<Instruction>(V))
422 return !L->contains(I->getParent());
423 return true;
424}
425
Evan Cheng98c073b2009-02-17 00:13:06 +0000426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
430}
431
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432const Type *SCEVUnknown::getType() const {
433 return V->getType();
434}
435
Dan Gohman13058cc2009-04-21 00:47:46 +0000436void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000437 if (isa<PointerType>(V->getType()))
438 OS << "(ptrtoint " << *V->getType() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 WriteAsOperand(OS, V, false);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000440 if (isa<PointerType>(V->getType()))
441 OS << " to iPTR)";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442}
443
444//===----------------------------------------------------------------------===//
445// SCEV Utilities
446//===----------------------------------------------------------------------===//
447
448namespace {
449 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450 /// than the complexity of the RHS. This comparator is used to canonicalize
451 /// expressions.
452 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000453 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 return LHS->getSCEVType() < RHS->getSCEVType();
455 }
456 };
457}
458
459/// GroupByComplexity - Given a list of SCEV objects, order them by their
460/// complexity, and group objects of the same complexity together by value.
461/// When this routine is finished, we know that any duplicates in the vector are
462/// consecutive and that complexity is monotonically increasing.
463///
464/// Note that we go take special precautions to ensure that we get determinstic
465/// results from this routine. In other words, we don't want the results of
466/// this to depend on where the addresses of various SCEV objects happened to
467/// land in memory.
468///
469static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
470 if (Ops.size() < 2) return; // Noop
471 if (Ops.size() == 2) {
472 // This is the common case, which also happens to be trivially simple.
473 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000474 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 std::swap(Ops[0], Ops[1]);
476 return;
477 }
478
479 // Do the rough sort by complexity.
480 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
481
482 // Now that we are sorted by complexity, group elements of the same
483 // complexity. Note that this is, at worst, N^2, but the vector is likely to
484 // be extremely short in practice. Note that we take this approach because we
485 // do not want to depend on the addresses of the objects we are grouping.
486 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
487 SCEV *S = Ops[i];
488 unsigned Complexity = S->getSCEVType();
489
490 // If there are any objects of the same complexity and same value as this
491 // one, group them.
492 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
493 if (Ops[j] == S) { // Found a duplicate.
494 // Move it to immediately after i'th element.
495 std::swap(Ops[i+1], Ops[j]);
496 ++i; // no need to rescan it.
497 if (i == e-2) return; // Done!
498 }
499 }
500 }
501}
502
503
504
505//===----------------------------------------------------------------------===//
506// Simple SCEV method implementations
507//===----------------------------------------------------------------------===//
508
Eli Friedman7489ec92008-08-04 23:49:06 +0000509/// BinomialCoefficient - Compute BC(It, K). The result has width W.
510// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000511static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000512 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000513 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000514 // Handle the simplest case efficiently.
515 if (K == 1)
516 return SE.getTruncateOrZeroExtend(It, ResultTy);
517
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000518 // We are using the following formula for BC(It, K):
519 //
520 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
521 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000522 // Suppose, W is the bitwidth of the return value. We must be prepared for
523 // overflow. Hence, we must assure that the result of our computation is
524 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
525 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000526 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000527 // However, this code doesn't use exactly that formula; the formula it uses
528 // is something like the following, where T is the number of factors of 2 in
529 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
530 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000531 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000532 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000533 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000534 // This formula is trivially equivalent to the previous formula. However,
535 // this formula can be implemented much more efficiently. The trick is that
536 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
537 // arithmetic. To do exact division in modular arithmetic, all we have
538 // to do is multiply by the inverse. Therefore, this step can be done at
539 // width W.
540 //
541 // The next issue is how to safely do the division by 2^T. The way this
542 // is done is by doing the multiplication step at a width of at least W + T
543 // bits. This way, the bottom W+T bits of the product are accurate. Then,
544 // when we perform the division by 2^T (which is equivalent to a right shift
545 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
546 // truncated out after the division by 2^T.
547 //
548 // In comparison to just directly using the first formula, this technique
549 // is much more efficient; using the first formula requires W * K bits,
550 // but this formula less than W + K bits. Also, the first formula requires
551 // a division step, whereas this formula only requires multiplies and shifts.
552 //
553 // It doesn't matter whether the subtraction step is done in the calculation
554 // width or the input iteration count's width; if the subtraction overflows,
555 // the result must be zero anyway. We prefer here to do it in the width of
556 // the induction variable because it helps a lot for certain cases; CodeGen
557 // isn't smart enough to ignore the overflow, which leads to much less
558 // efficient code if the width of the subtraction is wider than the native
559 // register width.
560 //
561 // (It's possible to not widen at all by pulling out factors of 2 before
562 // the multiplication; for example, K=2 can be calculated as
563 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
564 // extra arithmetic, so it's not an obvious win, and it gets
565 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000566
Eli Friedman7489ec92008-08-04 23:49:06 +0000567 // Protection from insane SCEVs; this bound is conservative,
568 // but it probably doesn't matter.
569 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000570 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000571
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000572 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000573
Eli Friedman7489ec92008-08-04 23:49:06 +0000574 // Calculate K! / 2^T and T; we divide out the factors of two before
575 // multiplying for calculating K! / 2^T to avoid overflow.
576 // Other overflow doesn't matter because we only care about the bottom
577 // W bits of the result.
578 APInt OddFactorial(W, 1);
579 unsigned T = 1;
580 for (unsigned i = 3; i <= K; ++i) {
581 APInt Mult(W, i);
582 unsigned TwoFactors = Mult.countTrailingZeros();
583 T += TwoFactors;
584 Mult = Mult.lshr(TwoFactors);
585 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000587
Eli Friedman7489ec92008-08-04 23:49:06 +0000588 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000589 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000590
591 // Calcuate 2^T, at width T+W.
592 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
593
594 // Calculate the multiplicative inverse of K! / 2^T;
595 // this multiplication factor will perform the exact division by
596 // K! / 2^T.
597 APInt Mod = APInt::getSignedMinValue(W+1);
598 APInt MultiplyFactor = OddFactorial.zext(W+1);
599 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
600 MultiplyFactor = MultiplyFactor.trunc(W);
601
602 // Calculate the product, at width T+W
603 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
604 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
605 for (unsigned i = 1; i != K; ++i) {
606 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
607 Dividend = SE.getMulExpr(Dividend,
608 SE.getTruncateOrZeroExtend(S, CalculationTy));
609 }
610
611 // Divide by 2^T
612 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
613
614 // Truncate the result, and divide by K! / 2^T.
615
616 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
617 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618}
619
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620/// evaluateAtIteration - Return the value of this chain of recurrences at
621/// the specified iteration number. We can evaluate this recurrence by
622/// multiplying each element in the chain by the binomial coefficient
623/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
624///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000625/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000627/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628///
Dan Gohman89f85052007-10-22 18:31:58 +0000629SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
630 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000633 // The computation is correct in the face of overflow provided that the
634 // multiplication is performed _after_ the evaluation of the binomial
635 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000636 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000637 if (isa<SCEVCouldNotCompute>(Coeff))
638 return Coeff;
639
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 }
642 return Result;
643}
644
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645//===----------------------------------------------------------------------===//
646// SCEV Expression folder implementations
647//===----------------------------------------------------------------------===//
648
Dan Gohman89f85052007-10-22 18:31:58 +0000649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000650 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000651 "This is not a truncating conversion!");
652
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000654 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 ConstantExpr::getTrunc(SC->getValue(), Ty));
656
Dan Gohman1a5c4992009-04-22 16:20:48 +0000657 // trunc(trunc(x)) --> trunc(x)
658 if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
659 return getTruncateExpr(ST->getOperand(), Ty);
660
Nick Lewycky37d04642009-04-23 05:15:08 +0000661 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
662 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
663 return getTruncateOrSignExtend(SS->getOperand(), Ty);
664
665 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
666 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
667 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
668
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 // If the input value is a chrec scev made out of constants, truncate
670 // all of the constants.
671 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
672 std::vector<SCEVHandle> Operands;
673 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
674 // FIXME: This should allow truncation of other expression types!
675 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000676 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 else
678 break;
679 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000680 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 }
682
683 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
684 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
685 return Result;
686}
687
Dan Gohman36d40922009-04-16 19:25:55 +0000688SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
689 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000690 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000691 "This is not an extending conversion!");
692
Dan Gohman01c2ee72009-04-16 03:18:22 +0000693 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000694 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000695 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
696 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
697 return getUnknown(C);
698 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699
Dan Gohman1a5c4992009-04-22 16:20:48 +0000700 // zext(zext(x)) --> zext(x)
701 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
702 return getZeroExtendExpr(SZ->getOperand(), Ty);
703
Dan Gohmana9dba962009-04-27 20:16:15 +0000704 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000706 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana9dba962009-04-27 20:16:15 +0000708 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
709 if (AR->isAffine()) {
710 // Check whether the backedge-taken count is SCEVCouldNotCompute.
711 // Note that this serves two purposes: It filters out loops that are
712 // simply not analyzable, and it covers the case where this code is
713 // being called from within backedge-taken count analysis, such that
714 // attempting to ask for the backedge-taken count would likely result
715 // in infinite recursion. In the later case, the analysis code will
716 // cope with a conservative value, and it will take care to purge
717 // that value once it has finished.
718 SCEVHandle BECount = getBackedgeTakenCount(AR->getLoop());
719 if (!isa<SCEVCouldNotCompute>(BECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000720 // Manually compute the final value for AR, checking for
721 // overflow at each step.
Dan Gohmana9dba962009-04-27 20:16:15 +0000722 SCEVHandle Start = AR->getStart();
723 SCEVHandle Step = AR->getStepRecurrence(*this);
724
725 // Check whether the backedge-taken count can be losslessly casted to
726 // the addrec's type. The count is always unsigned.
727 SCEVHandle CastedBECount =
728 getTruncateOrZeroExtend(BECount, Start->getType());
729 if (BECount ==
730 getTruncateOrZeroExtend(CastedBECount, BECount->getType())) {
731 const Type *WideTy =
732 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
733 SCEVHandle ZMul =
734 getMulExpr(CastedBECount,
735 getTruncateOrZeroExtend(Step, Start->getType()));
736 // Check whether Start+Step*BECount has no unsigned overflow.
737 if (getZeroExtendExpr(ZMul, WideTy) ==
738 getMulExpr(getZeroExtendExpr(CastedBECount, WideTy),
739 getZeroExtendExpr(Step, WideTy))) {
740 SCEVHandle Add = getAddExpr(Start, ZMul);
741 if (getZeroExtendExpr(Add, WideTy) ==
742 getAddExpr(getZeroExtendExpr(Start, WideTy),
743 getZeroExtendExpr(ZMul, WideTy)))
744 // Return the expression with the addrec on the outside.
745 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
746 getZeroExtendExpr(Step, Ty),
747 AR->getLoop());
748 }
749
750 // Similar to above, only this time treat the step value as signed.
751 // This covers loops that count down.
752 SCEVHandle SMul =
753 getMulExpr(CastedBECount,
754 getTruncateOrSignExtend(Step, Start->getType()));
755 // Check whether Start+Step*BECount has no unsigned overflow.
756 if (getSignExtendExpr(SMul, WideTy) ==
757 getMulExpr(getZeroExtendExpr(CastedBECount, WideTy),
758 getSignExtendExpr(Step, WideTy))) {
759 SCEVHandle Add = getAddExpr(Start, SMul);
760 if (getZeroExtendExpr(Add, WideTy) ==
761 getAddExpr(getZeroExtendExpr(Start, WideTy),
762 getSignExtendExpr(SMul, WideTy)))
763 // Return the expression with the addrec on the outside.
764 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
765 getSignExtendExpr(Step, Ty),
766 AR->getLoop());
767 }
768 }
769 }
770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771
772 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
773 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
774 return Result;
775}
776
Dan Gohmana9dba962009-04-27 20:16:15 +0000777SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
778 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000779 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000780 "This is not an extending conversion!");
781
Dan Gohman01c2ee72009-04-16 03:18:22 +0000782 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000783 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000784 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
785 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
786 return getUnknown(C);
787 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788
Dan Gohman1a5c4992009-04-22 16:20:48 +0000789 // sext(sext(x)) --> sext(x)
790 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
791 return getSignExtendExpr(SS->getOperand(), Ty);
792
Dan Gohmana9dba962009-04-27 20:16:15 +0000793 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000795 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana9dba962009-04-27 20:16:15 +0000797 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
798 if (AR->isAffine()) {
799 // Check whether the backedge-taken count is SCEVCouldNotCompute.
800 // Note that this serves two purposes: It filters out loops that are
801 // simply not analyzable, and it covers the case where this code is
802 // being called from within backedge-taken count analysis, such that
803 // attempting to ask for the backedge-taken count would likely result
804 // in infinite recursion. In the later case, the analysis code will
805 // cope with a conservative value, and it will take care to purge
806 // that value once it has finished.
807 SCEVHandle BECount = getBackedgeTakenCount(AR->getLoop());
808 if (!isa<SCEVCouldNotCompute>(BECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000809 // Manually compute the final value for AR, checking for
810 // overflow at each step.
Dan Gohmana9dba962009-04-27 20:16:15 +0000811 SCEVHandle Start = AR->getStart();
812 SCEVHandle Step = AR->getStepRecurrence(*this);
813
814 // Check whether the backedge-taken count can be losslessly casted to
815 // the addrec's type. The count is always unsigned.
816 SCEVHandle CastedBECount =
817 getTruncateOrZeroExtend(BECount, Start->getType());
818 if (BECount ==
819 getTruncateOrZeroExtend(CastedBECount, BECount->getType())) {
820 const Type *WideTy =
821 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
822 SCEVHandle SMul =
823 getMulExpr(CastedBECount,
824 getTruncateOrSignExtend(Step, Start->getType()));
825 // Check whether Start+Step*BECount has no signed overflow.
826 if (getSignExtendExpr(SMul, WideTy) ==
827 getMulExpr(getSignExtendExpr(CastedBECount, WideTy),
828 getSignExtendExpr(Step, WideTy))) {
829 SCEVHandle Add = getAddExpr(Start, SMul);
830 if (getSignExtendExpr(Add, WideTy) ==
831 getAddExpr(getSignExtendExpr(Start, WideTy),
832 getSignExtendExpr(SMul, WideTy)))
833 // Return the expression with the addrec on the outside.
834 return getAddRecExpr(getSignExtendExpr(Start, Ty),
835 getSignExtendExpr(Step, Ty),
836 AR->getLoop());
837 }
838 }
839 }
840 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841
842 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
843 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
844 return Result;
845}
846
847// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000848SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 assert(!Ops.empty() && "Cannot get empty add!");
850 if (Ops.size() == 1) return Ops[0];
851
852 // Sort by complexity, this groups all similar expression types together.
853 GroupByComplexity(Ops);
854
855 // If there are any constants, fold them together.
856 unsigned Idx = 0;
857 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
858 ++Idx;
859 assert(Idx < Ops.size());
860 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
861 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000862 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
863 RHSC->getValue()->getValue());
864 Ops[0] = getConstant(Fold);
865 Ops.erase(Ops.begin()+1); // Erase the folded element
866 if (Ops.size() == 1) return Ops[0];
867 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 }
869
870 // If we are left with a constant zero being added, strip it off.
871 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
872 Ops.erase(Ops.begin());
873 --Idx;
874 }
875 }
876
877 if (Ops.size() == 1) return Ops[0];
878
879 // Okay, check to see if the same value occurs in the operand list twice. If
880 // so, merge them together into an multiply expression. Since we sorted the
881 // list, these values are required to be adjacent.
882 const Type *Ty = Ops[0]->getType();
883 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
884 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
885 // Found a match, merge the two values into a multiply, and add any
886 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000887 SCEVHandle Two = getIntegerSCEV(2, Ty);
888 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 if (Ops.size() == 2)
890 return Mul;
891 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
892 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000893 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 }
895
896 // Now we know the first non-constant operand. Skip past any cast SCEVs.
897 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
898 ++Idx;
899
900 // If there are add operands they would be next.
901 if (Idx < Ops.size()) {
902 bool DeletedAdd = false;
903 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
904 // If we have an add, expand the add operands onto the end of the operands
905 // list.
906 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
907 Ops.erase(Ops.begin()+Idx);
908 DeletedAdd = true;
909 }
910
911 // If we deleted at least one add, we added operands to the end of the list,
912 // and they are not necessarily sorted. Recurse to resort and resimplify
913 // any operands we just aquired.
914 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000915 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 }
917
918 // Skip over the add expression until we get to a multiply.
919 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
920 ++Idx;
921
922 // If we are adding something to a multiply expression, make sure the
923 // something is not already an operand of the multiply. If so, merge it into
924 // the multiply.
925 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
926 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
927 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
928 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
929 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
930 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
931 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
932 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
933 if (Mul->getNumOperands() != 2) {
934 // If the multiply has more than two operands, we must get the
935 // Y*Z term.
936 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
937 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000938 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 }
Dan Gohman89f85052007-10-22 18:31:58 +0000940 SCEVHandle One = getIntegerSCEV(1, Ty);
941 SCEVHandle AddOne = getAddExpr(InnerMul, One);
942 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943 if (Ops.size() == 2) return OuterMul;
944 if (AddOp < Idx) {
945 Ops.erase(Ops.begin()+AddOp);
946 Ops.erase(Ops.begin()+Idx-1);
947 } else {
948 Ops.erase(Ops.begin()+Idx);
949 Ops.erase(Ops.begin()+AddOp-1);
950 }
951 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000952 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 }
954
955 // Check this multiply against other multiplies being added together.
956 for (unsigned OtherMulIdx = Idx+1;
957 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
958 ++OtherMulIdx) {
959 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
960 // If MulOp occurs in OtherMul, we can fold the two multiplies
961 // together.
962 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
963 OMulOp != e; ++OMulOp)
964 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
965 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
966 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
967 if (Mul->getNumOperands() != 2) {
968 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
969 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000970 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971 }
972 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
973 if (OtherMul->getNumOperands() != 2) {
974 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
975 OtherMul->op_end());
976 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000977 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 }
Dan Gohman89f85052007-10-22 18:31:58 +0000979 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
980 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 if (Ops.size() == 2) return OuterMul;
982 Ops.erase(Ops.begin()+Idx);
983 Ops.erase(Ops.begin()+OtherMulIdx-1);
984 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000985 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 }
987 }
988 }
989 }
990
991 // If there are any add recurrences in the operands list, see if any other
992 // added values are loop invariant. If so, we can fold them into the
993 // recurrence.
994 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
995 ++Idx;
996
997 // Scan over all recurrences, trying to fold loop invariants into them.
998 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
999 // Scan all of the other operands to this add and add them to the vector if
1000 // they are loop invariant w.r.t. the recurrence.
1001 std::vector<SCEVHandle> LIOps;
1002 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1003 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1004 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1005 LIOps.push_back(Ops[i]);
1006 Ops.erase(Ops.begin()+i);
1007 --i; --e;
1008 }
1009
1010 // If we found some loop invariants, fold them into the recurrence.
1011 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001012 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 LIOps.push_back(AddRec->getStart());
1014
1015 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001016 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001017
Dan Gohman89f85052007-10-22 18:31:58 +00001018 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 // If all of the other operands were loop invariant, we are done.
1020 if (Ops.size() == 1) return NewRec;
1021
1022 // Otherwise, add the folded AddRec by the non-liv parts.
1023 for (unsigned i = 0;; ++i)
1024 if (Ops[i] == AddRec) {
1025 Ops[i] = NewRec;
1026 break;
1027 }
Dan Gohman89f85052007-10-22 18:31:58 +00001028 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 }
1030
1031 // Okay, if there weren't any loop invariants to be folded, check to see if
1032 // there are multiple AddRec's with the same loop induction variable being
1033 // added together. If so, we can fold them.
1034 for (unsigned OtherIdx = Idx+1;
1035 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1036 if (OtherIdx != Idx) {
1037 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1038 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1039 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1040 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1041 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1042 if (i >= NewOps.size()) {
1043 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1044 OtherAddRec->op_end());
1045 break;
1046 }
Dan Gohman89f85052007-10-22 18:31:58 +00001047 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 }
Dan Gohman89f85052007-10-22 18:31:58 +00001049 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050
1051 if (Ops.size() == 2) return NewAddRec;
1052
1053 Ops.erase(Ops.begin()+Idx);
1054 Ops.erase(Ops.begin()+OtherIdx-1);
1055 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001056 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 }
1058 }
1059
1060 // Otherwise couldn't fold anything into this recurrence. Move onto the
1061 // next one.
1062 }
1063
1064 // Okay, it looks like we really DO need an add expr. Check to see if we
1065 // already have one, otherwise create a new one.
1066 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1067 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1068 SCEVOps)];
1069 if (Result == 0) Result = new SCEVAddExpr(Ops);
1070 return Result;
1071}
1072
1073
Dan Gohman89f85052007-10-22 18:31:58 +00001074SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001075 assert(!Ops.empty() && "Cannot get empty mul!");
1076
1077 // Sort by complexity, this groups all similar expression types together.
1078 GroupByComplexity(Ops);
1079
1080 // If there are any constants, fold them together.
1081 unsigned Idx = 0;
1082 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1083
1084 // C1*(C2+V) -> C1*C2 + C1*V
1085 if (Ops.size() == 2)
1086 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1087 if (Add->getNumOperands() == 2 &&
1088 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001089 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1090 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091
1092
1093 ++Idx;
1094 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1095 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001096 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1097 RHSC->getValue()->getValue());
1098 Ops[0] = getConstant(Fold);
1099 Ops.erase(Ops.begin()+1); // Erase the folded element
1100 if (Ops.size() == 1) return Ops[0];
1101 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 }
1103
1104 // If we are left with a constant one being multiplied, strip it off.
1105 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1106 Ops.erase(Ops.begin());
1107 --Idx;
1108 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1109 // If we have a multiply of zero, it will always be zero.
1110 return Ops[0];
1111 }
1112 }
1113
1114 // Skip over the add expression until we get to a multiply.
1115 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1116 ++Idx;
1117
1118 if (Ops.size() == 1)
1119 return Ops[0];
1120
1121 // If there are mul operands inline them all into this expression.
1122 if (Idx < Ops.size()) {
1123 bool DeletedMul = false;
1124 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1125 // If we have an mul, expand the mul operands onto the end of the operands
1126 // list.
1127 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1128 Ops.erase(Ops.begin()+Idx);
1129 DeletedMul = true;
1130 }
1131
1132 // If we deleted at least one mul, we added operands to the end of the list,
1133 // and they are not necessarily sorted. Recurse to resort and resimplify
1134 // any operands we just aquired.
1135 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001136 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 }
1138
1139 // If there are any add recurrences in the operands list, see if any other
1140 // added values are loop invariant. If so, we can fold them into the
1141 // recurrence.
1142 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1143 ++Idx;
1144
1145 // Scan over all recurrences, trying to fold loop invariants into them.
1146 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1147 // Scan all of the other operands to this mul and add them to the vector if
1148 // they are loop invariant w.r.t. the recurrence.
1149 std::vector<SCEVHandle> LIOps;
1150 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1151 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1152 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1153 LIOps.push_back(Ops[i]);
1154 Ops.erase(Ops.begin()+i);
1155 --i; --e;
1156 }
1157
1158 // If we found some loop invariants, fold them into the recurrence.
1159 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001160 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 std::vector<SCEVHandle> NewOps;
1162 NewOps.reserve(AddRec->getNumOperands());
1163 if (LIOps.size() == 1) {
1164 SCEV *Scale = LIOps[0];
1165 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001166 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 } else {
1168 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1169 std::vector<SCEVHandle> MulOps(LIOps);
1170 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001171 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 }
1173 }
1174
Dan Gohman89f85052007-10-22 18:31:58 +00001175 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001176
1177 // If all of the other operands were loop invariant, we are done.
1178 if (Ops.size() == 1) return NewRec;
1179
1180 // Otherwise, multiply the folded AddRec by the non-liv parts.
1181 for (unsigned i = 0;; ++i)
1182 if (Ops[i] == AddRec) {
1183 Ops[i] = NewRec;
1184 break;
1185 }
Dan Gohman89f85052007-10-22 18:31:58 +00001186 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 }
1188
1189 // Okay, if there weren't any loop invariants to be folded, check to see if
1190 // there are multiple AddRec's with the same loop induction variable being
1191 // multiplied together. If so, we can fold them.
1192 for (unsigned OtherIdx = Idx+1;
1193 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1194 if (OtherIdx != Idx) {
1195 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1196 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1197 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1198 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001199 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001201 SCEVHandle B = F->getStepRecurrence(*this);
1202 SCEVHandle D = G->getStepRecurrence(*this);
1203 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1204 getMulExpr(G, B),
1205 getMulExpr(B, D));
1206 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1207 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 if (Ops.size() == 2) return NewAddRec;
1209
1210 Ops.erase(Ops.begin()+Idx);
1211 Ops.erase(Ops.begin()+OtherIdx-1);
1212 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001213 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 }
1215 }
1216
1217 // Otherwise couldn't fold anything into this recurrence. Move onto the
1218 // next one.
1219 }
1220
1221 // Okay, it looks like we really DO need an mul expr. Check to see if we
1222 // already have one, otherwise create a new one.
1223 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1224 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1225 SCEVOps)];
1226 if (Result == 0)
1227 Result = new SCEVMulExpr(Ops);
1228 return Result;
1229}
1230
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001231SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1233 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001234 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235
1236 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1237 Constant *LHSCV = LHSC->getValue();
1238 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001239 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 }
1241 }
1242
Nick Lewycky35b56022009-01-13 09:18:58 +00001243 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1244
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001245 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1246 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 return Result;
1248}
1249
1250
1251/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1252/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001253SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 const SCEVHandle &Step, const Loop *L) {
1255 std::vector<SCEVHandle> Operands;
1256 Operands.push_back(Start);
1257 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1258 if (StepChrec->getLoop() == L) {
1259 Operands.insert(Operands.end(), StepChrec->op_begin(),
1260 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001261 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 }
1263
1264 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001265 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266}
1267
1268/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1269/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001270SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001271 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 if (Operands.size() == 1) return Operands[0];
1273
Dan Gohman7b560c42008-06-18 16:23:07 +00001274 if (Operands.back()->isZero()) {
1275 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001276 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001277 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278
Dan Gohman42936882008-08-08 18:33:12 +00001279 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1280 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1281 const Loop* NestedLoop = NestedAR->getLoop();
1282 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1283 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1284 NestedAR->op_end());
1285 SCEVHandle NestedARHandle(NestedAR);
1286 Operands[0] = NestedAR->getStart();
1287 NestedOperands[0] = getAddRecExpr(Operands, L);
1288 return getAddRecExpr(NestedOperands, NestedLoop);
1289 }
1290 }
1291
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 SCEVAddRecExpr *&Result =
1293 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1294 Operands.end()))];
1295 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1296 return Result;
1297}
1298
Nick Lewycky711640a2007-11-25 22:41:31 +00001299SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1300 const SCEVHandle &RHS) {
1301 std::vector<SCEVHandle> Ops;
1302 Ops.push_back(LHS);
1303 Ops.push_back(RHS);
1304 return getSMaxExpr(Ops);
1305}
1306
1307SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1308 assert(!Ops.empty() && "Cannot get empty smax!");
1309 if (Ops.size() == 1) return Ops[0];
1310
1311 // Sort by complexity, this groups all similar expression types together.
1312 GroupByComplexity(Ops);
1313
1314 // If there are any constants, fold them together.
1315 unsigned Idx = 0;
1316 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1317 ++Idx;
1318 assert(Idx < Ops.size());
1319 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1320 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001321 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001322 APIntOps::smax(LHSC->getValue()->getValue(),
1323 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001324 Ops[0] = getConstant(Fold);
1325 Ops.erase(Ops.begin()+1); // Erase the folded element
1326 if (Ops.size() == 1) return Ops[0];
1327 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001328 }
1329
1330 // If we are left with a constant -inf, strip it off.
1331 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1332 Ops.erase(Ops.begin());
1333 --Idx;
1334 }
1335 }
1336
1337 if (Ops.size() == 1) return Ops[0];
1338
1339 // Find the first SMax
1340 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1341 ++Idx;
1342
1343 // Check to see if one of the operands is an SMax. If so, expand its operands
1344 // onto our operand list, and recurse to simplify.
1345 if (Idx < Ops.size()) {
1346 bool DeletedSMax = false;
1347 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1348 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1349 Ops.erase(Ops.begin()+Idx);
1350 DeletedSMax = true;
1351 }
1352
1353 if (DeletedSMax)
1354 return getSMaxExpr(Ops);
1355 }
1356
1357 // Okay, check to see if the same value occurs in the operand list twice. If
1358 // so, delete one. Since we sorted the list, these values are required to
1359 // be adjacent.
1360 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1361 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1362 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1363 --i; --e;
1364 }
1365
1366 if (Ops.size() == 1) return Ops[0];
1367
1368 assert(!Ops.empty() && "Reduced smax down to nothing!");
1369
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001370 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001371 // already have one, otherwise create a new one.
1372 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1373 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1374 SCEVOps)];
1375 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1376 return Result;
1377}
1378
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001379SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1380 const SCEVHandle &RHS) {
1381 std::vector<SCEVHandle> Ops;
1382 Ops.push_back(LHS);
1383 Ops.push_back(RHS);
1384 return getUMaxExpr(Ops);
1385}
1386
1387SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1388 assert(!Ops.empty() && "Cannot get empty umax!");
1389 if (Ops.size() == 1) return Ops[0];
1390
1391 // Sort by complexity, this groups all similar expression types together.
1392 GroupByComplexity(Ops);
1393
1394 // If there are any constants, fold them together.
1395 unsigned Idx = 0;
1396 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1397 ++Idx;
1398 assert(Idx < Ops.size());
1399 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1400 // We found two constants, fold them together!
1401 ConstantInt *Fold = ConstantInt::get(
1402 APIntOps::umax(LHSC->getValue()->getValue(),
1403 RHSC->getValue()->getValue()));
1404 Ops[0] = getConstant(Fold);
1405 Ops.erase(Ops.begin()+1); // Erase the folded element
1406 if (Ops.size() == 1) return Ops[0];
1407 LHSC = cast<SCEVConstant>(Ops[0]);
1408 }
1409
1410 // If we are left with a constant zero, strip it off.
1411 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1412 Ops.erase(Ops.begin());
1413 --Idx;
1414 }
1415 }
1416
1417 if (Ops.size() == 1) return Ops[0];
1418
1419 // Find the first UMax
1420 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1421 ++Idx;
1422
1423 // Check to see if one of the operands is a UMax. If so, expand its operands
1424 // onto our operand list, and recurse to simplify.
1425 if (Idx < Ops.size()) {
1426 bool DeletedUMax = false;
1427 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1428 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1429 Ops.erase(Ops.begin()+Idx);
1430 DeletedUMax = true;
1431 }
1432
1433 if (DeletedUMax)
1434 return getUMaxExpr(Ops);
1435 }
1436
1437 // Okay, check to see if the same value occurs in the operand list twice. If
1438 // so, delete one. Since we sorted the list, these values are required to
1439 // be adjacent.
1440 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1441 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1442 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1443 --i; --e;
1444 }
1445
1446 if (Ops.size() == 1) return Ops[0];
1447
1448 assert(!Ops.empty() && "Reduced umax down to nothing!");
1449
1450 // Okay, it looks like we really DO need a umax expr. Check to see if we
1451 // already have one, otherwise create a new one.
1452 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1453 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1454 SCEVOps)];
1455 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1456 return Result;
1457}
1458
Dan Gohman89f85052007-10-22 18:31:58 +00001459SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001461 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001462 if (isa<ConstantPointerNull>(V))
1463 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1465 if (Result == 0) Result = new SCEVUnknown(V);
1466 return Result;
1467}
1468
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470// Basic SCEV Analysis and PHI Idiom Recognition Code
1471//
1472
1473/// deleteValueFromRecords - This method should be called by the
1474/// client before it removes an instruction from the program, to make sure
1475/// that no dangling references are left around.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001476void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 SmallVector<Value *, 16> Worklist;
1478
1479 if (Scalars.erase(V)) {
1480 if (PHINode *PN = dyn_cast<PHINode>(V))
1481 ConstantEvolutionLoopExitValue.erase(PN);
1482 Worklist.push_back(V);
1483 }
1484
1485 while (!Worklist.empty()) {
1486 Value *VV = Worklist.back();
1487 Worklist.pop_back();
1488
1489 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1490 UI != UE; ++UI) {
1491 Instruction *Inst = cast<Instruction>(*UI);
1492 if (Scalars.erase(Inst)) {
1493 if (PHINode *PN = dyn_cast<PHINode>(VV))
1494 ConstantEvolutionLoopExitValue.erase(PN);
1495 Worklist.push_back(Inst);
1496 }
1497 }
1498 }
1499}
1500
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001501/// isSCEVable - Test if values of the given type are analyzable within
1502/// the SCEV framework. This primarily includes integer types, and it
1503/// can optionally include pointer types if the ScalarEvolution class
1504/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001505bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001506 // Integers are always SCEVable.
1507 if (Ty->isInteger())
1508 return true;
1509
1510 // Pointers are SCEVable if TargetData information is available
1511 // to provide pointer size information.
1512 if (isa<PointerType>(Ty))
1513 return TD != NULL;
1514
1515 // Otherwise it's not SCEVable.
1516 return false;
1517}
1518
1519/// getTypeSizeInBits - Return the size in bits of the specified type,
1520/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001521uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001522 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1523
1524 // If we have a TargetData, use it!
1525 if (TD)
1526 return TD->getTypeSizeInBits(Ty);
1527
1528 // Otherwise, we support only integer types.
1529 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1530 return Ty->getPrimitiveSizeInBits();
1531}
1532
1533/// getEffectiveSCEVType - Return a type with the same bitwidth as
1534/// the given type and which represents how SCEV will treat the given
1535/// type, for which isSCEVable must return true. For pointer types,
1536/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001537const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001538 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1539
1540 if (Ty->isInteger())
1541 return Ty;
1542
1543 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1544 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001545}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001547SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001548 return UnknownValue;
1549}
1550
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1552/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001553SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001554 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001555
1556 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1557 if (I != Scalars.end()) return I->second;
1558 SCEVHandle S = createSCEV(V);
1559 Scalars.insert(std::make_pair(V, S));
1560 return S;
1561}
1562
Dan Gohman01c2ee72009-04-16 03:18:22 +00001563/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1564/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001565SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1566 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001567 Constant *C;
1568 if (Val == 0)
1569 C = Constant::getNullValue(Ty);
1570 else if (Ty->isFloatingPoint())
1571 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1572 APFloat::IEEEdouble, Val));
1573 else
1574 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001575 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001576}
1577
1578/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1579///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001580SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001581 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001582 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001583
1584 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001585 Ty = getEffectiveSCEVType(Ty);
1586 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001587}
1588
1589/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001590SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001591 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001592 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001593
1594 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001595 Ty = getEffectiveSCEVType(Ty);
1596 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001597 return getMinusSCEV(AllOnes, V);
1598}
1599
1600/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1601///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001602SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001603 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001604 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001605 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001606}
1607
1608/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1609/// input value to the specified type. If the type must be extended, it is zero
1610/// extended.
1611SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001612ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001613 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001614 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001615 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1616 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001617 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001618 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001619 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001620 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001621 return getTruncateExpr(V, Ty);
1622 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001623}
1624
1625/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1626/// input value to the specified type. If the type must be extended, it is sign
1627/// extended.
1628SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001629ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001630 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001631 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001632 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1633 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001634 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001635 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001636 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001637 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001638 return getTruncateExpr(V, Ty);
1639 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001640}
1641
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1643/// the specified instruction and replaces any references to the symbolic value
1644/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001645void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1647 const SCEVHandle &NewVal) {
1648 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1649 if (SI == Scalars.end()) return;
1650
1651 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001652 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001653 if (NV == SI->second) return; // No change.
1654
1655 SI->second = NV; // Update the scalars map!
1656
1657 // Any instruction values that use this instruction might also need to be
1658 // updated!
1659 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1660 UI != E; ++UI)
1661 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1662}
1663
1664/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1665/// a loop header, making it a potential recurrence, or it doesn't.
1666///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001667SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001669 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670 if (L->getHeader() == PN->getParent()) {
1671 // If it lives in the loop header, it has two incoming values, one
1672 // from outside the loop, and one from inside.
1673 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1674 unsigned BackEdge = IncomingEdge^1;
1675
1676 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001677 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001678 assert(Scalars.find(PN) == Scalars.end() &&
1679 "PHI node already processed?");
1680 Scalars.insert(std::make_pair(PN, SymbolicName));
1681
1682 // Using this symbolic name for the PHI, analyze the value coming around
1683 // the back-edge.
1684 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1685
1686 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1687 // has a special value for the first iteration of the loop.
1688
1689 // If the value coming around the backedge is an add with the symbolic
1690 // value we just inserted, then we found a simple induction variable!
1691 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1692 // If there is a single occurrence of the symbolic value, replace it
1693 // with a recurrence.
1694 unsigned FoundIndex = Add->getNumOperands();
1695 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1696 if (Add->getOperand(i) == SymbolicName)
1697 if (FoundIndex == e) {
1698 FoundIndex = i;
1699 break;
1700 }
1701
1702 if (FoundIndex != Add->getNumOperands()) {
1703 // Create an add with everything but the specified operand.
1704 std::vector<SCEVHandle> Ops;
1705 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1706 if (i != FoundIndex)
1707 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001708 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001709
1710 // This is not a valid addrec if the step amount is varying each
1711 // loop iteration, but is not itself an addrec in this loop.
1712 if (Accum->isLoopInvariant(L) ||
1713 (isa<SCEVAddRecExpr>(Accum) &&
1714 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1715 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001716 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001717
1718 // Okay, for the entire analysis of this edge we assumed the PHI
1719 // to be symbolic. We now need to go back and update all of the
1720 // entries for the scalars that use the PHI (except for the PHI
1721 // itself) to use the new analyzed value instead of the "symbolic"
1722 // value.
1723 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1724 return PHISCEV;
1725 }
1726 }
1727 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1728 // Otherwise, this could be a loop like this:
1729 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1730 // In this case, j = {1,+,1} and BEValue is j.
1731 // Because the other in-value of i (0) fits the evolution of BEValue
1732 // i really is an addrec evolution.
1733 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1734 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1735
1736 // If StartVal = j.start - j.stride, we can use StartVal as the
1737 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001738 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001739 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001740 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001741 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001742
1743 // Okay, for the entire analysis of this edge we assumed the PHI
1744 // to be symbolic. We now need to go back and update all of the
1745 // entries for the scalars that use the PHI (except for the PHI
1746 // itself) to use the new analyzed value instead of the "symbolic"
1747 // value.
1748 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1749 return PHISCEV;
1750 }
1751 }
1752 }
1753
1754 return SymbolicName;
1755 }
1756
1757 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001758 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759}
1760
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001761/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1762/// guaranteed to end in (at every loop iteration). It is, at the same time,
1763/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1764/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001765static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001766 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001767 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001769 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001770 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1771 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001772
1773 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001774 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1775 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1776 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001777 }
1778
1779 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001780 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1781 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1782 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001783 }
1784
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001786 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001787 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001788 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001789 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001790 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001791 }
1792
1793 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001794 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001795 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1796 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001797 for (unsigned i = 1, e = M->getNumOperands();
1798 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001799 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001800 BitWidth);
1801 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001803
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001804 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001805 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001806 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001807 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001808 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001809 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001811
Nick Lewycky711640a2007-11-25 22:41:31 +00001812 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1813 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001814 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001815 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001816 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001817 return MinOpRes;
1818 }
1819
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001820 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1821 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001822 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001823 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001824 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001825 return MinOpRes;
1826 }
1827
Nick Lewycky35b56022009-01-13 09:18:58 +00001828 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001829 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001830}
1831
1832/// createSCEV - We know that there is no SCEV for the specified value.
1833/// Analyze the expression.
1834///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001835SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001836 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001837 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001838
Dan Gohman3996f472008-06-22 19:56:46 +00001839 unsigned Opcode = Instruction::UserOp1;
1840 if (Instruction *I = dyn_cast<Instruction>(V))
1841 Opcode = I->getOpcode();
1842 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1843 Opcode = CE->getOpcode();
1844 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001845 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001846
Dan Gohman3996f472008-06-22 19:56:46 +00001847 User *U = cast<User>(V);
1848 switch (Opcode) {
1849 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001850 return getAddExpr(getSCEV(U->getOperand(0)),
1851 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001852 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001853 return getMulExpr(getSCEV(U->getOperand(0)),
1854 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001855 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001856 return getUDivExpr(getSCEV(U->getOperand(0)),
1857 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001858 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001859 return getMinusSCEV(getSCEV(U->getOperand(0)),
1860 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001861 case Instruction::And:
1862 // For an expression like x&255 that merely masks off the high bits,
1863 // use zext(trunc(x)) as the SCEV expression.
1864 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001865 if (CI->isNullValue())
1866 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00001867 if (CI->isAllOnesValue())
1868 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001869 const APInt &A = CI->getValue();
1870 unsigned Ones = A.countTrailingOnes();
1871 if (APIntOps::isMask(Ones, A))
1872 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001873 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1874 IntegerType::get(Ones)),
1875 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001876 }
1877 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001878 case Instruction::Or:
1879 // If the RHS of the Or is a constant, we may have something like:
1880 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1881 // optimizations will transparently handle this case.
1882 //
1883 // In order for this transformation to be safe, the LHS must be of the
1884 // form X*(2^n) and the Or constant must be less than 2^n.
1885 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1886 SCEVHandle LHS = getSCEV(U->getOperand(0));
1887 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001888 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001889 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001890 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001891 }
Dan Gohman3996f472008-06-22 19:56:46 +00001892 break;
1893 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001894 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001895 // If the RHS of the xor is a signbit, then this is just an add.
1896 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001897 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001898 return getAddExpr(getSCEV(U->getOperand(0)),
1899 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001900
1901 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001902 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001903 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001904 }
1905 break;
1906
1907 case Instruction::Shl:
1908 // Turn shift left of a constant amount into a multiply.
1909 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1910 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1911 Constant *X = ConstantInt::get(
1912 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001913 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001914 }
1915 break;
1916
Nick Lewycky7fd27892008-07-07 06:15:49 +00001917 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001918 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001919 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1920 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1921 Constant *X = ConstantInt::get(
1922 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001923 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001924 }
1925 break;
1926
Dan Gohman53bf64a2009-04-21 02:26:00 +00001927 case Instruction::AShr:
1928 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1929 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1930 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1931 if (L->getOpcode() == Instruction::Shl &&
1932 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001933 unsigned BitWidth = getTypeSizeInBits(U->getType());
1934 uint64_t Amt = BitWidth - CI->getZExtValue();
1935 if (Amt == BitWidth)
1936 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1937 if (Amt > BitWidth)
1938 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001939 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001940 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001941 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001942 U->getType());
1943 }
1944 break;
1945
Dan Gohman3996f472008-06-22 19:56:46 +00001946 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001947 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001948
1949 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001950 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001951
1952 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001953 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001954
1955 case Instruction::BitCast:
1956 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001957 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001958 return getSCEV(U->getOperand(0));
1959 break;
1960
Dan Gohman01c2ee72009-04-16 03:18:22 +00001961 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001962 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001963 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001964 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001965
1966 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001967 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001968 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1969 U->getType());
1970
1971 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001972 if (!TD) break; // Without TD we can't analyze pointers.
1973 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001974 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001975 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001976 gep_type_iterator GTI = gep_type_begin(U);
1977 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1978 E = U->op_end();
1979 I != E; ++I) {
1980 Value *Index = *I;
1981 // Compute the (potentially symbolic) offset in bytes for this index.
1982 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1983 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001984 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001985 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1986 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001987 TotalOffset = getAddExpr(TotalOffset,
1988 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001989 } else {
1990 // For an array, add the element offset, explicitly scaled.
1991 SCEVHandle LocalOffset = getSCEV(Index);
1992 if (!isa<PointerType>(LocalOffset->getType()))
1993 // Getelementptr indicies are signed.
1994 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1995 IntPtrTy);
1996 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001997 getMulExpr(LocalOffset,
1998 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1999 IntPtrTy));
2000 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002001 }
2002 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002003 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002004 }
2005
Dan Gohman3996f472008-06-22 19:56:46 +00002006 case Instruction::PHI:
2007 return createNodeForPHI(cast<PHINode>(U));
2008
2009 case Instruction::Select:
2010 // This could be a smax or umax that was lowered earlier.
2011 // Try to recover it.
2012 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2013 Value *LHS = ICI->getOperand(0);
2014 Value *RHS = ICI->getOperand(1);
2015 switch (ICI->getPredicate()) {
2016 case ICmpInst::ICMP_SLT:
2017 case ICmpInst::ICMP_SLE:
2018 std::swap(LHS, RHS);
2019 // fall through
2020 case ICmpInst::ICMP_SGT:
2021 case ICmpInst::ICMP_SGE:
2022 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002023 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002024 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002025 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002026 return getNotSCEV(getSMaxExpr(
2027 getNotSCEV(getSCEV(LHS)),
2028 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002029 break;
2030 case ICmpInst::ICMP_ULT:
2031 case ICmpInst::ICMP_ULE:
2032 std::swap(LHS, RHS);
2033 // fall through
2034 case ICmpInst::ICMP_UGT:
2035 case ICmpInst::ICMP_UGE:
2036 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002037 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002038 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2039 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002040 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2041 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002042 break;
2043 default:
2044 break;
2045 }
2046 }
2047
2048 default: // We cannot analyze this expression.
2049 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050 }
2051
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002052 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053}
2054
2055
2056
2057//===----------------------------------------------------------------------===//
2058// Iteration Count Computation Code
2059//
2060
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002061/// getBackedgeTakenCount - If the specified loop has a predictable
2062/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2063/// object. The backedge-taken count is the number of times the loop header
2064/// will be branched to from within the loop. This is one less than the
2065/// trip count of the loop, since it doesn't count the first iteration,
2066/// when the header is branched to from outside the loop.
2067///
2068/// Note that it is not valid to call this method on a loop without a
2069/// loop-invariant backedge-taken count (see
2070/// hasLoopInvariantBackedgeTakenCount).
2071///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002072SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002073 // Initially insert a CouldNotCompute for this loop. If the insertion
2074 // succeeds, procede to actually compute a backedge-taken count and
2075 // update the value. The temporary CouldNotCompute value tells SCEV
2076 // code elsewhere that it shouldn't attempt to request a new
2077 // backedge-taken count, which could result in infinite recursion.
2078 std::pair<std::map<const Loop*, SCEVHandle>::iterator, bool> Pair =
2079 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2080 if (Pair.second) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002081 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082 if (ItCount != UnknownValue) {
2083 assert(ItCount->isLoopInvariant(L) &&
2084 "Computed trip count isn't loop invariant for loop!");
2085 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002086
2087 // Now that we know the trip count for this loop, forget any
2088 // existing SCEV values for PHI nodes in this loop since they
2089 // are only conservative estimates made without the benefit
2090 // of trip count information.
2091 for (BasicBlock::iterator I = L->getHeader()->begin();
2092 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2093 deleteValueFromRecords(PN);
2094
2095 // Update the value in the map.
2096 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002097 } else if (isa<PHINode>(L->getHeader()->begin())) {
2098 // Only count loops that have phi nodes as not being computable.
2099 ++NumTripCountsNotComputed;
2100 }
2101 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002102 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002103}
2104
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002105/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002106/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002107/// ScalarEvolution's ability to compute a trip count, or if the loop
2108/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002109void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002110 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002111}
2112
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002113/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2114/// of the specified loop will execute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002115SCEVHandle ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002116 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002117 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002118 L->getExitBlocks(ExitBlocks);
2119 if (ExitBlocks.size() != 1) return UnknownValue;
2120
2121 // Okay, there is one exit block. Try to find the condition that causes the
2122 // loop to be exited.
2123 BasicBlock *ExitBlock = ExitBlocks[0];
2124
2125 BasicBlock *ExitingBlock = 0;
2126 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2127 PI != E; ++PI)
2128 if (L->contains(*PI)) {
2129 if (ExitingBlock == 0)
2130 ExitingBlock = *PI;
2131 else
2132 return UnknownValue; // More than one block exiting!
2133 }
2134 assert(ExitingBlock && "No exits from loop, something is broken!");
2135
2136 // Okay, we've computed the exiting block. See what condition causes us to
2137 // exit.
2138 //
2139 // FIXME: we should be able to handle switch instructions (with a single exit)
2140 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2141 if (ExitBr == 0) return UnknownValue;
2142 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2143
2144 // At this point, we know we have a conditional branch that determines whether
2145 // the loop is exited. However, we don't know if the branch is executed each
2146 // time through the loop. If not, then the execution count of the branch will
2147 // not be equal to the trip count of the loop.
2148 //
2149 // Currently we check for this by checking to see if the Exit branch goes to
2150 // the loop header. If so, we know it will always execute the same number of
2151 // times as the loop. We also handle the case where the exit block *is* the
2152 // loop header. This is common for un-rotated loops. More extensive analysis
2153 // could be done to handle more cases here.
2154 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2155 ExitBr->getSuccessor(1) != L->getHeader() &&
2156 ExitBr->getParent() != L->getHeader())
2157 return UnknownValue;
2158
2159 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2160
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002161 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002162 // Note that ICmpInst deals with pointer comparisons too so we must check
2163 // the type of the operand.
2164 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002165 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166 ExitBr->getSuccessor(0) == ExitBlock);
2167
2168 // If the condition was exit on true, convert the condition to exit on false
2169 ICmpInst::Predicate Cond;
2170 if (ExitBr->getSuccessor(1) == ExitBlock)
2171 Cond = ExitCond->getPredicate();
2172 else
2173 Cond = ExitCond->getInversePredicate();
2174
2175 // Handle common loops like: for (X = "string"; *X; ++X)
2176 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2177 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2178 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002179 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002180 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2181 }
2182
2183 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2184 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2185
2186 // Try to evaluate any dependencies out of the loop.
2187 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2188 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2189 Tmp = getSCEVAtScope(RHS, L);
2190 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2191
2192 // At this point, we would like to compute how many iterations of the
2193 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002194 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2195 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002196 std::swap(LHS, RHS);
2197 Cond = ICmpInst::getSwappedPredicate(Cond);
2198 }
2199
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002200 // If we have a comparison of a chrec against a constant, try to use value
2201 // ranges to answer this query.
2202 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2203 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2204 if (AddRec->getLoop() == L) {
2205 // Form the comparison range using the constant of the correct type so
2206 // that the ConstantRange class knows to do a signed or unsigned
2207 // comparison.
2208 ConstantInt *CompVal = RHSC->getValue();
2209 const Type *RealTy = ExitCond->getOperand(0)->getType();
2210 CompVal = dyn_cast<ConstantInt>(
2211 ConstantExpr::getBitCast(CompVal, RealTy));
2212 if (CompVal) {
2213 // Form the constant range.
2214 ConstantRange CompRange(
2215 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2216
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002217 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002218 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2219 }
2220 }
2221
2222 switch (Cond) {
2223 case ICmpInst::ICMP_NE: { // while (X != Y)
2224 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002225 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002226 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2227 break;
2228 }
2229 case ICmpInst::ICMP_EQ: {
2230 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002231 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002232 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2233 break;
2234 }
2235 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002236 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002237 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2238 break;
2239 }
2240 case ICmpInst::ICMP_SGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002241 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2242 getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002243 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2244 break;
2245 }
2246 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002247 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002248 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2249 break;
2250 }
2251 case ICmpInst::ICMP_UGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002252 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2253 getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002254 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2255 break;
2256 }
2257 default:
2258#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002259 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002261 errs() << "[unsigned] ";
2262 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 << Instruction::getOpcodeName(Instruction::ICmp)
2264 << " " << *RHS << "\n";
2265#endif
2266 break;
2267 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002268 return
2269 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2270 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002271}
2272
2273static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002274EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2275 ScalarEvolution &SE) {
2276 SCEVHandle InVal = SE.getConstant(C);
2277 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002278 assert(isa<SCEVConstant>(Val) &&
2279 "Evaluation of SCEV at constant didn't fold correctly?");
2280 return cast<SCEVConstant>(Val)->getValue();
2281}
2282
2283/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2284/// and a GEP expression (missing the pointer index) indexing into it, return
2285/// the addressed element of the initializer or null if the index expression is
2286/// invalid.
2287static Constant *
2288GetAddressedElementFromGlobal(GlobalVariable *GV,
2289 const std::vector<ConstantInt*> &Indices) {
2290 Constant *Init = GV->getInitializer();
2291 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2292 uint64_t Idx = Indices[i]->getZExtValue();
2293 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2294 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2295 Init = cast<Constant>(CS->getOperand(Idx));
2296 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2297 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2298 Init = cast<Constant>(CA->getOperand(Idx));
2299 } else if (isa<ConstantAggregateZero>(Init)) {
2300 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2301 assert(Idx < STy->getNumElements() && "Bad struct index!");
2302 Init = Constant::getNullValue(STy->getElementType(Idx));
2303 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2304 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2305 Init = Constant::getNullValue(ATy->getElementType());
2306 } else {
2307 assert(0 && "Unknown constant aggregate type!");
2308 }
2309 return 0;
2310 } else {
2311 return 0; // Unknown initializer type
2312 }
2313 }
2314 return Init;
2315}
2316
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002317/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2318/// 'icmp op load X, cst', try to see if we can compute the backedge
2319/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002320SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002321ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2322 const Loop *L,
2323 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 if (LI->isVolatile()) return UnknownValue;
2325
2326 // Check to see if the loaded pointer is a getelementptr of a global.
2327 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2328 if (!GEP) return UnknownValue;
2329
2330 // Make sure that it is really a constant global we are gepping, with an
2331 // initializer, and make sure the first IDX is really 0.
2332 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2333 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2334 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2335 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2336 return UnknownValue;
2337
2338 // Okay, we allow one non-constant index into the GEP instruction.
2339 Value *VarIdx = 0;
2340 std::vector<ConstantInt*> Indexes;
2341 unsigned VarIdxNum = 0;
2342 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2343 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2344 Indexes.push_back(CI);
2345 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2346 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2347 VarIdx = GEP->getOperand(i);
2348 VarIdxNum = i-2;
2349 Indexes.push_back(0);
2350 }
2351
2352 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2353 // Check to see if X is a loop variant variable value now.
2354 SCEVHandle Idx = getSCEV(VarIdx);
2355 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2356 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2357
2358 // We can only recognize very limited forms of loop index expressions, in
2359 // particular, only affine AddRec's like {C1,+,C2}.
2360 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2361 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2362 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2363 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2364 return UnknownValue;
2365
2366 unsigned MaxSteps = MaxBruteForceIterations;
2367 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2368 ConstantInt *ItCst =
2369 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002370 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002371
2372 // Form the GEP offset.
2373 Indexes[VarIdxNum] = Val;
2374
2375 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2376 if (Result == 0) break; // Cannot compute!
2377
2378 // Evaluate the condition for this iteration.
2379 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2380 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2381 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2382#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002383 errs() << "\n***\n*** Computed loop count " << *ItCst
2384 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2385 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386#endif
2387 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002388 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002389 }
2390 }
2391 return UnknownValue;
2392}
2393
2394
2395/// CanConstantFold - Return true if we can constant fold an instruction of the
2396/// specified type, assuming that all operands were constants.
2397static bool CanConstantFold(const Instruction *I) {
2398 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2399 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2400 return true;
2401
2402 if (const CallInst *CI = dyn_cast<CallInst>(I))
2403 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002404 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002405 return false;
2406}
2407
2408/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2409/// in the loop that V is derived from. We allow arbitrary operations along the
2410/// way, but the operands of an operation must either be constants or a value
2411/// derived from a constant PHI. If this expression does not fit with these
2412/// constraints, return null.
2413static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2414 // If this is not an instruction, or if this is an instruction outside of the
2415 // loop, it can't be derived from a loop PHI.
2416 Instruction *I = dyn_cast<Instruction>(V);
2417 if (I == 0 || !L->contains(I->getParent())) return 0;
2418
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002419 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002420 if (L->getHeader() == I->getParent())
2421 return PN;
2422 else
2423 // We don't currently keep track of the control flow needed to evaluate
2424 // PHIs, so we cannot handle PHIs inside of loops.
2425 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002427
2428 // If we won't be able to constant fold this expression even if the operands
2429 // are constants, return early.
2430 if (!CanConstantFold(I)) return 0;
2431
2432 // Otherwise, we can evaluate this instruction if all of its operands are
2433 // constant or derived from a PHI node themselves.
2434 PHINode *PHI = 0;
2435 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2436 if (!(isa<Constant>(I->getOperand(Op)) ||
2437 isa<GlobalValue>(I->getOperand(Op)))) {
2438 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2439 if (P == 0) return 0; // Not evolving from PHI
2440 if (PHI == 0)
2441 PHI = P;
2442 else if (PHI != P)
2443 return 0; // Evolving from multiple different PHIs.
2444 }
2445
2446 // This is a expression evolving from a constant PHI!
2447 return PHI;
2448}
2449
2450/// EvaluateExpression - Given an expression that passes the
2451/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2452/// in the loop has the value PHIVal. If we can't fold this expression for some
2453/// reason, return null.
2454static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2455 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002456 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002457 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002458 Instruction *I = cast<Instruction>(V);
2459
2460 std::vector<Constant*> Operands;
2461 Operands.resize(I->getNumOperands());
2462
2463 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2464 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2465 if (Operands[i] == 0) return 0;
2466 }
2467
Chris Lattnerd6e56912007-12-10 22:53:04 +00002468 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2469 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2470 &Operands[0], Operands.size());
2471 else
2472 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2473 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002474}
2475
2476/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2477/// in the header of its containing loop, we know the loop executes a
2478/// constant number of times, and the PHI node is just a recurrence
2479/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002480Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002481getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002482 std::map<PHINode*, Constant*>::iterator I =
2483 ConstantEvolutionLoopExitValue.find(PN);
2484 if (I != ConstantEvolutionLoopExitValue.end())
2485 return I->second;
2486
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002487 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002488 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2489
2490 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2491
2492 // Since the loop is canonicalized, the PHI node must have two entries. One
2493 // entry must be a constant (coming in from outside of the loop), and the
2494 // second must be derived from the same PHI.
2495 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2496 Constant *StartCST =
2497 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2498 if (StartCST == 0)
2499 return RetVal = 0; // Must be a constant.
2500
2501 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2502 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2503 if (PN2 != PN)
2504 return RetVal = 0; // Not derived from same PHI.
2505
2506 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002507 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002508 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2509
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002510 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511 unsigned IterationNum = 0;
2512 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2513 if (IterationNum == NumIterations)
2514 return RetVal = PHIVal; // Got exit value!
2515
2516 // Compute the value of the PHI node for the next iteration.
2517 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2518 if (NextPHI == PHIVal)
2519 return RetVal = NextPHI; // Stopped evolving!
2520 if (NextPHI == 0)
2521 return 0; // Couldn't evaluate!
2522 PHIVal = NextPHI;
2523 }
2524}
2525
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002526/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527/// constant number of times (the condition evolves only from constants),
2528/// try to evaluate a few iterations of the loop until we get the exit
2529/// condition gets a value of ExitWhen (true or false). If we cannot
2530/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002531SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002532ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002533 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2534 if (PN == 0) return UnknownValue;
2535
2536 // Since the loop is canonicalized, the PHI node must have two entries. One
2537 // entry must be a constant (coming in from outside of the loop), and the
2538 // second must be derived from the same PHI.
2539 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2540 Constant *StartCST =
2541 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2542 if (StartCST == 0) return UnknownValue; // Must be a constant.
2543
2544 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2545 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2546 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2547
2548 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2549 // the loop symbolically to determine when the condition gets a value of
2550 // "ExitWhen".
2551 unsigned IterationNum = 0;
2552 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2553 for (Constant *PHIVal = StartCST;
2554 IterationNum != MaxIterations; ++IterationNum) {
2555 ConstantInt *CondVal =
2556 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2557
2558 // Couldn't symbolically evaluate.
2559 if (!CondVal) return UnknownValue;
2560
2561 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2562 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2563 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002564 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002565 }
2566
2567 // Compute the value of the PHI node for the next iteration.
2568 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2569 if (NextPHI == 0 || NextPHI == PHIVal)
2570 return UnknownValue; // Couldn't evaluate or not making progress...
2571 PHIVal = NextPHI;
2572 }
2573
2574 // Too many iterations were needed to evaluate.
2575 return UnknownValue;
2576}
2577
2578/// getSCEVAtScope - Compute the value of the specified expression within the
2579/// indicated loop (which may be null to indicate in no loop). If the
2580/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002581SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002582 // FIXME: this should be turned into a virtual method on SCEV!
2583
2584 if (isa<SCEVConstant>(V)) return V;
2585
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002586 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002587 // exit value from the loop without using SCEVs.
2588 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2589 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002590 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002591 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2592 if (PHINode *PN = dyn_cast<PHINode>(I))
2593 if (PN->getParent() == LI->getHeader()) {
2594 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002595 // to see if the loop that contains it has a known backedge-taken
2596 // count. If so, we may be able to force computation of the exit
2597 // value.
2598 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2599 if (SCEVConstant *BTCC =
2600 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002601 // Okay, we know how many times the containing loop executes. If
2602 // this is a constant evolving PHI node, get the final value at
2603 // the specified iteration number.
2604 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002605 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002606 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002607 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002608 }
2609 }
2610
2611 // Okay, this is an expression that we cannot symbolically evaluate
2612 // into a SCEV. Check to see if it's possible to symbolically evaluate
2613 // the arguments into constants, and if so, try to constant propagate the
2614 // result. This is particularly useful for computing loop exit values.
2615 if (CanConstantFold(I)) {
2616 std::vector<Constant*> Operands;
2617 Operands.reserve(I->getNumOperands());
2618 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2619 Value *Op = I->getOperand(i);
2620 if (Constant *C = dyn_cast<Constant>(Op)) {
2621 Operands.push_back(C);
2622 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002623 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002624 // non-integer and non-pointer, don't even try to analyze them
2625 // with scev techniques.
2626 if (!isa<IntegerType>(Op->getType()) &&
2627 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002628 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002629
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002630 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2631 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2632 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2633 Op->getType(),
2634 false));
2635 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2636 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2637 Operands.push_back(ConstantExpr::getIntegerCast(C,
2638 Op->getType(),
2639 false));
2640 else
2641 return V;
2642 } else {
2643 return V;
2644 }
2645 }
2646 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002647
2648 Constant *C;
2649 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2650 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2651 &Operands[0], Operands.size());
2652 else
2653 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2654 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002655 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002656 }
2657 }
2658
2659 // This is some other type of SCEVUnknown, just return it.
2660 return V;
2661 }
2662
2663 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2664 // Avoid performing the look-up in the common case where the specified
2665 // expression has no loop-variant portions.
2666 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2667 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2668 if (OpAtScope != Comm->getOperand(i)) {
2669 if (OpAtScope == UnknownValue) return UnknownValue;
2670 // Okay, at least one of these operands is loop variant but might be
2671 // foldable. Build a new instance of the folded commutative expression.
2672 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2673 NewOps.push_back(OpAtScope);
2674
2675 for (++i; i != e; ++i) {
2676 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2677 if (OpAtScope == UnknownValue) return UnknownValue;
2678 NewOps.push_back(OpAtScope);
2679 }
2680 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002681 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002682 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002683 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002684 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002685 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002686 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002687 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002688 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002689 }
2690 }
2691 // If we got here, all operands are loop invariant.
2692 return Comm;
2693 }
2694
Nick Lewycky35b56022009-01-13 09:18:58 +00002695 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2696 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002698 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002699 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002700 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2701 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002702 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 }
2704
2705 // If this is a loop recurrence for a loop that does not contain L, then we
2706 // are dealing with the final value computed by the loop.
2707 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2708 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2709 // To evaluate this recurrence, we need to know how many times the AddRec
2710 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002711 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2712 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713
Eli Friedman7489ec92008-08-04 23:49:06 +00002714 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002715 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002716 }
2717 return UnknownValue;
2718 }
2719
2720 //assert(0 && "Unknown SCEV type!");
2721 return UnknownValue;
2722}
2723
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002724/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2725/// at the specified scope in the program. The L value specifies a loop
2726/// nest to evaluate the expression at, where null is the top-level or a
2727/// specified loop is immediately inside of the loop.
2728///
2729/// This method can be used to compute the exit value for a variable defined
2730/// in a loop by querying what the value will hold in the parent loop.
2731///
2732/// If this value is not computable at this scope, a SCEVCouldNotCompute
2733/// object is returned.
2734SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2735 return getSCEVAtScope(getSCEV(V), L);
2736}
2737
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002738/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2739/// following equation:
2740///
2741/// A * X = B (mod N)
2742///
2743/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2744/// A and B isn't important.
2745///
2746/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2747static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2748 ScalarEvolution &SE) {
2749 uint32_t BW = A.getBitWidth();
2750 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2751 assert(A != 0 && "A must be non-zero.");
2752
2753 // 1. D = gcd(A, N)
2754 //
2755 // The gcd of A and N may have only one prime factor: 2. The number of
2756 // trailing zeros in A is its multiplicity
2757 uint32_t Mult2 = A.countTrailingZeros();
2758 // D = 2^Mult2
2759
2760 // 2. Check if B is divisible by D.
2761 //
2762 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2763 // is not less than multiplicity of this prime factor for D.
2764 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002765 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002766
2767 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2768 // modulo (N / D).
2769 //
2770 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2771 // bit width during computations.
2772 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2773 APInt Mod(BW + 1, 0);
2774 Mod.set(BW - Mult2); // Mod = N / D
2775 APInt I = AD.multiplicativeInverse(Mod);
2776
2777 // 4. Compute the minimum unsigned root of the equation:
2778 // I * (B / D) mod (N / D)
2779 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2780
2781 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2782 // bits.
2783 return SE.getConstant(Result.trunc(BW));
2784}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002785
2786/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2787/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2788/// might be the same) or two SCEVCouldNotCompute objects.
2789///
2790static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002791SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002792 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2793 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2794 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2795 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2796
2797 // We currently can only solve this if the coefficients are constants.
2798 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002799 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002800 return std::make_pair(CNC, CNC);
2801 }
2802
2803 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2804 const APInt &L = LC->getValue()->getValue();
2805 const APInt &M = MC->getValue()->getValue();
2806 const APInt &N = NC->getValue()->getValue();
2807 APInt Two(BitWidth, 2);
2808 APInt Four(BitWidth, 4);
2809
2810 {
2811 using namespace APIntOps;
2812 const APInt& C = L;
2813 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2814 // The B coefficient is M-N/2
2815 APInt B(M);
2816 B -= sdiv(N,Two);
2817
2818 // The A coefficient is N/2
2819 APInt A(N.sdiv(Two));
2820
2821 // Compute the B^2-4ac term.
2822 APInt SqrtTerm(B);
2823 SqrtTerm *= B;
2824 SqrtTerm -= Four * (A * C);
2825
2826 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2827 // integer value or else APInt::sqrt() will assert.
2828 APInt SqrtVal(SqrtTerm.sqrt());
2829
2830 // Compute the two solutions for the quadratic formula.
2831 // The divisions must be performed as signed divisions.
2832 APInt NegB(-B);
2833 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002834 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002835 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002836 return std::make_pair(CNC, CNC);
2837 }
2838
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002839 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2840 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2841
Dan Gohman89f85052007-10-22 18:31:58 +00002842 return std::make_pair(SE.getConstant(Solution1),
2843 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002844 } // end APIntOps namespace
2845}
2846
2847/// HowFarToZero - Return the number of times a backedge comparing the specified
2848/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002849SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002850 // If the value is a constant
2851 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2852 // If the value is already zero, the branch will execute zero times.
2853 if (C->getValue()->isZero()) return C;
2854 return UnknownValue; // Otherwise it will loop infinitely.
2855 }
2856
2857 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2858 if (!AddRec || AddRec->getLoop() != L)
2859 return UnknownValue;
2860
2861 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002862 // If this is an affine expression, the execution count of this branch is
2863 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002864 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002865 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002867 // equivalent to:
2868 //
2869 // Step*N = -Start (mod 2^BW)
2870 //
2871 // where BW is the common bit width of Start and Step.
2872
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873 // Get the initial value for the loop.
2874 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2875 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002876
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002877 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002878
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002880 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002881
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002882 // First, handle unitary steps.
2883 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002884 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002885 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2886 return Start; // N = Start (as unsigned)
2887
2888 // Then, try to solve the above equation provided that Start is constant.
2889 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2890 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002891 -StartC->getValue()->getValue(),
2892 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002893 }
2894 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2895 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2896 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002897 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2898 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002899 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2900 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2901 if (R1) {
2902#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002903 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2904 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905#endif
2906 // Pick the smallest positive root value.
2907 if (ConstantInt *CB =
2908 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2909 R1->getValue(), R2->getValue()))) {
2910 if (CB->getZExtValue() == false)
2911 std::swap(R1, R2); // R1 is the minimum root now.
2912
2913 // We can only use this value if the chrec ends up with an exact zero
2914 // value at this index. When solving for "X*X != 5", for example, we
2915 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002916 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002917 if (Val->isZero())
2918 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002919 }
2920 }
2921 }
2922
2923 return UnknownValue;
2924}
2925
2926/// HowFarToNonZero - Return the number of times a backedge checking the
2927/// specified value for nonzero will execute. If not computable, return
2928/// UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002929SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002930 // Loops that look like: while (X == 0) are very strange indeed. We don't
2931 // handle them yet except for the trivial case. This could be expanded in the
2932 // future as needed.
2933
2934 // If the value is a constant, check to see if it is known to be non-zero
2935 // already. If so, the backedge will execute zero times.
2936 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002937 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002938 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002939 return UnknownValue; // Otherwise it will loop infinitely.
2940 }
2941
2942 // We could implement others, but I really doubt anyone writes loops like
2943 // this, and if they did, they would already be constant folded.
2944 return UnknownValue;
2945}
2946
Dan Gohman1cddf972008-09-15 22:18:04 +00002947/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2948/// (which may not be an immediate predecessor) which has exactly one
2949/// successor from which BB is reachable, or null if no such block is
2950/// found.
2951///
2952BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002953ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1cddf972008-09-15 22:18:04 +00002954 // If the block has a unique predecessor, the predecessor must have
2955 // no other successors from which BB is reachable.
2956 if (BasicBlock *Pred = BB->getSinglePredecessor())
2957 return Pred;
2958
2959 // A loop's header is defined to be a block that dominates the loop.
2960 // If the loop has a preheader, it must be a block that has exactly
2961 // one successor that can reach BB. This is slightly more strict
2962 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002963 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00002964 return L->getLoopPreheader();
2965
2966 return 0;
2967}
2968
Dan Gohmancacd2012009-02-12 22:19:27 +00002969/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002970/// a conditional between LHS and RHS.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002971bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohmancacd2012009-02-12 22:19:27 +00002972 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002973 SCEV *LHS, SCEV *RHS) {
2974 BasicBlock *Preheader = L->getLoopPreheader();
2975 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002976
Dan Gohmanab678fb2008-08-12 20:17:31 +00002977 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002978 // there are predecessors that can be found that have unique successors
2979 // leading to the original header.
2980 for (; Preheader;
2981 PreheaderDest = Preheader,
2982 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002983
2984 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002985 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002986 if (!LoopEntryPredicate ||
2987 LoopEntryPredicate->isUnconditional())
2988 continue;
2989
2990 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2991 if (!ICI) continue;
2992
2993 // Now that we found a conditional branch that dominates the loop, check to
2994 // see if it is the comparison we are looking for.
2995 Value *PreCondLHS = ICI->getOperand(0);
2996 Value *PreCondRHS = ICI->getOperand(1);
2997 ICmpInst::Predicate Cond;
2998 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2999 Cond = ICI->getPredicate();
3000 else
3001 Cond = ICI->getInversePredicate();
3002
Dan Gohmancacd2012009-02-12 22:19:27 +00003003 if (Cond == Pred)
3004 ; // An exact match.
3005 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3006 ; // The actual condition is beyond sufficient.
3007 else
3008 // Check a few special cases.
3009 switch (Cond) {
3010 case ICmpInst::ICMP_UGT:
3011 if (Pred == ICmpInst::ICMP_ULT) {
3012 std::swap(PreCondLHS, PreCondRHS);
3013 Cond = ICmpInst::ICMP_ULT;
3014 break;
3015 }
3016 continue;
3017 case ICmpInst::ICMP_SGT:
3018 if (Pred == ICmpInst::ICMP_SLT) {
3019 std::swap(PreCondLHS, PreCondRHS);
3020 Cond = ICmpInst::ICMP_SLT;
3021 break;
3022 }
3023 continue;
3024 case ICmpInst::ICMP_NE:
3025 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3026 // so check for this case by checking if the NE is comparing against
3027 // a minimum or maximum constant.
3028 if (!ICmpInst::isTrueWhenEqual(Pred))
3029 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3030 const APInt &A = CI->getValue();
3031 switch (Pred) {
3032 case ICmpInst::ICMP_SLT:
3033 if (A.isMaxSignedValue()) break;
3034 continue;
3035 case ICmpInst::ICMP_SGT:
3036 if (A.isMinSignedValue()) break;
3037 continue;
3038 case ICmpInst::ICMP_ULT:
3039 if (A.isMaxValue()) break;
3040 continue;
3041 case ICmpInst::ICMP_UGT:
3042 if (A.isMinValue()) break;
3043 continue;
3044 default:
3045 continue;
3046 }
3047 Cond = ICmpInst::ICMP_NE;
3048 // NE is symmetric but the original comparison may not be. Swap
3049 // the operands if necessary so that they match below.
3050 if (isa<SCEVConstant>(LHS))
3051 std::swap(PreCondLHS, PreCondRHS);
3052 break;
3053 }
3054 continue;
3055 default:
3056 // We weren't able to reconcile the condition.
3057 continue;
3058 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003059
3060 if (!PreCondLHS->getType()->isInteger()) continue;
3061
3062 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3063 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3064 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003065 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3066 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003067 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003068 }
3069
Dan Gohmanab678fb2008-08-12 20:17:31 +00003070 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003071}
3072
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003073/// HowManyLessThans - Return the number of times a backedge containing the
3074/// specified less-than comparison will execute. If not computable, return
3075/// UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003076SCEVHandle ScalarEvolution::
Nick Lewycky35b56022009-01-13 09:18:58 +00003077HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003078 // Only handle: "ADDREC < LoopInvariant".
3079 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3080
3081 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3082 if (!AddRec || AddRec->getLoop() != L)
3083 return UnknownValue;
3084
3085 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003086 // FORNOW: We only support unit strides.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003087 SCEVHandle One = getIntegerSCEV(1, RHS->getType());
Nick Lewycky35b56022009-01-13 09:18:58 +00003088 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 return UnknownValue;
3090
Nick Lewycky35b56022009-01-13 09:18:58 +00003091 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3092 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3093 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003094 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003096 // First, we get the value of the LHS in the first iteration: n
3097 SCEVHandle Start = AddRec->getOperand(0);
3098
Dan Gohmancacd2012009-02-12 22:19:27 +00003099 if (isLoopGuardedByCond(L,
3100 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003101 getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003102 // Since we know that the condition is true in order to enter the loop,
3103 // we know that it will run exactly m-n times.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003104 return getMinusSCEV(RHS, Start);
Nick Lewycky35b56022009-01-13 09:18:58 +00003105 } else {
3106 // Then, we get the value of the LHS in the first iteration in which the
3107 // above condition doesn't hold. This equals to max(m,n).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003108 SCEVHandle End = isSigned ? getSMaxExpr(RHS, Start)
3109 : getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003110
Nick Lewycky35b56022009-01-13 09:18:58 +00003111 // Finally, we subtract these two values to get the number of times the
3112 // backedge is executed: max(m,n)-n.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003113 return getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00003114 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115 }
3116
3117 return UnknownValue;
3118}
3119
3120/// getNumIterationsInRange - Return the number of iterations of this loop that
3121/// produce values in the specified constant range. Another way of looking at
3122/// this is that it returns the first iteration number where the value is not in
3123/// the condition, thus computing the exit count. If the iteration count can't
3124/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003125SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3126 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003127 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003128 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003129
3130 // If the start is a non-zero constant, shift the range to simplify things.
3131 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3132 if (!SC->getValue()->isZero()) {
3133 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003134 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3135 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003136 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3137 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003138 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003139 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003140 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003141 }
3142
3143 // The only time we can solve this is when we have all constant indices.
3144 // Otherwise, we cannot determine the overflow conditions.
3145 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3146 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003147 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003148
3149
3150 // Okay at this point we know that all elements of the chrec are constants and
3151 // that the start element is zero.
3152
3153 // First check to see if the range contains zero. If not, the first
3154 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003155 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003156 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003157 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003158
3159 if (isAffine()) {
3160 // If this is an affine expression then we have this situation:
3161 // Solve {0,+,A} in Range === Ax in Range
3162
3163 // We know that zero is in the range. If A is positive then we know that
3164 // the upper value of the range must be the first possible exit value.
3165 // If A is negative then the lower of the range is the last possible loop
3166 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003167 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3169 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3170
3171 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003172 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3174
3175 // Evaluate at the exit value. If we really did fall out of the valid
3176 // range, then we computed our trip count, otherwise wrap around or other
3177 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003178 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003180 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003181
3182 // Ensure that the previous value is in the range. This is a sanity check.
3183 assert(Range.contains(
3184 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003185 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003186 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003187 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 } else if (isQuadratic()) {
3189 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3190 // quadratic equation to solve it. To do this, we must frame our problem in
3191 // terms of figuring out when zero is crossed, instead of when
3192 // Range.getUpper() is crossed.
3193 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003194 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3195 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003196
3197 // Next, solve the constructed addrec
3198 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003199 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003200 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3201 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3202 if (R1) {
3203 // Pick the smallest positive root value.
3204 if (ConstantInt *CB =
3205 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3206 R1->getValue(), R2->getValue()))) {
3207 if (CB->getZExtValue() == false)
3208 std::swap(R1, R2); // R1 is the minimum root now.
3209
3210 // Make sure the root is not off by one. The returned iteration should
3211 // not be in the range, but the previous one should be. When solving
3212 // for "X*X < 5", for example, we should not return a root of 2.
3213 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003214 R1->getValue(),
3215 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216 if (Range.contains(R1Val->getValue())) {
3217 // The next iteration must be out of the range...
3218 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3219
Dan Gohman89f85052007-10-22 18:31:58 +00003220 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003222 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003223 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 }
3225
3226 // If R1 was not in the range, then it is a good return value. Make
3227 // sure that R1-1 WAS in the range though, just in case.
3228 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003229 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003230 if (Range.contains(R1Val->getValue()))
3231 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003232 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233 }
3234 }
3235 }
3236
Dan Gohman0ad08b02009-04-18 17:58:19 +00003237 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003238}
3239
3240
3241
3242//===----------------------------------------------------------------------===//
3243// ScalarEvolution Class Implementation
3244//===----------------------------------------------------------------------===//
3245
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003246ScalarEvolution::ScalarEvolution()
3247 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3248}
3249
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003250bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003251 this->F = &F;
3252 LI = &getAnalysis<LoopInfo>();
3253 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254 return false;
3255}
3256
3257void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003258 Scalars.clear();
3259 BackedgeTakenCounts.clear();
3260 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003261}
3262
3263void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3264 AU.setPreservesAll();
3265 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003266}
3267
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003268bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003269 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003270}
3271
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003272static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003273 const Loop *L) {
3274 // Print all inner loops first
3275 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3276 PrintLoopInfo(OS, SE, *I);
3277
Nick Lewyckye5da1912008-01-02 02:49:20 +00003278 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003279
Devang Patel02451fa2007-08-21 00:31:24 +00003280 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003281 L->getExitBlocks(ExitBlocks);
3282 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003283 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003285 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3286 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003287 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003288 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003289 }
3290
Nick Lewyckye5da1912008-01-02 02:49:20 +00003291 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292}
3293
Dan Gohman13058cc2009-04-21 00:47:46 +00003294void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003295 // ScalarEvolution's implementaiton of the print method is to print
3296 // out SCEV values of all instructions that are interesting. Doing
3297 // this potentially causes it to create new SCEV objects though,
3298 // which technically conflicts with the const qualifier. This isn't
3299 // observable from outside the class though (the hasSCEV function
3300 // notwithstanding), so casting away the const isn't dangerous.
3301 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003302
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003303 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003304 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3305 if (I->getType()->isInteger()) {
3306 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003307 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003308 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003309 SV->print(OS);
3310 OS << "\t\t";
3311
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003312 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003313 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003314 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003315 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3316 OS << "<<Unknown>>";
3317 } else {
3318 OS << *ExitValue;
3319 }
3320 }
3321
3322
3323 OS << "\n";
3324 }
3325
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003326 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3327 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3328 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003329}
Dan Gohman13058cc2009-04-21 00:47:46 +00003330
3331void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3332 raw_os_ostream OS(o);
3333 print(OS, M);
3334}