blob: b81df12b4c667e1e6041a217db310279d8ffb424 [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 Gohmanc9119222009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223}
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 Gohmanc9119222009-04-29 20:27:52 +0000243 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244}
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 Gohmanc9119222009-04-29 20:27:52 +0000264 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265}
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
Dale Johannesen68264ff2009-04-29 16:38:47 +0000815 // the addrec's type. The count needs to be the same whether sign
816 // extended or zero extended.
Dan Gohmana9dba962009-04-27 20:16:15 +0000817 SCEVHandle CastedBECount =
818 getTruncateOrZeroExtend(BECount, Start->getType());
819 if (BECount ==
Dale Johannesen68264ff2009-04-29 16:38:47 +0000820 getTruncateOrZeroExtend(CastedBECount, BECount->getType()) &&
821 BECount ==
822 getTruncateOrSignExtend(CastedBECount, BECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000823 const Type *WideTy =
824 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
825 SCEVHandle SMul =
826 getMulExpr(CastedBECount,
827 getTruncateOrSignExtend(Step, Start->getType()));
828 // Check whether Start+Step*BECount has no signed overflow.
829 if (getSignExtendExpr(SMul, WideTy) ==
830 getMulExpr(getSignExtendExpr(CastedBECount, WideTy),
831 getSignExtendExpr(Step, WideTy))) {
832 SCEVHandle Add = getAddExpr(Start, SMul);
833 if (getSignExtendExpr(Add, WideTy) ==
834 getAddExpr(getSignExtendExpr(Start, WideTy),
835 getSignExtendExpr(SMul, WideTy)))
836 // Return the expression with the addrec on the outside.
837 return getAddRecExpr(getSignExtendExpr(Start, Ty),
838 getSignExtendExpr(Step, Ty),
839 AR->getLoop());
840 }
841 }
842 }
843 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844
845 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
846 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
847 return Result;
848}
849
850// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000851SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 assert(!Ops.empty() && "Cannot get empty add!");
853 if (Ops.size() == 1) return Ops[0];
854
855 // Sort by complexity, this groups all similar expression types together.
856 GroupByComplexity(Ops);
857
858 // If there are any constants, fold them together.
859 unsigned Idx = 0;
860 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
861 ++Idx;
862 assert(Idx < Ops.size());
863 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
864 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000865 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
866 RHSC->getValue()->getValue());
867 Ops[0] = getConstant(Fold);
868 Ops.erase(Ops.begin()+1); // Erase the folded element
869 if (Ops.size() == 1) return Ops[0];
870 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 }
872
873 // If we are left with a constant zero being added, strip it off.
874 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
875 Ops.erase(Ops.begin());
876 --Idx;
877 }
878 }
879
880 if (Ops.size() == 1) return Ops[0];
881
882 // Okay, check to see if the same value occurs in the operand list twice. If
883 // so, merge them together into an multiply expression. Since we sorted the
884 // list, these values are required to be adjacent.
885 const Type *Ty = Ops[0]->getType();
886 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
887 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
888 // Found a match, merge the two values into a multiply, and add any
889 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000890 SCEVHandle Two = getIntegerSCEV(2, Ty);
891 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 if (Ops.size() == 2)
893 return Mul;
894 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
895 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000896 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 }
898
899 // Now we know the first non-constant operand. Skip past any cast SCEVs.
900 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
901 ++Idx;
902
903 // If there are add operands they would be next.
904 if (Idx < Ops.size()) {
905 bool DeletedAdd = false;
906 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
907 // If we have an add, expand the add operands onto the end of the operands
908 // list.
909 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
910 Ops.erase(Ops.begin()+Idx);
911 DeletedAdd = true;
912 }
913
914 // If we deleted at least one add, we added operands to the end of the list,
915 // and they are not necessarily sorted. Recurse to resort and resimplify
916 // any operands we just aquired.
917 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000918 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 }
920
921 // Skip over the add expression until we get to a multiply.
922 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
923 ++Idx;
924
925 // If we are adding something to a multiply expression, make sure the
926 // something is not already an operand of the multiply. If so, merge it into
927 // the multiply.
928 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
929 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
930 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
931 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
932 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
933 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
934 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
935 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
936 if (Mul->getNumOperands() != 2) {
937 // If the multiply has more than two operands, we must get the
938 // Y*Z term.
939 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
940 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000941 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 }
Dan Gohman89f85052007-10-22 18:31:58 +0000943 SCEVHandle One = getIntegerSCEV(1, Ty);
944 SCEVHandle AddOne = getAddExpr(InnerMul, One);
945 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 if (Ops.size() == 2) return OuterMul;
947 if (AddOp < Idx) {
948 Ops.erase(Ops.begin()+AddOp);
949 Ops.erase(Ops.begin()+Idx-1);
950 } else {
951 Ops.erase(Ops.begin()+Idx);
952 Ops.erase(Ops.begin()+AddOp-1);
953 }
954 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000955 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 }
957
958 // Check this multiply against other multiplies being added together.
959 for (unsigned OtherMulIdx = Idx+1;
960 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
961 ++OtherMulIdx) {
962 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
963 // If MulOp occurs in OtherMul, we can fold the two multiplies
964 // together.
965 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
966 OMulOp != e; ++OMulOp)
967 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
968 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
969 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
970 if (Mul->getNumOperands() != 2) {
971 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
972 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000973 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 }
975 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
976 if (OtherMul->getNumOperands() != 2) {
977 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
978 OtherMul->op_end());
979 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000980 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 }
Dan Gohman89f85052007-10-22 18:31:58 +0000982 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
983 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 if (Ops.size() == 2) return OuterMul;
985 Ops.erase(Ops.begin()+Idx);
986 Ops.erase(Ops.begin()+OtherMulIdx-1);
987 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000988 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 }
990 }
991 }
992 }
993
994 // If there are any add recurrences in the operands list, see if any other
995 // added values are loop invariant. If so, we can fold them into the
996 // recurrence.
997 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
998 ++Idx;
999
1000 // Scan over all recurrences, trying to fold loop invariants into them.
1001 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1002 // Scan all of the other operands to this add and add them to the vector if
1003 // they are loop invariant w.r.t. the recurrence.
1004 std::vector<SCEVHandle> LIOps;
1005 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1006 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1007 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1008 LIOps.push_back(Ops[i]);
1009 Ops.erase(Ops.begin()+i);
1010 --i; --e;
1011 }
1012
1013 // If we found some loop invariants, fold them into the recurrence.
1014 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001015 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016 LIOps.push_back(AddRec->getStart());
1017
1018 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001019 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020
Dan Gohman89f85052007-10-22 18:31:58 +00001021 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 // If all of the other operands were loop invariant, we are done.
1023 if (Ops.size() == 1) return NewRec;
1024
1025 // Otherwise, add the folded AddRec by the non-liv parts.
1026 for (unsigned i = 0;; ++i)
1027 if (Ops[i] == AddRec) {
1028 Ops[i] = NewRec;
1029 break;
1030 }
Dan Gohman89f85052007-10-22 18:31:58 +00001031 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 }
1033
1034 // Okay, if there weren't any loop invariants to be folded, check to see if
1035 // there are multiple AddRec's with the same loop induction variable being
1036 // added together. If so, we can fold them.
1037 for (unsigned OtherIdx = Idx+1;
1038 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1039 if (OtherIdx != Idx) {
1040 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1041 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1042 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1043 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1044 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1045 if (i >= NewOps.size()) {
1046 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1047 OtherAddRec->op_end());
1048 break;
1049 }
Dan Gohman89f85052007-10-22 18:31:58 +00001050 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 }
Dan Gohman89f85052007-10-22 18:31:58 +00001052 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053
1054 if (Ops.size() == 2) return NewAddRec;
1055
1056 Ops.erase(Ops.begin()+Idx);
1057 Ops.erase(Ops.begin()+OtherIdx-1);
1058 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001059 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060 }
1061 }
1062
1063 // Otherwise couldn't fold anything into this recurrence. Move onto the
1064 // next one.
1065 }
1066
1067 // Okay, it looks like we really DO need an add expr. Check to see if we
1068 // already have one, otherwise create a new one.
1069 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1070 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1071 SCEVOps)];
1072 if (Result == 0) Result = new SCEVAddExpr(Ops);
1073 return Result;
1074}
1075
1076
Dan Gohman89f85052007-10-22 18:31:58 +00001077SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 assert(!Ops.empty() && "Cannot get empty mul!");
1079
1080 // Sort by complexity, this groups all similar expression types together.
1081 GroupByComplexity(Ops);
1082
1083 // If there are any constants, fold them together.
1084 unsigned Idx = 0;
1085 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1086
1087 // C1*(C2+V) -> C1*C2 + C1*V
1088 if (Ops.size() == 2)
1089 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1090 if (Add->getNumOperands() == 2 &&
1091 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001092 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1093 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094
1095
1096 ++Idx;
1097 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1098 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001099 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1100 RHSC->getValue()->getValue());
1101 Ops[0] = getConstant(Fold);
1102 Ops.erase(Ops.begin()+1); // Erase the folded element
1103 if (Ops.size() == 1) return Ops[0];
1104 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 }
1106
1107 // If we are left with a constant one being multiplied, strip it off.
1108 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1109 Ops.erase(Ops.begin());
1110 --Idx;
1111 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1112 // If we have a multiply of zero, it will always be zero.
1113 return Ops[0];
1114 }
1115 }
1116
1117 // Skip over the add expression until we get to a multiply.
1118 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1119 ++Idx;
1120
1121 if (Ops.size() == 1)
1122 return Ops[0];
1123
1124 // If there are mul operands inline them all into this expression.
1125 if (Idx < Ops.size()) {
1126 bool DeletedMul = false;
1127 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1128 // If we have an mul, expand the mul operands onto the end of the operands
1129 // list.
1130 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1131 Ops.erase(Ops.begin()+Idx);
1132 DeletedMul = true;
1133 }
1134
1135 // If we deleted at least one mul, we added operands to the end of the list,
1136 // and they are not necessarily sorted. Recurse to resort and resimplify
1137 // any operands we just aquired.
1138 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001139 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 }
1141
1142 // If there are any add recurrences in the operands list, see if any other
1143 // added values are loop invariant. If so, we can fold them into the
1144 // recurrence.
1145 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1146 ++Idx;
1147
1148 // Scan over all recurrences, trying to fold loop invariants into them.
1149 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1150 // Scan all of the other operands to this mul and add them to the vector if
1151 // they are loop invariant w.r.t. the recurrence.
1152 std::vector<SCEVHandle> LIOps;
1153 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1154 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1155 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1156 LIOps.push_back(Ops[i]);
1157 Ops.erase(Ops.begin()+i);
1158 --i; --e;
1159 }
1160
1161 // If we found some loop invariants, fold them into the recurrence.
1162 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001163 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 std::vector<SCEVHandle> NewOps;
1165 NewOps.reserve(AddRec->getNumOperands());
1166 if (LIOps.size() == 1) {
1167 SCEV *Scale = LIOps[0];
1168 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001169 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 } else {
1171 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1172 std::vector<SCEVHandle> MulOps(LIOps);
1173 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001174 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 }
1176 }
1177
Dan Gohman89f85052007-10-22 18:31:58 +00001178 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179
1180 // If all of the other operands were loop invariant, we are done.
1181 if (Ops.size() == 1) return NewRec;
1182
1183 // Otherwise, multiply the folded AddRec by the non-liv parts.
1184 for (unsigned i = 0;; ++i)
1185 if (Ops[i] == AddRec) {
1186 Ops[i] = NewRec;
1187 break;
1188 }
Dan Gohman89f85052007-10-22 18:31:58 +00001189 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 }
1191
1192 // Okay, if there weren't any loop invariants to be folded, check to see if
1193 // there are multiple AddRec's with the same loop induction variable being
1194 // multiplied together. If so, we can fold them.
1195 for (unsigned OtherIdx = Idx+1;
1196 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1197 if (OtherIdx != Idx) {
1198 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1199 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1200 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1201 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001202 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001204 SCEVHandle B = F->getStepRecurrence(*this);
1205 SCEVHandle D = G->getStepRecurrence(*this);
1206 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1207 getMulExpr(G, B),
1208 getMulExpr(B, D));
1209 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1210 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 if (Ops.size() == 2) return NewAddRec;
1212
1213 Ops.erase(Ops.begin()+Idx);
1214 Ops.erase(Ops.begin()+OtherIdx-1);
1215 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001216 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217 }
1218 }
1219
1220 // Otherwise couldn't fold anything into this recurrence. Move onto the
1221 // next one.
1222 }
1223
1224 // Okay, it looks like we really DO need an mul expr. Check to see if we
1225 // already have one, otherwise create a new one.
1226 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1227 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1228 SCEVOps)];
1229 if (Result == 0)
1230 Result = new SCEVMulExpr(Ops);
1231 return Result;
1232}
1233
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001234SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1236 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001237 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238
1239 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1240 Constant *LHSCV = LHSC->getValue();
1241 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001242 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 }
1244 }
1245
Nick Lewycky35b56022009-01-13 09:18:58 +00001246 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1247
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001248 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1249 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 return Result;
1251}
1252
1253
1254/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1255/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001256SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001257 const SCEVHandle &Step, const Loop *L) {
1258 std::vector<SCEVHandle> Operands;
1259 Operands.push_back(Start);
1260 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1261 if (StepChrec->getLoop() == L) {
1262 Operands.insert(Operands.end(), StepChrec->op_begin(),
1263 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001264 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 }
1266
1267 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001268 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269}
1270
1271/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1272/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001273SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001274 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 if (Operands.size() == 1) return Operands[0];
1276
Dan Gohman7b560c42008-06-18 16:23:07 +00001277 if (Operands.back()->isZero()) {
1278 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001279 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001280 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281
Dan Gohman42936882008-08-08 18:33:12 +00001282 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1283 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1284 const Loop* NestedLoop = NestedAR->getLoop();
1285 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1286 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1287 NestedAR->op_end());
1288 SCEVHandle NestedARHandle(NestedAR);
1289 Operands[0] = NestedAR->getStart();
1290 NestedOperands[0] = getAddRecExpr(Operands, L);
1291 return getAddRecExpr(NestedOperands, NestedLoop);
1292 }
1293 }
1294
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 SCEVAddRecExpr *&Result =
1296 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1297 Operands.end()))];
1298 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1299 return Result;
1300}
1301
Nick Lewycky711640a2007-11-25 22:41:31 +00001302SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1303 const SCEVHandle &RHS) {
1304 std::vector<SCEVHandle> Ops;
1305 Ops.push_back(LHS);
1306 Ops.push_back(RHS);
1307 return getSMaxExpr(Ops);
1308}
1309
1310SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1311 assert(!Ops.empty() && "Cannot get empty smax!");
1312 if (Ops.size() == 1) return Ops[0];
1313
1314 // Sort by complexity, this groups all similar expression types together.
1315 GroupByComplexity(Ops);
1316
1317 // If there are any constants, fold them together.
1318 unsigned Idx = 0;
1319 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1320 ++Idx;
1321 assert(Idx < Ops.size());
1322 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1323 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001324 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001325 APIntOps::smax(LHSC->getValue()->getValue(),
1326 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001327 Ops[0] = getConstant(Fold);
1328 Ops.erase(Ops.begin()+1); // Erase the folded element
1329 if (Ops.size() == 1) return Ops[0];
1330 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001331 }
1332
1333 // If we are left with a constant -inf, strip it off.
1334 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1335 Ops.erase(Ops.begin());
1336 --Idx;
1337 }
1338 }
1339
1340 if (Ops.size() == 1) return Ops[0];
1341
1342 // Find the first SMax
1343 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1344 ++Idx;
1345
1346 // Check to see if one of the operands is an SMax. If so, expand its operands
1347 // onto our operand list, and recurse to simplify.
1348 if (Idx < Ops.size()) {
1349 bool DeletedSMax = false;
1350 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1351 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1352 Ops.erase(Ops.begin()+Idx);
1353 DeletedSMax = true;
1354 }
1355
1356 if (DeletedSMax)
1357 return getSMaxExpr(Ops);
1358 }
1359
1360 // Okay, check to see if the same value occurs in the operand list twice. If
1361 // so, delete one. Since we sorted the list, these values are required to
1362 // be adjacent.
1363 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1364 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1365 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1366 --i; --e;
1367 }
1368
1369 if (Ops.size() == 1) return Ops[0];
1370
1371 assert(!Ops.empty() && "Reduced smax down to nothing!");
1372
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001373 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001374 // already have one, otherwise create a new one.
1375 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1376 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1377 SCEVOps)];
1378 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1379 return Result;
1380}
1381
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001382SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1383 const SCEVHandle &RHS) {
1384 std::vector<SCEVHandle> Ops;
1385 Ops.push_back(LHS);
1386 Ops.push_back(RHS);
1387 return getUMaxExpr(Ops);
1388}
1389
1390SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1391 assert(!Ops.empty() && "Cannot get empty umax!");
1392 if (Ops.size() == 1) return Ops[0];
1393
1394 // Sort by complexity, this groups all similar expression types together.
1395 GroupByComplexity(Ops);
1396
1397 // If there are any constants, fold them together.
1398 unsigned Idx = 0;
1399 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1400 ++Idx;
1401 assert(Idx < Ops.size());
1402 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1403 // We found two constants, fold them together!
1404 ConstantInt *Fold = ConstantInt::get(
1405 APIntOps::umax(LHSC->getValue()->getValue(),
1406 RHSC->getValue()->getValue()));
1407 Ops[0] = getConstant(Fold);
1408 Ops.erase(Ops.begin()+1); // Erase the folded element
1409 if (Ops.size() == 1) return Ops[0];
1410 LHSC = cast<SCEVConstant>(Ops[0]);
1411 }
1412
1413 // If we are left with a constant zero, strip it off.
1414 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1415 Ops.erase(Ops.begin());
1416 --Idx;
1417 }
1418 }
1419
1420 if (Ops.size() == 1) return Ops[0];
1421
1422 // Find the first UMax
1423 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1424 ++Idx;
1425
1426 // Check to see if one of the operands is a UMax. If so, expand its operands
1427 // onto our operand list, and recurse to simplify.
1428 if (Idx < Ops.size()) {
1429 bool DeletedUMax = false;
1430 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1431 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1432 Ops.erase(Ops.begin()+Idx);
1433 DeletedUMax = true;
1434 }
1435
1436 if (DeletedUMax)
1437 return getUMaxExpr(Ops);
1438 }
1439
1440 // Okay, check to see if the same value occurs in the operand list twice. If
1441 // so, delete one. Since we sorted the list, these values are required to
1442 // be adjacent.
1443 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1444 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1445 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1446 --i; --e;
1447 }
1448
1449 if (Ops.size() == 1) return Ops[0];
1450
1451 assert(!Ops.empty() && "Reduced umax down to nothing!");
1452
1453 // Okay, it looks like we really DO need a umax expr. Check to see if we
1454 // already have one, otherwise create a new one.
1455 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1456 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1457 SCEVOps)];
1458 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1459 return Result;
1460}
1461
Dan Gohman89f85052007-10-22 18:31:58 +00001462SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001464 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001465 if (isa<ConstantPointerNull>(V))
1466 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1468 if (Result == 0) Result = new SCEVUnknown(V);
1469 return Result;
1470}
1471
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473// Basic SCEV Analysis and PHI Idiom Recognition Code
1474//
1475
1476/// deleteValueFromRecords - This method should be called by the
1477/// client before it removes an instruction from the program, to make sure
1478/// that no dangling references are left around.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001479void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001480 SmallVector<Value *, 16> Worklist;
1481
1482 if (Scalars.erase(V)) {
1483 if (PHINode *PN = dyn_cast<PHINode>(V))
1484 ConstantEvolutionLoopExitValue.erase(PN);
1485 Worklist.push_back(V);
1486 }
1487
1488 while (!Worklist.empty()) {
1489 Value *VV = Worklist.back();
1490 Worklist.pop_back();
1491
1492 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1493 UI != UE; ++UI) {
1494 Instruction *Inst = cast<Instruction>(*UI);
1495 if (Scalars.erase(Inst)) {
1496 if (PHINode *PN = dyn_cast<PHINode>(VV))
1497 ConstantEvolutionLoopExitValue.erase(PN);
1498 Worklist.push_back(Inst);
1499 }
1500 }
1501 }
1502}
1503
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001504/// isSCEVable - Test if values of the given type are analyzable within
1505/// the SCEV framework. This primarily includes integer types, and it
1506/// can optionally include pointer types if the ScalarEvolution class
1507/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001508bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001509 // Integers are always SCEVable.
1510 if (Ty->isInteger())
1511 return true;
1512
1513 // Pointers are SCEVable if TargetData information is available
1514 // to provide pointer size information.
1515 if (isa<PointerType>(Ty))
1516 return TD != NULL;
1517
1518 // Otherwise it's not SCEVable.
1519 return false;
1520}
1521
1522/// getTypeSizeInBits - Return the size in bits of the specified type,
1523/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001524uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001525 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1526
1527 // If we have a TargetData, use it!
1528 if (TD)
1529 return TD->getTypeSizeInBits(Ty);
1530
1531 // Otherwise, we support only integer types.
1532 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1533 return Ty->getPrimitiveSizeInBits();
1534}
1535
1536/// getEffectiveSCEVType - Return a type with the same bitwidth as
1537/// the given type and which represents how SCEV will treat the given
1538/// type, for which isSCEVable must return true. For pointer types,
1539/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001540const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001541 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1542
1543 if (Ty->isInteger())
1544 return Ty;
1545
1546 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1547 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001548}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001550SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001551 return UnknownValue;
1552}
1553
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1555/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001556SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001557 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558
1559 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1560 if (I != Scalars.end()) return I->second;
1561 SCEVHandle S = createSCEV(V);
1562 Scalars.insert(std::make_pair(V, S));
1563 return S;
1564}
1565
Dan Gohman01c2ee72009-04-16 03:18:22 +00001566/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1567/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001568SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1569 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001570 Constant *C;
1571 if (Val == 0)
1572 C = Constant::getNullValue(Ty);
1573 else if (Ty->isFloatingPoint())
1574 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1575 APFloat::IEEEdouble, Val));
1576 else
1577 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001578 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001579}
1580
1581/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1582///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001583SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001584 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001585 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001586
1587 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001588 Ty = getEffectiveSCEVType(Ty);
1589 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001590}
1591
1592/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001593SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001594 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001595 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001596
1597 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001598 Ty = getEffectiveSCEVType(Ty);
1599 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001600 return getMinusSCEV(AllOnes, V);
1601}
1602
1603/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1604///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001605SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001606 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001607 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001608 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001609}
1610
1611/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1612/// input value to the specified type. If the type must be extended, it is zero
1613/// extended.
1614SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001615ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001616 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001617 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001618 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1619 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001620 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001621 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001622 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001623 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001624 return getTruncateExpr(V, Ty);
1625 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001626}
1627
1628/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1629/// input value to the specified type. If the type must be extended, it is sign
1630/// extended.
1631SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001632ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001633 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001634 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001635 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1636 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001637 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001638 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001639 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001640 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001641 return getTruncateExpr(V, Ty);
1642 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001643}
1644
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1646/// the specified instruction and replaces any references to the symbolic value
1647/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001648void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1650 const SCEVHandle &NewVal) {
1651 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1652 if (SI == Scalars.end()) return;
1653
1654 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001655 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001656 if (NV == SI->second) return; // No change.
1657
1658 SI->second = NV; // Update the scalars map!
1659
1660 // Any instruction values that use this instruction might also need to be
1661 // updated!
1662 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1663 UI != E; ++UI)
1664 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1665}
1666
1667/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1668/// a loop header, making it a potential recurrence, or it doesn't.
1669///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001670SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001672 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673 if (L->getHeader() == PN->getParent()) {
1674 // If it lives in the loop header, it has two incoming values, one
1675 // from outside the loop, and one from inside.
1676 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1677 unsigned BackEdge = IncomingEdge^1;
1678
1679 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001680 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681 assert(Scalars.find(PN) == Scalars.end() &&
1682 "PHI node already processed?");
1683 Scalars.insert(std::make_pair(PN, SymbolicName));
1684
1685 // Using this symbolic name for the PHI, analyze the value coming around
1686 // the back-edge.
1687 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1688
1689 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1690 // has a special value for the first iteration of the loop.
1691
1692 // If the value coming around the backedge is an add with the symbolic
1693 // value we just inserted, then we found a simple induction variable!
1694 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1695 // If there is a single occurrence of the symbolic value, replace it
1696 // with a recurrence.
1697 unsigned FoundIndex = Add->getNumOperands();
1698 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1699 if (Add->getOperand(i) == SymbolicName)
1700 if (FoundIndex == e) {
1701 FoundIndex = i;
1702 break;
1703 }
1704
1705 if (FoundIndex != Add->getNumOperands()) {
1706 // Create an add with everything but the specified operand.
1707 std::vector<SCEVHandle> Ops;
1708 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1709 if (i != FoundIndex)
1710 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001711 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712
1713 // This is not a valid addrec if the step amount is varying each
1714 // loop iteration, but is not itself an addrec in this loop.
1715 if (Accum->isLoopInvariant(L) ||
1716 (isa<SCEVAddRecExpr>(Accum) &&
1717 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1718 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001719 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720
1721 // Okay, for the entire analysis of this edge we assumed the PHI
1722 // to be symbolic. We now need to go back and update all of the
1723 // entries for the scalars that use the PHI (except for the PHI
1724 // itself) to use the new analyzed value instead of the "symbolic"
1725 // value.
1726 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1727 return PHISCEV;
1728 }
1729 }
1730 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1731 // Otherwise, this could be a loop like this:
1732 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1733 // In this case, j = {1,+,1} and BEValue is j.
1734 // Because the other in-value of i (0) fits the evolution of BEValue
1735 // i really is an addrec evolution.
1736 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1737 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1738
1739 // If StartVal = j.start - j.stride, we can use StartVal as the
1740 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001741 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001742 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001743 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001744 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001745
1746 // Okay, for the entire analysis of this edge we assumed the PHI
1747 // to be symbolic. We now need to go back and update all of the
1748 // entries for the scalars that use the PHI (except for the PHI
1749 // itself) to use the new analyzed value instead of the "symbolic"
1750 // value.
1751 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1752 return PHISCEV;
1753 }
1754 }
1755 }
1756
1757 return SymbolicName;
1758 }
1759
1760 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001761 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001762}
1763
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001764/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1765/// guaranteed to end in (at every loop iteration). It is, at the same time,
1766/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1767/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001768static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001769 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001770 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001771
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001772 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001773 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1774 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001775
1776 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001777 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1778 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1779 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001780 }
1781
1782 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001783 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1784 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1785 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001786 }
1787
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001788 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001789 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001790 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001791 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001792 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001793 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794 }
1795
1796 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001797 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001798 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1799 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001800 for (unsigned i = 1, e = M->getNumOperands();
1801 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001802 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001803 BitWidth);
1804 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001805 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001806
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001807 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001808 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001809 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001810 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001811 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001812 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001814
Nick Lewycky711640a2007-11-25 22:41:31 +00001815 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1816 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001817 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001818 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001819 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001820 return MinOpRes;
1821 }
1822
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001823 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1824 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001825 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001826 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001827 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001828 return MinOpRes;
1829 }
1830
Nick Lewycky35b56022009-01-13 09:18:58 +00001831 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001832 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001833}
1834
1835/// createSCEV - We know that there is no SCEV for the specified value.
1836/// Analyze the expression.
1837///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001838SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001839 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001840 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001841
Dan Gohman3996f472008-06-22 19:56:46 +00001842 unsigned Opcode = Instruction::UserOp1;
1843 if (Instruction *I = dyn_cast<Instruction>(V))
1844 Opcode = I->getOpcode();
1845 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1846 Opcode = CE->getOpcode();
1847 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001848 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001849
Dan Gohman3996f472008-06-22 19:56:46 +00001850 User *U = cast<User>(V);
1851 switch (Opcode) {
1852 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001853 return getAddExpr(getSCEV(U->getOperand(0)),
1854 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001855 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001856 return getMulExpr(getSCEV(U->getOperand(0)),
1857 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001858 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001859 return getUDivExpr(getSCEV(U->getOperand(0)),
1860 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001861 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001862 return getMinusSCEV(getSCEV(U->getOperand(0)),
1863 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001864 case Instruction::And:
1865 // For an expression like x&255 that merely masks off the high bits,
1866 // use zext(trunc(x)) as the SCEV expression.
1867 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001868 if (CI->isNullValue())
1869 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00001870 if (CI->isAllOnesValue())
1871 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001872 const APInt &A = CI->getValue();
1873 unsigned Ones = A.countTrailingOnes();
1874 if (APIntOps::isMask(Ones, A))
1875 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001876 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1877 IntegerType::get(Ones)),
1878 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001879 }
1880 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001881 case Instruction::Or:
1882 // If the RHS of the Or is a constant, we may have something like:
1883 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1884 // optimizations will transparently handle this case.
1885 //
1886 // In order for this transformation to be safe, the LHS must be of the
1887 // form X*(2^n) and the Or constant must be less than 2^n.
1888 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1889 SCEVHandle LHS = getSCEV(U->getOperand(0));
1890 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001891 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001892 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001893 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001894 }
Dan Gohman3996f472008-06-22 19:56:46 +00001895 break;
1896 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001897 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001898 // If the RHS of the xor is a signbit, then this is just an add.
1899 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001900 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001901 return getAddExpr(getSCEV(U->getOperand(0)),
1902 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001903
1904 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001905 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001906 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001907 }
1908 break;
1909
1910 case Instruction::Shl:
1911 // Turn shift left of a constant amount into a multiply.
1912 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1913 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1914 Constant *X = ConstantInt::get(
1915 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001916 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001917 }
1918 break;
1919
Nick Lewycky7fd27892008-07-07 06:15:49 +00001920 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001921 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001922 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1923 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1924 Constant *X = ConstantInt::get(
1925 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001926 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001927 }
1928 break;
1929
Dan Gohman53bf64a2009-04-21 02:26:00 +00001930 case Instruction::AShr:
1931 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1932 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1933 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1934 if (L->getOpcode() == Instruction::Shl &&
1935 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001936 unsigned BitWidth = getTypeSizeInBits(U->getType());
1937 uint64_t Amt = BitWidth - CI->getZExtValue();
1938 if (Amt == BitWidth)
1939 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1940 if (Amt > BitWidth)
1941 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001942 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001943 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001944 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001945 U->getType());
1946 }
1947 break;
1948
Dan Gohman3996f472008-06-22 19:56:46 +00001949 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001950 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001951
1952 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001953 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001954
1955 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001956 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001957
1958 case Instruction::BitCast:
1959 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001960 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001961 return getSCEV(U->getOperand(0));
1962 break;
1963
Dan Gohman01c2ee72009-04-16 03:18:22 +00001964 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001965 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001966 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001967 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001968
1969 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001970 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001971 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1972 U->getType());
1973
1974 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001975 if (!TD) break; // Without TD we can't analyze pointers.
1976 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001977 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001978 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001979 gep_type_iterator GTI = gep_type_begin(U);
1980 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1981 E = U->op_end();
1982 I != E; ++I) {
1983 Value *Index = *I;
1984 // Compute the (potentially symbolic) offset in bytes for this index.
1985 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1986 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001987 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001988 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1989 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001990 TotalOffset = getAddExpr(TotalOffset,
1991 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001992 } else {
1993 // For an array, add the element offset, explicitly scaled.
1994 SCEVHandle LocalOffset = getSCEV(Index);
1995 if (!isa<PointerType>(LocalOffset->getType()))
1996 // Getelementptr indicies are signed.
1997 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1998 IntPtrTy);
1999 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002000 getMulExpr(LocalOffset,
2001 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2002 IntPtrTy));
2003 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002004 }
2005 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002006 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002007 }
2008
Dan Gohman3996f472008-06-22 19:56:46 +00002009 case Instruction::PHI:
2010 return createNodeForPHI(cast<PHINode>(U));
2011
2012 case Instruction::Select:
2013 // This could be a smax or umax that was lowered earlier.
2014 // Try to recover it.
2015 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2016 Value *LHS = ICI->getOperand(0);
2017 Value *RHS = ICI->getOperand(1);
2018 switch (ICI->getPredicate()) {
2019 case ICmpInst::ICMP_SLT:
2020 case ICmpInst::ICMP_SLE:
2021 std::swap(LHS, RHS);
2022 // fall through
2023 case ICmpInst::ICMP_SGT:
2024 case ICmpInst::ICMP_SGE:
2025 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002026 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002027 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002028 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002029 return getNotSCEV(getSMaxExpr(
2030 getNotSCEV(getSCEV(LHS)),
2031 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002032 break;
2033 case ICmpInst::ICMP_ULT:
2034 case ICmpInst::ICMP_ULE:
2035 std::swap(LHS, RHS);
2036 // fall through
2037 case ICmpInst::ICMP_UGT:
2038 case ICmpInst::ICMP_UGE:
2039 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002040 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002041 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2042 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002043 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2044 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002045 break;
2046 default:
2047 break;
2048 }
2049 }
2050
2051 default: // We cannot analyze this expression.
2052 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053 }
2054
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002055 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002056}
2057
2058
2059
2060//===----------------------------------------------------------------------===//
2061// Iteration Count Computation Code
2062//
2063
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002064/// getBackedgeTakenCount - If the specified loop has a predictable
2065/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2066/// object. The backedge-taken count is the number of times the loop header
2067/// will be branched to from within the loop. This is one less than the
2068/// trip count of the loop, since it doesn't count the first iteration,
2069/// when the header is branched to from outside the loop.
2070///
2071/// Note that it is not valid to call this method on a loop without a
2072/// loop-invariant backedge-taken count (see
2073/// hasLoopInvariantBackedgeTakenCount).
2074///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002075SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002076 // Initially insert a CouldNotCompute for this loop. If the insertion
2077 // succeeds, procede to actually compute a backedge-taken count and
2078 // update the value. The temporary CouldNotCompute value tells SCEV
2079 // code elsewhere that it shouldn't attempt to request a new
2080 // backedge-taken count, which could result in infinite recursion.
2081 std::pair<std::map<const Loop*, SCEVHandle>::iterator, bool> Pair =
2082 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2083 if (Pair.second) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002084 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 if (ItCount != UnknownValue) {
2086 assert(ItCount->isLoopInvariant(L) &&
2087 "Computed trip count isn't loop invariant for loop!");
2088 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002089
2090 // Now that we know the trip count for this loop, forget any
2091 // existing SCEV values for PHI nodes in this loop since they
2092 // are only conservative estimates made without the benefit
2093 // of trip count information.
2094 for (BasicBlock::iterator I = L->getHeader()->begin();
2095 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2096 deleteValueFromRecords(PN);
2097
2098 // Update the value in the map.
2099 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100 } else if (isa<PHINode>(L->getHeader()->begin())) {
2101 // Only count loops that have phi nodes as not being computable.
2102 ++NumTripCountsNotComputed;
2103 }
2104 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002105 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002106}
2107
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002108/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002109/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002110/// ScalarEvolution's ability to compute a trip count, or if the loop
2111/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002112void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002113 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002114}
2115
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002116/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2117/// of the specified loop will execute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002118SCEVHandle ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002120 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002121 L->getExitBlocks(ExitBlocks);
2122 if (ExitBlocks.size() != 1) return UnknownValue;
2123
2124 // Okay, there is one exit block. Try to find the condition that causes the
2125 // loop to be exited.
2126 BasicBlock *ExitBlock = ExitBlocks[0];
2127
2128 BasicBlock *ExitingBlock = 0;
2129 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2130 PI != E; ++PI)
2131 if (L->contains(*PI)) {
2132 if (ExitingBlock == 0)
2133 ExitingBlock = *PI;
2134 else
2135 return UnknownValue; // More than one block exiting!
2136 }
2137 assert(ExitingBlock && "No exits from loop, something is broken!");
2138
2139 // Okay, we've computed the exiting block. See what condition causes us to
2140 // exit.
2141 //
2142 // FIXME: we should be able to handle switch instructions (with a single exit)
2143 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2144 if (ExitBr == 0) return UnknownValue;
2145 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2146
2147 // At this point, we know we have a conditional branch that determines whether
2148 // the loop is exited. However, we don't know if the branch is executed each
2149 // time through the loop. If not, then the execution count of the branch will
2150 // not be equal to the trip count of the loop.
2151 //
2152 // Currently we check for this by checking to see if the Exit branch goes to
2153 // the loop header. If so, we know it will always execute the same number of
2154 // times as the loop. We also handle the case where the exit block *is* the
2155 // loop header. This is common for un-rotated loops. More extensive analysis
2156 // could be done to handle more cases here.
2157 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2158 ExitBr->getSuccessor(1) != L->getHeader() &&
2159 ExitBr->getParent() != L->getHeader())
2160 return UnknownValue;
2161
2162 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2163
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002164 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002165 // Note that ICmpInst deals with pointer comparisons too so we must check
2166 // the type of the operand.
2167 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002168 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002169 ExitBr->getSuccessor(0) == ExitBlock);
2170
2171 // If the condition was exit on true, convert the condition to exit on false
2172 ICmpInst::Predicate Cond;
2173 if (ExitBr->getSuccessor(1) == ExitBlock)
2174 Cond = ExitCond->getPredicate();
2175 else
2176 Cond = ExitCond->getInversePredicate();
2177
2178 // Handle common loops like: for (X = "string"; *X; ++X)
2179 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2180 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2181 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002182 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2184 }
2185
2186 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2187 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2188
2189 // Try to evaluate any dependencies out of the loop.
2190 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2191 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2192 Tmp = getSCEVAtScope(RHS, L);
2193 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2194
2195 // At this point, we would like to compute how many iterations of the
2196 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002197 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2198 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002199 std::swap(LHS, RHS);
2200 Cond = ICmpInst::getSwappedPredicate(Cond);
2201 }
2202
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002203 // If we have a comparison of a chrec against a constant, try to use value
2204 // ranges to answer this query.
2205 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2206 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2207 if (AddRec->getLoop() == L) {
2208 // Form the comparison range using the constant of the correct type so
2209 // that the ConstantRange class knows to do a signed or unsigned
2210 // comparison.
2211 ConstantInt *CompVal = RHSC->getValue();
2212 const Type *RealTy = ExitCond->getOperand(0)->getType();
2213 CompVal = dyn_cast<ConstantInt>(
2214 ConstantExpr::getBitCast(CompVal, RealTy));
2215 if (CompVal) {
2216 // Form the constant range.
2217 ConstantRange CompRange(
2218 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2219
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002220 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2222 }
2223 }
2224
2225 switch (Cond) {
2226 case ICmpInst::ICMP_NE: { // while (X != Y)
2227 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002228 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002229 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2230 break;
2231 }
2232 case ICmpInst::ICMP_EQ: {
2233 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002234 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2236 break;
2237 }
2238 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002239 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2241 break;
2242 }
2243 case ICmpInst::ICMP_SGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002244 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2245 getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002246 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2247 break;
2248 }
2249 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002250 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002251 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2252 break;
2253 }
2254 case ICmpInst::ICMP_UGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002255 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2256 getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002257 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2258 break;
2259 }
2260 default:
2261#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002262 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002264 errs() << "[unsigned] ";
2265 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002266 << Instruction::getOpcodeName(Instruction::ICmp)
2267 << " " << *RHS << "\n";
2268#endif
2269 break;
2270 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002271 return
2272 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2273 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274}
2275
2276static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002277EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2278 ScalarEvolution &SE) {
2279 SCEVHandle InVal = SE.getConstant(C);
2280 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281 assert(isa<SCEVConstant>(Val) &&
2282 "Evaluation of SCEV at constant didn't fold correctly?");
2283 return cast<SCEVConstant>(Val)->getValue();
2284}
2285
2286/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2287/// and a GEP expression (missing the pointer index) indexing into it, return
2288/// the addressed element of the initializer or null if the index expression is
2289/// invalid.
2290static Constant *
2291GetAddressedElementFromGlobal(GlobalVariable *GV,
2292 const std::vector<ConstantInt*> &Indices) {
2293 Constant *Init = GV->getInitializer();
2294 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2295 uint64_t Idx = Indices[i]->getZExtValue();
2296 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2297 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2298 Init = cast<Constant>(CS->getOperand(Idx));
2299 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2300 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2301 Init = cast<Constant>(CA->getOperand(Idx));
2302 } else if (isa<ConstantAggregateZero>(Init)) {
2303 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2304 assert(Idx < STy->getNumElements() && "Bad struct index!");
2305 Init = Constant::getNullValue(STy->getElementType(Idx));
2306 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2307 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2308 Init = Constant::getNullValue(ATy->getElementType());
2309 } else {
2310 assert(0 && "Unknown constant aggregate type!");
2311 }
2312 return 0;
2313 } else {
2314 return 0; // Unknown initializer type
2315 }
2316 }
2317 return Init;
2318}
2319
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002320/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2321/// 'icmp op load X, cst', try to see if we can compute the backedge
2322/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002323SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002324ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2325 const Loop *L,
2326 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002327 if (LI->isVolatile()) return UnknownValue;
2328
2329 // Check to see if the loaded pointer is a getelementptr of a global.
2330 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2331 if (!GEP) return UnknownValue;
2332
2333 // Make sure that it is really a constant global we are gepping, with an
2334 // initializer, and make sure the first IDX is really 0.
2335 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2336 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2337 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2338 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2339 return UnknownValue;
2340
2341 // Okay, we allow one non-constant index into the GEP instruction.
2342 Value *VarIdx = 0;
2343 std::vector<ConstantInt*> Indexes;
2344 unsigned VarIdxNum = 0;
2345 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2346 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2347 Indexes.push_back(CI);
2348 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2349 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2350 VarIdx = GEP->getOperand(i);
2351 VarIdxNum = i-2;
2352 Indexes.push_back(0);
2353 }
2354
2355 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2356 // Check to see if X is a loop variant variable value now.
2357 SCEVHandle Idx = getSCEV(VarIdx);
2358 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2359 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2360
2361 // We can only recognize very limited forms of loop index expressions, in
2362 // particular, only affine AddRec's like {C1,+,C2}.
2363 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2364 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2365 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2366 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2367 return UnknownValue;
2368
2369 unsigned MaxSteps = MaxBruteForceIterations;
2370 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2371 ConstantInt *ItCst =
2372 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002373 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002374
2375 // Form the GEP offset.
2376 Indexes[VarIdxNum] = Val;
2377
2378 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2379 if (Result == 0) break; // Cannot compute!
2380
2381 // Evaluate the condition for this iteration.
2382 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2383 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2384 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2385#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002386 errs() << "\n***\n*** Computed loop count " << *ItCst
2387 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2388 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002389#endif
2390 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002391 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002392 }
2393 }
2394 return UnknownValue;
2395}
2396
2397
2398/// CanConstantFold - Return true if we can constant fold an instruction of the
2399/// specified type, assuming that all operands were constants.
2400static bool CanConstantFold(const Instruction *I) {
2401 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2402 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2403 return true;
2404
2405 if (const CallInst *CI = dyn_cast<CallInst>(I))
2406 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002407 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002408 return false;
2409}
2410
2411/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2412/// in the loop that V is derived from. We allow arbitrary operations along the
2413/// way, but the operands of an operation must either be constants or a value
2414/// derived from a constant PHI. If this expression does not fit with these
2415/// constraints, return null.
2416static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2417 // If this is not an instruction, or if this is an instruction outside of the
2418 // loop, it can't be derived from a loop PHI.
2419 Instruction *I = dyn_cast<Instruction>(V);
2420 if (I == 0 || !L->contains(I->getParent())) return 0;
2421
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002422 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423 if (L->getHeader() == I->getParent())
2424 return PN;
2425 else
2426 // We don't currently keep track of the control flow needed to evaluate
2427 // PHIs, so we cannot handle PHIs inside of loops.
2428 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002429 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002430
2431 // If we won't be able to constant fold this expression even if the operands
2432 // are constants, return early.
2433 if (!CanConstantFold(I)) return 0;
2434
2435 // Otherwise, we can evaluate this instruction if all of its operands are
2436 // constant or derived from a PHI node themselves.
2437 PHINode *PHI = 0;
2438 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2439 if (!(isa<Constant>(I->getOperand(Op)) ||
2440 isa<GlobalValue>(I->getOperand(Op)))) {
2441 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2442 if (P == 0) return 0; // Not evolving from PHI
2443 if (PHI == 0)
2444 PHI = P;
2445 else if (PHI != P)
2446 return 0; // Evolving from multiple different PHIs.
2447 }
2448
2449 // This is a expression evolving from a constant PHI!
2450 return PHI;
2451}
2452
2453/// EvaluateExpression - Given an expression that passes the
2454/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2455/// in the loop has the value PHIVal. If we can't fold this expression for some
2456/// reason, return null.
2457static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2458 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002460 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002461 Instruction *I = cast<Instruction>(V);
2462
2463 std::vector<Constant*> Operands;
2464 Operands.resize(I->getNumOperands());
2465
2466 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2467 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2468 if (Operands[i] == 0) return 0;
2469 }
2470
Chris Lattnerd6e56912007-12-10 22:53:04 +00002471 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2472 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2473 &Operands[0], Operands.size());
2474 else
2475 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2476 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002477}
2478
2479/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2480/// in the header of its containing loop, we know the loop executes a
2481/// constant number of times, and the PHI node is just a recurrence
2482/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002483Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002484getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002485 std::map<PHINode*, Constant*>::iterator I =
2486 ConstantEvolutionLoopExitValue.find(PN);
2487 if (I != ConstantEvolutionLoopExitValue.end())
2488 return I->second;
2489
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002490 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2492
2493 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2494
2495 // Since the loop is canonicalized, the PHI node must have two entries. One
2496 // entry must be a constant (coming in from outside of the loop), and the
2497 // second must be derived from the same PHI.
2498 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2499 Constant *StartCST =
2500 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2501 if (StartCST == 0)
2502 return RetVal = 0; // Must be a constant.
2503
2504 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2505 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2506 if (PN2 != PN)
2507 return RetVal = 0; // Not derived from same PHI.
2508
2509 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002510 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2512
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002513 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002514 unsigned IterationNum = 0;
2515 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2516 if (IterationNum == NumIterations)
2517 return RetVal = PHIVal; // Got exit value!
2518
2519 // Compute the value of the PHI node for the next iteration.
2520 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2521 if (NextPHI == PHIVal)
2522 return RetVal = NextPHI; // Stopped evolving!
2523 if (NextPHI == 0)
2524 return 0; // Couldn't evaluate!
2525 PHIVal = NextPHI;
2526 }
2527}
2528
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002529/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530/// constant number of times (the condition evolves only from constants),
2531/// try to evaluate a few iterations of the loop until we get the exit
2532/// condition gets a value of ExitWhen (true or false). If we cannot
2533/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002534SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002535ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002536 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2537 if (PN == 0) return UnknownValue;
2538
2539 // Since the loop is canonicalized, the PHI node must have two entries. One
2540 // entry must be a constant (coming in from outside of the loop), and the
2541 // second must be derived from the same PHI.
2542 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2543 Constant *StartCST =
2544 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2545 if (StartCST == 0) return UnknownValue; // Must be a constant.
2546
2547 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2548 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2549 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2550
2551 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2552 // the loop symbolically to determine when the condition gets a value of
2553 // "ExitWhen".
2554 unsigned IterationNum = 0;
2555 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2556 for (Constant *PHIVal = StartCST;
2557 IterationNum != MaxIterations; ++IterationNum) {
2558 ConstantInt *CondVal =
2559 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2560
2561 // Couldn't symbolically evaluate.
2562 if (!CondVal) return UnknownValue;
2563
2564 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2565 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2566 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002567 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002568 }
2569
2570 // Compute the value of the PHI node for the next iteration.
2571 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2572 if (NextPHI == 0 || NextPHI == PHIVal)
2573 return UnknownValue; // Couldn't evaluate or not making progress...
2574 PHIVal = NextPHI;
2575 }
2576
2577 // Too many iterations were needed to evaluate.
2578 return UnknownValue;
2579}
2580
2581/// getSCEVAtScope - Compute the value of the specified expression within the
2582/// indicated loop (which may be null to indicate in no loop). If the
2583/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002584SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002585 // FIXME: this should be turned into a virtual method on SCEV!
2586
2587 if (isa<SCEVConstant>(V)) return V;
2588
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002589 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590 // exit value from the loop without using SCEVs.
2591 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2592 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002593 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002594 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2595 if (PHINode *PN = dyn_cast<PHINode>(I))
2596 if (PN->getParent() == LI->getHeader()) {
2597 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002598 // to see if the loop that contains it has a known backedge-taken
2599 // count. If so, we may be able to force computation of the exit
2600 // value.
2601 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2602 if (SCEVConstant *BTCC =
2603 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002604 // Okay, we know how many times the containing loop executes. If
2605 // this is a constant evolving PHI node, get the final value at
2606 // the specified iteration number.
2607 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002608 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002609 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002610 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002611 }
2612 }
2613
2614 // Okay, this is an expression that we cannot symbolically evaluate
2615 // into a SCEV. Check to see if it's possible to symbolically evaluate
2616 // the arguments into constants, and if so, try to constant propagate the
2617 // result. This is particularly useful for computing loop exit values.
2618 if (CanConstantFold(I)) {
2619 std::vector<Constant*> Operands;
2620 Operands.reserve(I->getNumOperands());
2621 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2622 Value *Op = I->getOperand(i);
2623 if (Constant *C = dyn_cast<Constant>(Op)) {
2624 Operands.push_back(C);
2625 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002626 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002627 // non-integer and non-pointer, don't even try to analyze them
2628 // with scev techniques.
2629 if (!isa<IntegerType>(Op->getType()) &&
2630 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002631 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002632
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002633 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2634 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2635 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2636 Op->getType(),
2637 false));
2638 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2639 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2640 Operands.push_back(ConstantExpr::getIntegerCast(C,
2641 Op->getType(),
2642 false));
2643 else
2644 return V;
2645 } else {
2646 return V;
2647 }
2648 }
2649 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002650
2651 Constant *C;
2652 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2653 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2654 &Operands[0], Operands.size());
2655 else
2656 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2657 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002658 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002659 }
2660 }
2661
2662 // This is some other type of SCEVUnknown, just return it.
2663 return V;
2664 }
2665
2666 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2667 // Avoid performing the look-up in the common case where the specified
2668 // expression has no loop-variant portions.
2669 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2670 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2671 if (OpAtScope != Comm->getOperand(i)) {
2672 if (OpAtScope == UnknownValue) return UnknownValue;
2673 // Okay, at least one of these operands is loop variant but might be
2674 // foldable. Build a new instance of the folded commutative expression.
2675 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2676 NewOps.push_back(OpAtScope);
2677
2678 for (++i; i != e; ++i) {
2679 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2680 if (OpAtScope == UnknownValue) return UnknownValue;
2681 NewOps.push_back(OpAtScope);
2682 }
2683 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002684 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002685 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002686 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002687 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002688 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002689 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002690 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002691 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002692 }
2693 }
2694 // If we got here, all operands are loop invariant.
2695 return Comm;
2696 }
2697
Nick Lewycky35b56022009-01-13 09:18:58 +00002698 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2699 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002700 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002701 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002702 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002703 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2704 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002705 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002706 }
2707
2708 // If this is a loop recurrence for a loop that does not contain L, then we
2709 // are dealing with the final value computed by the loop.
2710 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2711 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2712 // To evaluate this recurrence, we need to know how many times the AddRec
2713 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002714 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2715 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002716
Eli Friedman7489ec92008-08-04 23:49:06 +00002717 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002718 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719 }
2720 return UnknownValue;
2721 }
2722
2723 //assert(0 && "Unknown SCEV type!");
2724 return UnknownValue;
2725}
2726
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002727/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2728/// at the specified scope in the program. The L value specifies a loop
2729/// nest to evaluate the expression at, where null is the top-level or a
2730/// specified loop is immediately inside of the loop.
2731///
2732/// This method can be used to compute the exit value for a variable defined
2733/// in a loop by querying what the value will hold in the parent loop.
2734///
2735/// If this value is not computable at this scope, a SCEVCouldNotCompute
2736/// object is returned.
2737SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2738 return getSCEVAtScope(getSCEV(V), L);
2739}
2740
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002741/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2742/// following equation:
2743///
2744/// A * X = B (mod N)
2745///
2746/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2747/// A and B isn't important.
2748///
2749/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2750static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2751 ScalarEvolution &SE) {
2752 uint32_t BW = A.getBitWidth();
2753 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2754 assert(A != 0 && "A must be non-zero.");
2755
2756 // 1. D = gcd(A, N)
2757 //
2758 // The gcd of A and N may have only one prime factor: 2. The number of
2759 // trailing zeros in A is its multiplicity
2760 uint32_t Mult2 = A.countTrailingZeros();
2761 // D = 2^Mult2
2762
2763 // 2. Check if B is divisible by D.
2764 //
2765 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2766 // is not less than multiplicity of this prime factor for D.
2767 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002768 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002769
2770 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2771 // modulo (N / D).
2772 //
2773 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2774 // bit width during computations.
2775 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2776 APInt Mod(BW + 1, 0);
2777 Mod.set(BW - Mult2); // Mod = N / D
2778 APInt I = AD.multiplicativeInverse(Mod);
2779
2780 // 4. Compute the minimum unsigned root of the equation:
2781 // I * (B / D) mod (N / D)
2782 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2783
2784 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2785 // bits.
2786 return SE.getConstant(Result.trunc(BW));
2787}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002788
2789/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2790/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2791/// might be the same) or two SCEVCouldNotCompute objects.
2792///
2793static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002794SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2796 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2797 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2798 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2799
2800 // We currently can only solve this if the coefficients are constants.
2801 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002802 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002803 return std::make_pair(CNC, CNC);
2804 }
2805
2806 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2807 const APInt &L = LC->getValue()->getValue();
2808 const APInt &M = MC->getValue()->getValue();
2809 const APInt &N = NC->getValue()->getValue();
2810 APInt Two(BitWidth, 2);
2811 APInt Four(BitWidth, 4);
2812
2813 {
2814 using namespace APIntOps;
2815 const APInt& C = L;
2816 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2817 // The B coefficient is M-N/2
2818 APInt B(M);
2819 B -= sdiv(N,Two);
2820
2821 // The A coefficient is N/2
2822 APInt A(N.sdiv(Two));
2823
2824 // Compute the B^2-4ac term.
2825 APInt SqrtTerm(B);
2826 SqrtTerm *= B;
2827 SqrtTerm -= Four * (A * C);
2828
2829 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2830 // integer value or else APInt::sqrt() will assert.
2831 APInt SqrtVal(SqrtTerm.sqrt());
2832
2833 // Compute the two solutions for the quadratic formula.
2834 // The divisions must be performed as signed divisions.
2835 APInt NegB(-B);
2836 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002837 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002838 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002839 return std::make_pair(CNC, CNC);
2840 }
2841
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002842 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2843 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2844
Dan Gohman89f85052007-10-22 18:31:58 +00002845 return std::make_pair(SE.getConstant(Solution1),
2846 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002847 } // end APIntOps namespace
2848}
2849
2850/// HowFarToZero - Return the number of times a backedge comparing the specified
2851/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002852SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002853 // If the value is a constant
2854 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2855 // If the value is already zero, the branch will execute zero times.
2856 if (C->getValue()->isZero()) return C;
2857 return UnknownValue; // Otherwise it will loop infinitely.
2858 }
2859
2860 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2861 if (!AddRec || AddRec->getLoop() != L)
2862 return UnknownValue;
2863
2864 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002865 // If this is an affine expression, the execution count of this branch is
2866 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002868 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002870 // equivalent to:
2871 //
2872 // Step*N = -Start (mod 2^BW)
2873 //
2874 // where BW is the common bit width of Start and Step.
2875
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002876 // Get the initial value for the loop.
2877 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2878 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002880 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002881
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002882 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002883 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002884
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002885 // First, handle unitary steps.
2886 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002887 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002888 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2889 return Start; // N = Start (as unsigned)
2890
2891 // Then, try to solve the above equation provided that Start is constant.
2892 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2893 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002894 -StartC->getValue()->getValue(),
2895 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002896 }
2897 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2898 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2899 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002900 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2901 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002902 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2903 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2904 if (R1) {
2905#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002906 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2907 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002908#endif
2909 // Pick the smallest positive root value.
2910 if (ConstantInt *CB =
2911 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2912 R1->getValue(), R2->getValue()))) {
2913 if (CB->getZExtValue() == false)
2914 std::swap(R1, R2); // R1 is the minimum root now.
2915
2916 // We can only use this value if the chrec ends up with an exact zero
2917 // value at this index. When solving for "X*X != 5", for example, we
2918 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002919 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002920 if (Val->isZero())
2921 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002922 }
2923 }
2924 }
2925
2926 return UnknownValue;
2927}
2928
2929/// HowFarToNonZero - Return the number of times a backedge checking the
2930/// specified value for nonzero will execute. If not computable, return
2931/// UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002932SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002933 // Loops that look like: while (X == 0) are very strange indeed. We don't
2934 // handle them yet except for the trivial case. This could be expanded in the
2935 // future as needed.
2936
2937 // If the value is a constant, check to see if it is known to be non-zero
2938 // already. If so, the backedge will execute zero times.
2939 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002940 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002941 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002942 return UnknownValue; // Otherwise it will loop infinitely.
2943 }
2944
2945 // We could implement others, but I really doubt anyone writes loops like
2946 // this, and if they did, they would already be constant folded.
2947 return UnknownValue;
2948}
2949
Dan Gohman1cddf972008-09-15 22:18:04 +00002950/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2951/// (which may not be an immediate predecessor) which has exactly one
2952/// successor from which BB is reachable, or null if no such block is
2953/// found.
2954///
2955BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002956ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1cddf972008-09-15 22:18:04 +00002957 // If the block has a unique predecessor, the predecessor must have
2958 // no other successors from which BB is reachable.
2959 if (BasicBlock *Pred = BB->getSinglePredecessor())
2960 return Pred;
2961
2962 // A loop's header is defined to be a block that dominates the loop.
2963 // If the loop has a preheader, it must be a block that has exactly
2964 // one successor that can reach BB. This is slightly more strict
2965 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002966 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00002967 return L->getLoopPreheader();
2968
2969 return 0;
2970}
2971
Dan Gohmancacd2012009-02-12 22:19:27 +00002972/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002973/// a conditional between LHS and RHS.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002974bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohmancacd2012009-02-12 22:19:27 +00002975 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002976 SCEV *LHS, SCEV *RHS) {
2977 BasicBlock *Preheader = L->getLoopPreheader();
2978 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002979
Dan Gohmanab678fb2008-08-12 20:17:31 +00002980 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002981 // there are predecessors that can be found that have unique successors
2982 // leading to the original header.
2983 for (; Preheader;
2984 PreheaderDest = Preheader,
2985 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002986
2987 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002988 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002989 if (!LoopEntryPredicate ||
2990 LoopEntryPredicate->isUnconditional())
2991 continue;
2992
2993 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2994 if (!ICI) continue;
2995
2996 // Now that we found a conditional branch that dominates the loop, check to
2997 // see if it is the comparison we are looking for.
2998 Value *PreCondLHS = ICI->getOperand(0);
2999 Value *PreCondRHS = ICI->getOperand(1);
3000 ICmpInst::Predicate Cond;
3001 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3002 Cond = ICI->getPredicate();
3003 else
3004 Cond = ICI->getInversePredicate();
3005
Dan Gohmancacd2012009-02-12 22:19:27 +00003006 if (Cond == Pred)
3007 ; // An exact match.
3008 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3009 ; // The actual condition is beyond sufficient.
3010 else
3011 // Check a few special cases.
3012 switch (Cond) {
3013 case ICmpInst::ICMP_UGT:
3014 if (Pred == ICmpInst::ICMP_ULT) {
3015 std::swap(PreCondLHS, PreCondRHS);
3016 Cond = ICmpInst::ICMP_ULT;
3017 break;
3018 }
3019 continue;
3020 case ICmpInst::ICMP_SGT:
3021 if (Pred == ICmpInst::ICMP_SLT) {
3022 std::swap(PreCondLHS, PreCondRHS);
3023 Cond = ICmpInst::ICMP_SLT;
3024 break;
3025 }
3026 continue;
3027 case ICmpInst::ICMP_NE:
3028 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3029 // so check for this case by checking if the NE is comparing against
3030 // a minimum or maximum constant.
3031 if (!ICmpInst::isTrueWhenEqual(Pred))
3032 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3033 const APInt &A = CI->getValue();
3034 switch (Pred) {
3035 case ICmpInst::ICMP_SLT:
3036 if (A.isMaxSignedValue()) break;
3037 continue;
3038 case ICmpInst::ICMP_SGT:
3039 if (A.isMinSignedValue()) break;
3040 continue;
3041 case ICmpInst::ICMP_ULT:
3042 if (A.isMaxValue()) break;
3043 continue;
3044 case ICmpInst::ICMP_UGT:
3045 if (A.isMinValue()) break;
3046 continue;
3047 default:
3048 continue;
3049 }
3050 Cond = ICmpInst::ICMP_NE;
3051 // NE is symmetric but the original comparison may not be. Swap
3052 // the operands if necessary so that they match below.
3053 if (isa<SCEVConstant>(LHS))
3054 std::swap(PreCondLHS, PreCondRHS);
3055 break;
3056 }
3057 continue;
3058 default:
3059 // We weren't able to reconcile the condition.
3060 continue;
3061 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003062
3063 if (!PreCondLHS->getType()->isInteger()) continue;
3064
3065 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3066 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3067 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003068 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3069 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003070 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003071 }
3072
Dan Gohmanab678fb2008-08-12 20:17:31 +00003073 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003074}
3075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003076/// HowManyLessThans - Return the number of times a backedge containing the
3077/// specified less-than comparison will execute. If not computable, return
3078/// UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003079SCEVHandle ScalarEvolution::
Nick Lewycky35b56022009-01-13 09:18:58 +00003080HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003081 // Only handle: "ADDREC < LoopInvariant".
3082 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3083
3084 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3085 if (!AddRec || AddRec->getLoop() != L)
3086 return UnknownValue;
3087
3088 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003089 // FORNOW: We only support unit strides.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003090 SCEVHandle One = getIntegerSCEV(1, RHS->getType());
Nick Lewycky35b56022009-01-13 09:18:58 +00003091 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003092 return UnknownValue;
3093
Nick Lewycky35b56022009-01-13 09:18:58 +00003094 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3095 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3096 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003097 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003098
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003099 // First, we get the value of the LHS in the first iteration: n
3100 SCEVHandle Start = AddRec->getOperand(0);
3101
Dan Gohmancacd2012009-02-12 22:19:27 +00003102 if (isLoopGuardedByCond(L,
3103 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003104 getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003105 // Since we know that the condition is true in order to enter the loop,
3106 // we know that it will run exactly m-n times.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003107 return getMinusSCEV(RHS, Start);
Nick Lewycky35b56022009-01-13 09:18:58 +00003108 } else {
3109 // Then, we get the value of the LHS in the first iteration in which the
3110 // above condition doesn't hold. This equals to max(m,n).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003111 SCEVHandle End = isSigned ? getSMaxExpr(RHS, Start)
3112 : getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003113
Nick Lewycky35b56022009-01-13 09:18:58 +00003114 // Finally, we subtract these two values to get the number of times the
3115 // backedge is executed: max(m,n)-n.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003116 return getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00003117 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118 }
3119
3120 return UnknownValue;
3121}
3122
3123/// getNumIterationsInRange - Return the number of iterations of this loop that
3124/// produce values in the specified constant range. Another way of looking at
3125/// this is that it returns the first iteration number where the value is not in
3126/// the condition, thus computing the exit count. If the iteration count can't
3127/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003128SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3129 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003130 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003131 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003132
3133 // If the start is a non-zero constant, shift the range to simplify things.
3134 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3135 if (!SC->getValue()->isZero()) {
3136 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003137 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3138 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003139 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3140 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003141 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003142 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003143 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003144 }
3145
3146 // The only time we can solve this is when we have all constant indices.
3147 // Otherwise, we cannot determine the overflow conditions.
3148 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3149 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003150 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151
3152
3153 // Okay at this point we know that all elements of the chrec are constants and
3154 // that the start element is zero.
3155
3156 // First check to see if the range contains zero. If not, the first
3157 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003158 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003159 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003160 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161
3162 if (isAffine()) {
3163 // If this is an affine expression then we have this situation:
3164 // Solve {0,+,A} in Range === Ax in Range
3165
3166 // We know that zero is in the range. If A is positive then we know that
3167 // the upper value of the range must be the first possible exit value.
3168 // If A is negative then the lower of the range is the last possible loop
3169 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003170 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003171 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3172 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3173
3174 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003175 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3177
3178 // Evaluate at the exit value. If we really did fall out of the valid
3179 // range, then we computed our trip count, otherwise wrap around or other
3180 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003181 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003182 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003183 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184
3185 // Ensure that the previous value is in the range. This is a sanity check.
3186 assert(Range.contains(
3187 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003188 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003189 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003190 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003191 } else if (isQuadratic()) {
3192 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3193 // quadratic equation to solve it. To do this, we must frame our problem in
3194 // terms of figuring out when zero is crossed, instead of when
3195 // Range.getUpper() is crossed.
3196 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003197 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3198 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003199
3200 // Next, solve the constructed addrec
3201 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003202 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3204 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3205 if (R1) {
3206 // Pick the smallest positive root value.
3207 if (ConstantInt *CB =
3208 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3209 R1->getValue(), R2->getValue()))) {
3210 if (CB->getZExtValue() == false)
3211 std::swap(R1, R2); // R1 is the minimum root now.
3212
3213 // Make sure the root is not off by one. The returned iteration should
3214 // not be in the range, but the previous one should be. When solving
3215 // for "X*X < 5", for example, we should not return a root of 2.
3216 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003217 R1->getValue(),
3218 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 if (Range.contains(R1Val->getValue())) {
3220 // The next iteration must be out of the range...
3221 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3222
Dan Gohman89f85052007-10-22 18:31:58 +00003223 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003225 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003226 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003227 }
3228
3229 // If R1 was not in the range, then it is a good return value. Make
3230 // sure that R1-1 WAS in the range though, just in case.
3231 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003232 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233 if (Range.contains(R1Val->getValue()))
3234 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003235 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003236 }
3237 }
3238 }
3239
Dan Gohman0ad08b02009-04-18 17:58:19 +00003240 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003241}
3242
3243
3244
3245//===----------------------------------------------------------------------===//
3246// ScalarEvolution Class Implementation
3247//===----------------------------------------------------------------------===//
3248
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003249ScalarEvolution::ScalarEvolution()
3250 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3251}
3252
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003253bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003254 this->F = &F;
3255 LI = &getAnalysis<LoopInfo>();
3256 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003257 return false;
3258}
3259
3260void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003261 Scalars.clear();
3262 BackedgeTakenCounts.clear();
3263 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003264}
3265
3266void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3267 AU.setPreservesAll();
3268 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003269}
3270
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003271bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003272 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003273}
3274
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003275static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003276 const Loop *L) {
3277 // Print all inner loops first
3278 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3279 PrintLoopInfo(OS, SE, *I);
3280
Nick Lewyckye5da1912008-01-02 02:49:20 +00003281 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003282
Devang Patel02451fa2007-08-21 00:31:24 +00003283 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284 L->getExitBlocks(ExitBlocks);
3285 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003286 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003287
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003288 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3289 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003290 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003291 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292 }
3293
Nick Lewyckye5da1912008-01-02 02:49:20 +00003294 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295}
3296
Dan Gohman13058cc2009-04-21 00:47:46 +00003297void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003298 // ScalarEvolution's implementaiton of the print method is to print
3299 // out SCEV values of all instructions that are interesting. Doing
3300 // this potentially causes it to create new SCEV objects though,
3301 // which technically conflicts with the const qualifier. This isn't
3302 // observable from outside the class though (the hasSCEV function
3303 // notwithstanding), so casting away the const isn't dangerous.
3304 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003306 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003307 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3308 if (I->getType()->isInteger()) {
3309 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003310 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003311 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003312 SV->print(OS);
3313 OS << "\t\t";
3314
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003315 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003316 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003317 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003318 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3319 OS << "<<Unknown>>";
3320 } else {
3321 OS << *ExitValue;
3322 }
3323 }
3324
3325
3326 OS << "\n";
3327 }
3328
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003329 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3330 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3331 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003332}
Dan Gohman13058cc2009-04-21 00:47:46 +00003333
3334void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3335 raw_os_ostream OS(o);
3336 print(OS, M);
3337}