blob: d458399c0553b5c8192b5fda0f132a933a031cca [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 Gohmanf17a25c2007-07-18 16:29:46 +0000437 WriteAsOperand(OS, V, false);
438}
439
440//===----------------------------------------------------------------------===//
441// SCEV Utilities
442//===----------------------------------------------------------------------===//
443
444namespace {
445 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
446 /// than the complexity of the RHS. This comparator is used to canonicalize
447 /// expressions.
448 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000449 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 return LHS->getSCEVType() < RHS->getSCEVType();
451 }
452 };
453}
454
455/// GroupByComplexity - Given a list of SCEV objects, order them by their
456/// complexity, and group objects of the same complexity together by value.
457/// When this routine is finished, we know that any duplicates in the vector are
458/// consecutive and that complexity is monotonically increasing.
459///
460/// Note that we go take special precautions to ensure that we get determinstic
461/// results from this routine. In other words, we don't want the results of
462/// this to depend on where the addresses of various SCEV objects happened to
463/// land in memory.
464///
465static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
466 if (Ops.size() < 2) return; // Noop
467 if (Ops.size() == 2) {
468 // This is the common case, which also happens to be trivially simple.
469 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000470 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 std::swap(Ops[0], Ops[1]);
472 return;
473 }
474
475 // Do the rough sort by complexity.
476 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
477
478 // Now that we are sorted by complexity, group elements of the same
479 // complexity. Note that this is, at worst, N^2, but the vector is likely to
480 // be extremely short in practice. Note that we take this approach because we
481 // do not want to depend on the addresses of the objects we are grouping.
482 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
483 SCEV *S = Ops[i];
484 unsigned Complexity = S->getSCEVType();
485
486 // If there are any objects of the same complexity and same value as this
487 // one, group them.
488 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
489 if (Ops[j] == S) { // Found a duplicate.
490 // Move it to immediately after i'th element.
491 std::swap(Ops[i+1], Ops[j]);
492 ++i; // no need to rescan it.
493 if (i == e-2) return; // Done!
494 }
495 }
496 }
497}
498
499
500
501//===----------------------------------------------------------------------===//
502// Simple SCEV method implementations
503//===----------------------------------------------------------------------===//
504
Eli Friedman7489ec92008-08-04 23:49:06 +0000505/// BinomialCoefficient - Compute BC(It, K). The result has width W.
506// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000507static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000508 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000509 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000510 // Handle the simplest case efficiently.
511 if (K == 1)
512 return SE.getTruncateOrZeroExtend(It, ResultTy);
513
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000514 // We are using the following formula for BC(It, K):
515 //
516 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
517 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000518 // Suppose, W is the bitwidth of the return value. We must be prepared for
519 // overflow. Hence, we must assure that the result of our computation is
520 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
521 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000522 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000523 // However, this code doesn't use exactly that formula; the formula it uses
524 // is something like the following, where T is the number of factors of 2 in
525 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
526 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000527 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000528 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000529 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000530 // This formula is trivially equivalent to the previous formula. However,
531 // this formula can be implemented much more efficiently. The trick is that
532 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
533 // arithmetic. To do exact division in modular arithmetic, all we have
534 // to do is multiply by the inverse. Therefore, this step can be done at
535 // width W.
536 //
537 // The next issue is how to safely do the division by 2^T. The way this
538 // is done is by doing the multiplication step at a width of at least W + T
539 // bits. This way, the bottom W+T bits of the product are accurate. Then,
540 // when we perform the division by 2^T (which is equivalent to a right shift
541 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
542 // truncated out after the division by 2^T.
543 //
544 // In comparison to just directly using the first formula, this technique
545 // is much more efficient; using the first formula requires W * K bits,
546 // but this formula less than W + K bits. Also, the first formula requires
547 // a division step, whereas this formula only requires multiplies and shifts.
548 //
549 // It doesn't matter whether the subtraction step is done in the calculation
550 // width or the input iteration count's width; if the subtraction overflows,
551 // the result must be zero anyway. We prefer here to do it in the width of
552 // the induction variable because it helps a lot for certain cases; CodeGen
553 // isn't smart enough to ignore the overflow, which leads to much less
554 // efficient code if the width of the subtraction is wider than the native
555 // register width.
556 //
557 // (It's possible to not widen at all by pulling out factors of 2 before
558 // the multiplication; for example, K=2 can be calculated as
559 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
560 // extra arithmetic, so it's not an obvious win, and it gets
561 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000562
Eli Friedman7489ec92008-08-04 23:49:06 +0000563 // Protection from insane SCEVs; this bound is conservative,
564 // but it probably doesn't matter.
565 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000566 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000567
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000568 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000569
Eli Friedman7489ec92008-08-04 23:49:06 +0000570 // Calculate K! / 2^T and T; we divide out the factors of two before
571 // multiplying for calculating K! / 2^T to avoid overflow.
572 // Other overflow doesn't matter because we only care about the bottom
573 // W bits of the result.
574 APInt OddFactorial(W, 1);
575 unsigned T = 1;
576 for (unsigned i = 3; i <= K; ++i) {
577 APInt Mult(W, i);
578 unsigned TwoFactors = Mult.countTrailingZeros();
579 T += TwoFactors;
580 Mult = Mult.lshr(TwoFactors);
581 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000583
Eli Friedman7489ec92008-08-04 23:49:06 +0000584 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000585 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000586
587 // Calcuate 2^T, at width T+W.
588 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
589
590 // Calculate the multiplicative inverse of K! / 2^T;
591 // this multiplication factor will perform the exact division by
592 // K! / 2^T.
593 APInt Mod = APInt::getSignedMinValue(W+1);
594 APInt MultiplyFactor = OddFactorial.zext(W+1);
595 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
596 MultiplyFactor = MultiplyFactor.trunc(W);
597
598 // Calculate the product, at width T+W
599 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
600 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
601 for (unsigned i = 1; i != K; ++i) {
602 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
603 Dividend = SE.getMulExpr(Dividend,
604 SE.getTruncateOrZeroExtend(S, CalculationTy));
605 }
606
607 // Divide by 2^T
608 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
609
610 // Truncate the result, and divide by K! / 2^T.
611
612 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
613 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614}
615
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616/// evaluateAtIteration - Return the value of this chain of recurrences at
617/// the specified iteration number. We can evaluate this recurrence by
618/// multiplying each element in the chain by the binomial coefficient
619/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
620///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000621/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000623/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624///
Dan Gohman89f85052007-10-22 18:31:58 +0000625SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
626 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000629 // The computation is correct in the face of overflow provided that the
630 // multiplication is performed _after_ the evaluation of the binomial
631 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000632 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000633 if (isa<SCEVCouldNotCompute>(Coeff))
634 return Coeff;
635
636 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 }
638 return Result;
639}
640
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641//===----------------------------------------------------------------------===//
642// SCEV Expression folder implementations
643//===----------------------------------------------------------------------===//
644
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000645SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
646 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000647 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000648 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000649 assert(isSCEVable(Ty) &&
650 "This is not a conversion to a SCEVable type!");
651 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000652
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!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000692 assert(isSCEVable(Ty) &&
693 "This is not a conversion to a SCEVable type!");
694 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000695
Dan Gohman01c2ee72009-04-16 03:18:22 +0000696 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000697 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000698 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
699 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
700 return getUnknown(C);
701 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702
Dan Gohman1a5c4992009-04-22 16:20:48 +0000703 // zext(zext(x)) --> zext(x)
704 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
705 return getZeroExtendExpr(SZ->getOperand(), Ty);
706
Dan Gohmana9dba962009-04-27 20:16:15 +0000707 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000709 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana9dba962009-04-27 20:16:15 +0000711 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
712 if (AR->isAffine()) {
713 // Check whether the backedge-taken count is SCEVCouldNotCompute.
714 // Note that this serves two purposes: It filters out loops that are
715 // simply not analyzable, and it covers the case where this code is
716 // being called from within backedge-taken count analysis, such that
717 // attempting to ask for the backedge-taken count would likely result
718 // in infinite recursion. In the later case, the analysis code will
719 // cope with a conservative value, and it will take care to purge
720 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000721 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
722 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000723 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000724 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000725 SCEVHandle Start = AR->getStart();
726 SCEVHandle Step = AR->getStepRecurrence(*this);
727
728 // Check whether the backedge-taken count can be losslessly casted to
729 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000730 SCEVHandle CastedMaxBECount =
731 getTruncateOrZeroExtend(MaxBECount, Start->getType());
732 if (MaxBECount ==
733 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000734 const Type *WideTy =
735 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000736 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000737 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000738 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000739 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000740 SCEVHandle Add = getAddExpr(Start, ZMul);
741 if (getZeroExtendExpr(Add, WideTy) ==
742 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000743 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000744 getZeroExtendExpr(Step, WideTy))))
745 // Return the expression with the addrec on the outside.
746 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
747 getZeroExtendExpr(Step, Ty),
748 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000749
750 // Similar to above, only this time treat the step value as signed.
751 // This covers loops that count down.
752 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000753 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000754 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000755 Add = getAddExpr(Start, SMul);
756 if (getZeroExtendExpr(Add, WideTy) ==
757 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000758 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000759 getSignExtendExpr(Step, WideTy))))
760 // Return the expression with the addrec on the outside.
761 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
762 getSignExtendExpr(Step, Ty),
763 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000764 }
765 }
766 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767
768 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
769 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
770 return Result;
771}
772
Dan Gohmana9dba962009-04-27 20:16:15 +0000773SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
774 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000775 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000776 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000777 assert(isSCEVable(Ty) &&
778 "This is not a conversion to a SCEVable type!");
779 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000780
Dan Gohman01c2ee72009-04-16 03:18:22 +0000781 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000782 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000783 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
784 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
785 return getUnknown(C);
786 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787
Dan Gohman1a5c4992009-04-22 16:20:48 +0000788 // sext(sext(x)) --> sext(x)
789 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
790 return getSignExtendExpr(SS->getOperand(), Ty);
791
Dan Gohmana9dba962009-04-27 20:16:15 +0000792 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000794 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana9dba962009-04-27 20:16:15 +0000796 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
797 if (AR->isAffine()) {
798 // Check whether the backedge-taken count is SCEVCouldNotCompute.
799 // Note that this serves two purposes: It filters out loops that are
800 // simply not analyzable, and it covers the case where this code is
801 // being called from within backedge-taken count analysis, such that
802 // attempting to ask for the backedge-taken count would likely result
803 // in infinite recursion. In the later case, the analysis code will
804 // cope with a conservative value, and it will take care to purge
805 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000806 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
807 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000808 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000809 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000810 SCEVHandle Start = AR->getStart();
811 SCEVHandle Step = AR->getStepRecurrence(*this);
812
813 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000814 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000815 SCEVHandle CastedMaxBECount =
816 getTruncateOrZeroExtend(MaxBECount, Start->getType());
817 if (MaxBECount ==
818 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000819 const Type *WideTy =
820 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000821 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000822 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000823 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000824 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000825 SCEVHandle Add = getAddExpr(Start, SMul);
826 if (getSignExtendExpr(Add, WideTy) ==
827 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000828 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000829 getSignExtendExpr(Step, WideTy))))
830 // Return the expression with the addrec on the outside.
831 return getAddRecExpr(getSignExtendExpr(Start, Ty),
832 getSignExtendExpr(Step, Ty),
833 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000834 }
835 }
836 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837
838 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
839 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
840 return Result;
841}
842
843// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000844SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 assert(!Ops.empty() && "Cannot get empty add!");
846 if (Ops.size() == 1) return Ops[0];
847
848 // Sort by complexity, this groups all similar expression types together.
849 GroupByComplexity(Ops);
850
851 // If there are any constants, fold them together.
852 unsigned Idx = 0;
853 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
854 ++Idx;
855 assert(Idx < Ops.size());
856 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
857 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000858 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
859 RHSC->getValue()->getValue());
860 Ops[0] = getConstant(Fold);
861 Ops.erase(Ops.begin()+1); // Erase the folded element
862 if (Ops.size() == 1) return Ops[0];
863 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 }
865
866 // If we are left with a constant zero being added, strip it off.
867 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
868 Ops.erase(Ops.begin());
869 --Idx;
870 }
871 }
872
873 if (Ops.size() == 1) return Ops[0];
874
875 // Okay, check to see if the same value occurs in the operand list twice. If
876 // so, merge them together into an multiply expression. Since we sorted the
877 // list, these values are required to be adjacent.
878 const Type *Ty = Ops[0]->getType();
879 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
880 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
881 // Found a match, merge the two values into a multiply, and add any
882 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000883 SCEVHandle Two = getIntegerSCEV(2, Ty);
884 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885 if (Ops.size() == 2)
886 return Mul;
887 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
888 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000889 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 }
891
892 // Now we know the first non-constant operand. Skip past any cast SCEVs.
893 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
894 ++Idx;
895
896 // If there are add operands they would be next.
897 if (Idx < Ops.size()) {
898 bool DeletedAdd = false;
899 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
900 // If we have an add, expand the add operands onto the end of the operands
901 // list.
902 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
903 Ops.erase(Ops.begin()+Idx);
904 DeletedAdd = true;
905 }
906
907 // If we deleted at least one add, we added operands to the end of the list,
908 // and they are not necessarily sorted. Recurse to resort and resimplify
909 // any operands we just aquired.
910 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000911 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 }
913
914 // Skip over the add expression until we get to a multiply.
915 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
916 ++Idx;
917
918 // If we are adding something to a multiply expression, make sure the
919 // something is not already an operand of the multiply. If so, merge it into
920 // the multiply.
921 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
922 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
923 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
924 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
925 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
926 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
927 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
928 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
929 if (Mul->getNumOperands() != 2) {
930 // If the multiply has more than two operands, we must get the
931 // Y*Z term.
932 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
933 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000934 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 }
Dan Gohman89f85052007-10-22 18:31:58 +0000936 SCEVHandle One = getIntegerSCEV(1, Ty);
937 SCEVHandle AddOne = getAddExpr(InnerMul, One);
938 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 if (Ops.size() == 2) return OuterMul;
940 if (AddOp < Idx) {
941 Ops.erase(Ops.begin()+AddOp);
942 Ops.erase(Ops.begin()+Idx-1);
943 } else {
944 Ops.erase(Ops.begin()+Idx);
945 Ops.erase(Ops.begin()+AddOp-1);
946 }
947 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000948 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 }
950
951 // Check this multiply against other multiplies being added together.
952 for (unsigned OtherMulIdx = Idx+1;
953 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
954 ++OtherMulIdx) {
955 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
956 // If MulOp occurs in OtherMul, we can fold the two multiplies
957 // together.
958 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
959 OMulOp != e; ++OMulOp)
960 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
961 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
962 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
963 if (Mul->getNumOperands() != 2) {
964 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
965 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000966 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 }
968 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
969 if (OtherMul->getNumOperands() != 2) {
970 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
971 OtherMul->op_end());
972 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000973 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 }
Dan Gohman89f85052007-10-22 18:31:58 +0000975 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
976 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977 if (Ops.size() == 2) return OuterMul;
978 Ops.erase(Ops.begin()+Idx);
979 Ops.erase(Ops.begin()+OtherMulIdx-1);
980 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000981 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 }
983 }
984 }
985 }
986
987 // If there are any add recurrences in the operands list, see if any other
988 // added values are loop invariant. If so, we can fold them into the
989 // recurrence.
990 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
991 ++Idx;
992
993 // Scan over all recurrences, trying to fold loop invariants into them.
994 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
995 // Scan all of the other operands to this add and add them to the vector if
996 // they are loop invariant w.r.t. the recurrence.
997 std::vector<SCEVHandle> LIOps;
998 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
999 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1000 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1001 LIOps.push_back(Ops[i]);
1002 Ops.erase(Ops.begin()+i);
1003 --i; --e;
1004 }
1005
1006 // If we found some loop invariants, fold them into the recurrence.
1007 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001008 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 LIOps.push_back(AddRec->getStart());
1010
1011 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001012 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013
Dan Gohman89f85052007-10-22 18:31:58 +00001014 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 // If all of the other operands were loop invariant, we are done.
1016 if (Ops.size() == 1) return NewRec;
1017
1018 // Otherwise, add the folded AddRec by the non-liv parts.
1019 for (unsigned i = 0;; ++i)
1020 if (Ops[i] == AddRec) {
1021 Ops[i] = NewRec;
1022 break;
1023 }
Dan Gohman89f85052007-10-22 18:31:58 +00001024 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 }
1026
1027 // Okay, if there weren't any loop invariants to be folded, check to see if
1028 // there are multiple AddRec's with the same loop induction variable being
1029 // added together. If so, we can fold them.
1030 for (unsigned OtherIdx = Idx+1;
1031 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1032 if (OtherIdx != Idx) {
1033 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1034 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1035 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1036 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1037 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1038 if (i >= NewOps.size()) {
1039 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1040 OtherAddRec->op_end());
1041 break;
1042 }
Dan Gohman89f85052007-10-22 18:31:58 +00001043 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 }
Dan Gohman89f85052007-10-22 18:31:58 +00001045 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046
1047 if (Ops.size() == 2) return NewAddRec;
1048
1049 Ops.erase(Ops.begin()+Idx);
1050 Ops.erase(Ops.begin()+OtherIdx-1);
1051 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001052 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 }
1054 }
1055
1056 // Otherwise couldn't fold anything into this recurrence. Move onto the
1057 // next one.
1058 }
1059
1060 // Okay, it looks like we really DO need an add expr. Check to see if we
1061 // already have one, otherwise create a new one.
1062 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1063 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1064 SCEVOps)];
1065 if (Result == 0) Result = new SCEVAddExpr(Ops);
1066 return Result;
1067}
1068
1069
Dan Gohman89f85052007-10-22 18:31:58 +00001070SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 assert(!Ops.empty() && "Cannot get empty mul!");
1072
1073 // Sort by complexity, this groups all similar expression types together.
1074 GroupByComplexity(Ops);
1075
1076 // If there are any constants, fold them together.
1077 unsigned Idx = 0;
1078 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1079
1080 // C1*(C2+V) -> C1*C2 + C1*V
1081 if (Ops.size() == 2)
1082 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
1083 if (Add->getNumOperands() == 2 &&
1084 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001085 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1086 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087
1088
1089 ++Idx;
1090 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1091 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001092 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1093 RHSC->getValue()->getValue());
1094 Ops[0] = getConstant(Fold);
1095 Ops.erase(Ops.begin()+1); // Erase the folded element
1096 if (Ops.size() == 1) return Ops[0];
1097 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 }
1099
1100 // If we are left with a constant one being multiplied, strip it off.
1101 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1102 Ops.erase(Ops.begin());
1103 --Idx;
1104 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1105 // If we have a multiply of zero, it will always be zero.
1106 return Ops[0];
1107 }
1108 }
1109
1110 // Skip over the add expression until we get to a multiply.
1111 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1112 ++Idx;
1113
1114 if (Ops.size() == 1)
1115 return Ops[0];
1116
1117 // If there are mul operands inline them all into this expression.
1118 if (Idx < Ops.size()) {
1119 bool DeletedMul = false;
1120 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1121 // If we have an mul, expand the mul operands onto the end of the operands
1122 // list.
1123 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1124 Ops.erase(Ops.begin()+Idx);
1125 DeletedMul = true;
1126 }
1127
1128 // If we deleted at least one mul, we added operands to the end of the list,
1129 // and they are not necessarily sorted. Recurse to resort and resimplify
1130 // any operands we just aquired.
1131 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001132 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 }
1134
1135 // If there are any add recurrences in the operands list, see if any other
1136 // added values are loop invariant. If so, we can fold them into the
1137 // recurrence.
1138 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1139 ++Idx;
1140
1141 // Scan over all recurrences, trying to fold loop invariants into them.
1142 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1143 // Scan all of the other operands to this mul and add them to the vector if
1144 // they are loop invariant w.r.t. the recurrence.
1145 std::vector<SCEVHandle> LIOps;
1146 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1147 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1148 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1149 LIOps.push_back(Ops[i]);
1150 Ops.erase(Ops.begin()+i);
1151 --i; --e;
1152 }
1153
1154 // If we found some loop invariants, fold them into the recurrence.
1155 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001156 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001157 std::vector<SCEVHandle> NewOps;
1158 NewOps.reserve(AddRec->getNumOperands());
1159 if (LIOps.size() == 1) {
1160 SCEV *Scale = LIOps[0];
1161 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001162 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 } else {
1164 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1165 std::vector<SCEVHandle> MulOps(LIOps);
1166 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001167 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168 }
1169 }
1170
Dan Gohman89f85052007-10-22 18:31:58 +00001171 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172
1173 // If all of the other operands were loop invariant, we are done.
1174 if (Ops.size() == 1) return NewRec;
1175
1176 // Otherwise, multiply the folded AddRec by the non-liv parts.
1177 for (unsigned i = 0;; ++i)
1178 if (Ops[i] == AddRec) {
1179 Ops[i] = NewRec;
1180 break;
1181 }
Dan Gohman89f85052007-10-22 18:31:58 +00001182 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 }
1184
1185 // Okay, if there weren't any loop invariants to be folded, check to see if
1186 // there are multiple AddRec's with the same loop induction variable being
1187 // multiplied together. If so, we can fold them.
1188 for (unsigned OtherIdx = Idx+1;
1189 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1190 if (OtherIdx != Idx) {
1191 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1192 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1193 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1194 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001195 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001197 SCEVHandle B = F->getStepRecurrence(*this);
1198 SCEVHandle D = G->getStepRecurrence(*this);
1199 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1200 getMulExpr(G, B),
1201 getMulExpr(B, D));
1202 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1203 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 if (Ops.size() == 2) return NewAddRec;
1205
1206 Ops.erase(Ops.begin()+Idx);
1207 Ops.erase(Ops.begin()+OtherIdx-1);
1208 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001209 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 }
1211 }
1212
1213 // Otherwise couldn't fold anything into this recurrence. Move onto the
1214 // next one.
1215 }
1216
1217 // Okay, it looks like we really DO need an mul expr. Check to see if we
1218 // already have one, otherwise create a new one.
1219 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1220 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1221 SCEVOps)];
1222 if (Result == 0)
1223 Result = new SCEVMulExpr(Ops);
1224 return Result;
1225}
1226
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001227SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1229 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001230 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231
1232 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1233 Constant *LHSCV = LHSC->getValue();
1234 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001235 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 }
1237 }
1238
Nick Lewycky35b56022009-01-13 09:18:58 +00001239 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1240
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001241 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1242 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 return Result;
1244}
1245
1246
1247/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1248/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001249SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 const SCEVHandle &Step, const Loop *L) {
1251 std::vector<SCEVHandle> Operands;
1252 Operands.push_back(Start);
1253 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1254 if (StepChrec->getLoop() == L) {
1255 Operands.insert(Operands.end(), StepChrec->op_begin(),
1256 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001257 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 }
1259
1260 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001261 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262}
1263
1264/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1265/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001266SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001267 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 if (Operands.size() == 1) return Operands[0];
1269
Dan Gohman7b560c42008-06-18 16:23:07 +00001270 if (Operands.back()->isZero()) {
1271 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001272 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001273 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274
Dan Gohman42936882008-08-08 18:33:12 +00001275 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1276 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1277 const Loop* NestedLoop = NestedAR->getLoop();
1278 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1279 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1280 NestedAR->op_end());
1281 SCEVHandle NestedARHandle(NestedAR);
1282 Operands[0] = NestedAR->getStart();
1283 NestedOperands[0] = getAddRecExpr(Operands, L);
1284 return getAddRecExpr(NestedOperands, NestedLoop);
1285 }
1286 }
1287
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 SCEVAddRecExpr *&Result =
1289 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1290 Operands.end()))];
1291 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1292 return Result;
1293}
1294
Nick Lewycky711640a2007-11-25 22:41:31 +00001295SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1296 const SCEVHandle &RHS) {
1297 std::vector<SCEVHandle> Ops;
1298 Ops.push_back(LHS);
1299 Ops.push_back(RHS);
1300 return getSMaxExpr(Ops);
1301}
1302
1303SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1304 assert(!Ops.empty() && "Cannot get empty smax!");
1305 if (Ops.size() == 1) return Ops[0];
1306
1307 // Sort by complexity, this groups all similar expression types together.
1308 GroupByComplexity(Ops);
1309
1310 // If there are any constants, fold them together.
1311 unsigned Idx = 0;
1312 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1313 ++Idx;
1314 assert(Idx < Ops.size());
1315 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1316 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001317 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001318 APIntOps::smax(LHSC->getValue()->getValue(),
1319 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001320 Ops[0] = getConstant(Fold);
1321 Ops.erase(Ops.begin()+1); // Erase the folded element
1322 if (Ops.size() == 1) return Ops[0];
1323 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001324 }
1325
1326 // If we are left with a constant -inf, strip it off.
1327 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1328 Ops.erase(Ops.begin());
1329 --Idx;
1330 }
1331 }
1332
1333 if (Ops.size() == 1) return Ops[0];
1334
1335 // Find the first SMax
1336 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1337 ++Idx;
1338
1339 // Check to see if one of the operands is an SMax. If so, expand its operands
1340 // onto our operand list, and recurse to simplify.
1341 if (Idx < Ops.size()) {
1342 bool DeletedSMax = false;
1343 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1344 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1345 Ops.erase(Ops.begin()+Idx);
1346 DeletedSMax = true;
1347 }
1348
1349 if (DeletedSMax)
1350 return getSMaxExpr(Ops);
1351 }
1352
1353 // Okay, check to see if the same value occurs in the operand list twice. If
1354 // so, delete one. Since we sorted the list, these values are required to
1355 // be adjacent.
1356 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1357 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1358 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1359 --i; --e;
1360 }
1361
1362 if (Ops.size() == 1) return Ops[0];
1363
1364 assert(!Ops.empty() && "Reduced smax down to nothing!");
1365
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001366 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001367 // already have one, otherwise create a new one.
1368 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1369 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1370 SCEVOps)];
1371 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1372 return Result;
1373}
1374
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001375SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1376 const SCEVHandle &RHS) {
1377 std::vector<SCEVHandle> Ops;
1378 Ops.push_back(LHS);
1379 Ops.push_back(RHS);
1380 return getUMaxExpr(Ops);
1381}
1382
1383SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1384 assert(!Ops.empty() && "Cannot get empty umax!");
1385 if (Ops.size() == 1) return Ops[0];
1386
1387 // Sort by complexity, this groups all similar expression types together.
1388 GroupByComplexity(Ops);
1389
1390 // If there are any constants, fold them together.
1391 unsigned Idx = 0;
1392 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1393 ++Idx;
1394 assert(Idx < Ops.size());
1395 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1396 // We found two constants, fold them together!
1397 ConstantInt *Fold = ConstantInt::get(
1398 APIntOps::umax(LHSC->getValue()->getValue(),
1399 RHSC->getValue()->getValue()));
1400 Ops[0] = getConstant(Fold);
1401 Ops.erase(Ops.begin()+1); // Erase the folded element
1402 if (Ops.size() == 1) return Ops[0];
1403 LHSC = cast<SCEVConstant>(Ops[0]);
1404 }
1405
1406 // If we are left with a constant zero, strip it off.
1407 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1408 Ops.erase(Ops.begin());
1409 --Idx;
1410 }
1411 }
1412
1413 if (Ops.size() == 1) return Ops[0];
1414
1415 // Find the first UMax
1416 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1417 ++Idx;
1418
1419 // Check to see if one of the operands is a UMax. If so, expand its operands
1420 // onto our operand list, and recurse to simplify.
1421 if (Idx < Ops.size()) {
1422 bool DeletedUMax = false;
1423 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1424 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1425 Ops.erase(Ops.begin()+Idx);
1426 DeletedUMax = true;
1427 }
1428
1429 if (DeletedUMax)
1430 return getUMaxExpr(Ops);
1431 }
1432
1433 // Okay, check to see if the same value occurs in the operand list twice. If
1434 // so, delete one. Since we sorted the list, these values are required to
1435 // be adjacent.
1436 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1437 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1438 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1439 --i; --e;
1440 }
1441
1442 if (Ops.size() == 1) return Ops[0];
1443
1444 assert(!Ops.empty() && "Reduced umax down to nothing!");
1445
1446 // Okay, it looks like we really DO need a umax expr. Check to see if we
1447 // already have one, otherwise create a new one.
1448 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1449 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1450 SCEVOps)];
1451 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1452 return Result;
1453}
1454
Dan Gohman89f85052007-10-22 18:31:58 +00001455SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001457 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001458 if (isa<ConstantPointerNull>(V))
1459 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1461 if (Result == 0) Result = new SCEVUnknown(V);
1462 return Result;
1463}
1464
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001465//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001466// Basic SCEV Analysis and PHI Idiom Recognition Code
1467//
1468
1469/// deleteValueFromRecords - This method should be called by the
1470/// client before it removes an instruction from the program, to make sure
1471/// that no dangling references are left around.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001472void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001473 SmallVector<Value *, 16> Worklist;
1474
1475 if (Scalars.erase(V)) {
1476 if (PHINode *PN = dyn_cast<PHINode>(V))
1477 ConstantEvolutionLoopExitValue.erase(PN);
1478 Worklist.push_back(V);
1479 }
1480
1481 while (!Worklist.empty()) {
1482 Value *VV = Worklist.back();
1483 Worklist.pop_back();
1484
1485 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1486 UI != UE; ++UI) {
1487 Instruction *Inst = cast<Instruction>(*UI);
1488 if (Scalars.erase(Inst)) {
1489 if (PHINode *PN = dyn_cast<PHINode>(VV))
1490 ConstantEvolutionLoopExitValue.erase(PN);
1491 Worklist.push_back(Inst);
1492 }
1493 }
1494 }
1495}
1496
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001497/// isSCEVable - Test if values of the given type are analyzable within
1498/// the SCEV framework. This primarily includes integer types, and it
1499/// can optionally include pointer types if the ScalarEvolution class
1500/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001501bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001502 // Integers are always SCEVable.
1503 if (Ty->isInteger())
1504 return true;
1505
1506 // Pointers are SCEVable if TargetData information is available
1507 // to provide pointer size information.
1508 if (isa<PointerType>(Ty))
1509 return TD != NULL;
1510
1511 // Otherwise it's not SCEVable.
1512 return false;
1513}
1514
1515/// getTypeSizeInBits - Return the size in bits of the specified type,
1516/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001517uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001518 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1519
1520 // If we have a TargetData, use it!
1521 if (TD)
1522 return TD->getTypeSizeInBits(Ty);
1523
1524 // Otherwise, we support only integer types.
1525 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1526 return Ty->getPrimitiveSizeInBits();
1527}
1528
1529/// getEffectiveSCEVType - Return a type with the same bitwidth as
1530/// the given type and which represents how SCEV will treat the given
1531/// type, for which isSCEVable must return true. For pointer types,
1532/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001533const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001534 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1535
1536 if (Ty->isInteger())
1537 return Ty;
1538
1539 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1540 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001541}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001543SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001544 return UnknownValue;
1545}
1546
Edwin Török0e828d62009-05-01 08:33:47 +00001547// hasSCEV - Return true if the SCEV for this value has already been
1548/// computed.
1549bool ScalarEvolution::hasSCEV(Value *V) const {
1550 return Scalars.count(V);
1551}
1552
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001553/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1554/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001555SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001556 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557
1558 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1559 if (I != Scalars.end()) return I->second;
1560 SCEVHandle S = createSCEV(V);
1561 Scalars.insert(std::make_pair(V, S));
1562 return S;
1563}
1564
Dan Gohman01c2ee72009-04-16 03:18:22 +00001565/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1566/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001567SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1568 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001569 Constant *C;
1570 if (Val == 0)
1571 C = Constant::getNullValue(Ty);
1572 else if (Ty->isFloatingPoint())
1573 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1574 APFloat::IEEEdouble, Val));
1575 else
1576 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001577 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001578}
1579
1580/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1581///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001582SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001583 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001584 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001585
1586 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001587 Ty = getEffectiveSCEVType(Ty);
1588 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001589}
1590
1591/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001592SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001593 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001594 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001595
1596 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001597 Ty = getEffectiveSCEVType(Ty);
1598 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001599 return getMinusSCEV(AllOnes, V);
1600}
1601
1602/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1603///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001604SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001605 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001606 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001607 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001608}
1609
1610/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1611/// input value to the specified type. If the type must be extended, it is zero
1612/// extended.
1613SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001614ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001615 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001616 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001617 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1618 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001619 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001620 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001621 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001622 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001623 return getTruncateExpr(V, Ty);
1624 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001625}
1626
1627/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1628/// input value to the specified type. If the type must be extended, it is sign
1629/// extended.
1630SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001631ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001632 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001633 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001634 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1635 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001636 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001637 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001638 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001639 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001640 return getTruncateExpr(V, Ty);
1641 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001642}
1643
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001644/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1645/// the specified instruction and replaces any references to the symbolic value
1646/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001647void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1649 const SCEVHandle &NewVal) {
1650 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1651 if (SI == Scalars.end()) return;
1652
1653 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001654 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001655 if (NV == SI->second) return; // No change.
1656
1657 SI->second = NV; // Update the scalars map!
1658
1659 // Any instruction values that use this instruction might also need to be
1660 // updated!
1661 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1662 UI != E; ++UI)
1663 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1664}
1665
1666/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1667/// a loop header, making it a potential recurrence, or it doesn't.
1668///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001669SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001671 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001672 if (L->getHeader() == PN->getParent()) {
1673 // If it lives in the loop header, it has two incoming values, one
1674 // from outside the loop, and one from inside.
1675 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1676 unsigned BackEdge = IncomingEdge^1;
1677
1678 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001679 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 assert(Scalars.find(PN) == Scalars.end() &&
1681 "PHI node already processed?");
1682 Scalars.insert(std::make_pair(PN, SymbolicName));
1683
1684 // Using this symbolic name for the PHI, analyze the value coming around
1685 // the back-edge.
1686 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1687
1688 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1689 // has a special value for the first iteration of the loop.
1690
1691 // If the value coming around the backedge is an add with the symbolic
1692 // value we just inserted, then we found a simple induction variable!
1693 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1694 // If there is a single occurrence of the symbolic value, replace it
1695 // with a recurrence.
1696 unsigned FoundIndex = Add->getNumOperands();
1697 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1698 if (Add->getOperand(i) == SymbolicName)
1699 if (FoundIndex == e) {
1700 FoundIndex = i;
1701 break;
1702 }
1703
1704 if (FoundIndex != Add->getNumOperands()) {
1705 // Create an add with everything but the specified operand.
1706 std::vector<SCEVHandle> Ops;
1707 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1708 if (i != FoundIndex)
1709 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001710 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001711
1712 // This is not a valid addrec if the step amount is varying each
1713 // loop iteration, but is not itself an addrec in this loop.
1714 if (Accum->isLoopInvariant(L) ||
1715 (isa<SCEVAddRecExpr>(Accum) &&
1716 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1717 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001718 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719
1720 // Okay, for the entire analysis of this edge we assumed the PHI
1721 // to be symbolic. We now need to go back and update all of the
1722 // entries for the scalars that use the PHI (except for the PHI
1723 // itself) to use the new analyzed value instead of the "symbolic"
1724 // value.
1725 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1726 return PHISCEV;
1727 }
1728 }
1729 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1730 // Otherwise, this could be a loop like this:
1731 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1732 // In this case, j = {1,+,1} and BEValue is j.
1733 // Because the other in-value of i (0) fits the evolution of BEValue
1734 // i really is an addrec evolution.
1735 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1736 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1737
1738 // If StartVal = j.start - j.stride, we can use StartVal as the
1739 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001740 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001741 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001742 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001743 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744
1745 // Okay, for the entire analysis of this edge we assumed the PHI
1746 // to be symbolic. We now need to go back and update all of the
1747 // entries for the scalars that use the PHI (except for the PHI
1748 // itself) to use the new analyzed value instead of the "symbolic"
1749 // value.
1750 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1751 return PHISCEV;
1752 }
1753 }
1754 }
1755
1756 return SymbolicName;
1757 }
1758
1759 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001760 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761}
1762
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001763/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1764/// guaranteed to end in (at every loop iteration). It is, at the same time,
1765/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1766/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001767static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001768 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001769 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001770
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001771 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001772 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1773 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001774
1775 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001776 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1777 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1778 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001779 }
1780
1781 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001782 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1783 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1784 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001785 }
1786
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001787 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001788 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001789 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001790 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001791 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001792 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793 }
1794
1795 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001796 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001797 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1798 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001799 for (unsigned i = 1, e = M->getNumOperands();
1800 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001801 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001802 BitWidth);
1803 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001804 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001805
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001806 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001807 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001808 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001809 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001810 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001811 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001813
Nick Lewycky711640a2007-11-25 22:41:31 +00001814 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1815 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001816 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001817 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001818 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001819 return MinOpRes;
1820 }
1821
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001822 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1823 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001824 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001825 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001826 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001827 return MinOpRes;
1828 }
1829
Nick Lewycky35b56022009-01-13 09:18:58 +00001830 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001831 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001832}
1833
1834/// createSCEV - We know that there is no SCEV for the specified value.
1835/// Analyze the expression.
1836///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001837SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001838 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001839 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001840
Dan Gohman3996f472008-06-22 19:56:46 +00001841 unsigned Opcode = Instruction::UserOp1;
1842 if (Instruction *I = dyn_cast<Instruction>(V))
1843 Opcode = I->getOpcode();
1844 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1845 Opcode = CE->getOpcode();
1846 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001847 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848
Dan Gohman3996f472008-06-22 19:56:46 +00001849 User *U = cast<User>(V);
1850 switch (Opcode) {
1851 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001852 return getAddExpr(getSCEV(U->getOperand(0)),
1853 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001854 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001855 return getMulExpr(getSCEV(U->getOperand(0)),
1856 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001857 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001858 return getUDivExpr(getSCEV(U->getOperand(0)),
1859 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001860 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001861 return getMinusSCEV(getSCEV(U->getOperand(0)),
1862 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001863 case Instruction::And:
1864 // For an expression like x&255 that merely masks off the high bits,
1865 // use zext(trunc(x)) as the SCEV expression.
1866 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001867 if (CI->isNullValue())
1868 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00001869 if (CI->isAllOnesValue())
1870 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001871 const APInt &A = CI->getValue();
1872 unsigned Ones = A.countTrailingOnes();
1873 if (APIntOps::isMask(Ones, A))
1874 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001875 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1876 IntegerType::get(Ones)),
1877 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001878 }
1879 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001880 case Instruction::Or:
1881 // If the RHS of the Or is a constant, we may have something like:
1882 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1883 // optimizations will transparently handle this case.
1884 //
1885 // In order for this transformation to be safe, the LHS must be of the
1886 // form X*(2^n) and the Or constant must be less than 2^n.
1887 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1888 SCEVHandle LHS = getSCEV(U->getOperand(0));
1889 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001890 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001891 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001892 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 }
Dan Gohman3996f472008-06-22 19:56:46 +00001894 break;
1895 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001896 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001897 // If the RHS of the xor is a signbit, then this is just an add.
1898 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001899 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001900 return getAddExpr(getSCEV(U->getOperand(0)),
1901 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001902
1903 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001904 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001905 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001906 }
1907 break;
1908
1909 case Instruction::Shl:
1910 // Turn shift left of a constant amount into a multiply.
1911 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1912 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1913 Constant *X = ConstantInt::get(
1914 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001915 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001916 }
1917 break;
1918
Nick Lewycky7fd27892008-07-07 06:15:49 +00001919 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001920 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001921 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1922 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1923 Constant *X = ConstantInt::get(
1924 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001925 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001926 }
1927 break;
1928
Dan Gohman53bf64a2009-04-21 02:26:00 +00001929 case Instruction::AShr:
1930 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1931 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1932 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1933 if (L->getOpcode() == Instruction::Shl &&
1934 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001935 unsigned BitWidth = getTypeSizeInBits(U->getType());
1936 uint64_t Amt = BitWidth - CI->getZExtValue();
1937 if (Amt == BitWidth)
1938 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1939 if (Amt > BitWidth)
1940 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001941 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001942 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001943 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001944 U->getType());
1945 }
1946 break;
1947
Dan Gohman3996f472008-06-22 19:56:46 +00001948 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001949 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001950
1951 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001952 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001953
1954 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001955 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001956
1957 case Instruction::BitCast:
1958 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001959 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001960 return getSCEV(U->getOperand(0));
1961 break;
1962
Dan Gohman01c2ee72009-04-16 03:18:22 +00001963 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001964 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001965 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001966 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001967
1968 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001969 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001970 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1971 U->getType());
1972
1973 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001974 if (!TD) break; // Without TD we can't analyze pointers.
1975 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001976 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001977 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001978 gep_type_iterator GTI = gep_type_begin(U);
1979 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1980 E = U->op_end();
1981 I != E; ++I) {
1982 Value *Index = *I;
1983 // Compute the (potentially symbolic) offset in bytes for this index.
1984 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1985 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001986 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001987 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1988 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001989 TotalOffset = getAddExpr(TotalOffset,
1990 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001991 } else {
1992 // For an array, add the element offset, explicitly scaled.
1993 SCEVHandle LocalOffset = getSCEV(Index);
1994 if (!isa<PointerType>(LocalOffset->getType()))
1995 // Getelementptr indicies are signed.
1996 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1997 IntPtrTy);
1998 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001999 getMulExpr(LocalOffset,
2000 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2001 IntPtrTy));
2002 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002003 }
2004 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002005 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002006 }
2007
Dan Gohman3996f472008-06-22 19:56:46 +00002008 case Instruction::PHI:
2009 return createNodeForPHI(cast<PHINode>(U));
2010
2011 case Instruction::Select:
2012 // This could be a smax or umax that was lowered earlier.
2013 // Try to recover it.
2014 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2015 Value *LHS = ICI->getOperand(0);
2016 Value *RHS = ICI->getOperand(1);
2017 switch (ICI->getPredicate()) {
2018 case ICmpInst::ICMP_SLT:
2019 case ICmpInst::ICMP_SLE:
2020 std::swap(LHS, RHS);
2021 // fall through
2022 case ICmpInst::ICMP_SGT:
2023 case ICmpInst::ICMP_SGE:
2024 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002025 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002026 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002027 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002028 return getNotSCEV(getSMaxExpr(
2029 getNotSCEV(getSCEV(LHS)),
2030 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002031 break;
2032 case ICmpInst::ICMP_ULT:
2033 case ICmpInst::ICMP_ULE:
2034 std::swap(LHS, RHS);
2035 // fall through
2036 case ICmpInst::ICMP_UGT:
2037 case ICmpInst::ICMP_UGE:
2038 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002039 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002040 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2041 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002042 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2043 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002044 break;
2045 default:
2046 break;
2047 }
2048 }
2049
2050 default: // We cannot analyze this expression.
2051 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002052 }
2053
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002054 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002055}
2056
2057
2058
2059//===----------------------------------------------------------------------===//
2060// Iteration Count Computation Code
2061//
2062
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002063/// getBackedgeTakenCount - If the specified loop has a predictable
2064/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2065/// object. The backedge-taken count is the number of times the loop header
2066/// will be branched to from within the loop. This is one less than the
2067/// trip count of the loop, since it doesn't count the first iteration,
2068/// when the header is branched to from outside the loop.
2069///
2070/// Note that it is not valid to call this method on a loop without a
2071/// loop-invariant backedge-taken count (see
2072/// hasLoopInvariantBackedgeTakenCount).
2073///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002074SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002075 return getBackedgeTakenInfo(L).Exact;
2076}
2077
2078/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2079/// return the least SCEV value that is known never to be less than the
2080/// actual backedge taken count.
2081SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2082 return getBackedgeTakenInfo(L).Max;
2083}
2084
2085const ScalarEvolution::BackedgeTakenInfo &
2086ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002087 // Initially insert a CouldNotCompute for this loop. If the insertion
2088 // succeeds, procede to actually compute a backedge-taken count and
2089 // update the value. The temporary CouldNotCompute value tells SCEV
2090 // code elsewhere that it shouldn't attempt to request a new
2091 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002092 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002093 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2094 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002095 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2096 if (ItCount.Exact != UnknownValue) {
2097 assert(ItCount.Exact->isLoopInvariant(L) &&
2098 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 "Computed trip count isn't loop invariant for loop!");
2100 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002101
Dan Gohmana9dba962009-04-27 20:16:15 +00002102 // Update the value in the map.
2103 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 } else if (isa<PHINode>(L->getHeader()->begin())) {
2105 // Only count loops that have phi nodes as not being computable.
2106 ++NumTripCountsNotComputed;
2107 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002108
2109 // Now that we know more about the trip count for this loop, forget any
2110 // existing SCEV values for PHI nodes in this loop since they are only
2111 // conservative estimates made without the benefit
2112 // of trip count information.
2113 if (ItCount.hasAnyInfo())
2114 for (BasicBlock::iterator I = L->getHeader()->begin();
2115 PHINode *PN = dyn_cast<PHINode>(I); ++I)
2116 deleteValueFromRecords(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002117 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002118 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119}
2120
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002121/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002122/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002123/// ScalarEvolution's ability to compute a trip count, or if the loop
2124/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002125void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002126 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002127}
2128
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002129/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2130/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002131ScalarEvolution::BackedgeTakenInfo
2132ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002133 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002134 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002135 L->getExitBlocks(ExitBlocks);
2136 if (ExitBlocks.size() != 1) return UnknownValue;
2137
2138 // Okay, there is one exit block. Try to find the condition that causes the
2139 // loop to be exited.
2140 BasicBlock *ExitBlock = ExitBlocks[0];
2141
2142 BasicBlock *ExitingBlock = 0;
2143 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2144 PI != E; ++PI)
2145 if (L->contains(*PI)) {
2146 if (ExitingBlock == 0)
2147 ExitingBlock = *PI;
2148 else
2149 return UnknownValue; // More than one block exiting!
2150 }
2151 assert(ExitingBlock && "No exits from loop, something is broken!");
2152
2153 // Okay, we've computed the exiting block. See what condition causes us to
2154 // exit.
2155 //
2156 // FIXME: we should be able to handle switch instructions (with a single exit)
2157 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2158 if (ExitBr == 0) return UnknownValue;
2159 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2160
2161 // At this point, we know we have a conditional branch that determines whether
2162 // the loop is exited. However, we don't know if the branch is executed each
2163 // time through the loop. If not, then the execution count of the branch will
2164 // not be equal to the trip count of the loop.
2165 //
2166 // Currently we check for this by checking to see if the Exit branch goes to
2167 // the loop header. If so, we know it will always execute the same number of
2168 // times as the loop. We also handle the case where the exit block *is* the
2169 // loop header. This is common for un-rotated loops. More extensive analysis
2170 // could be done to handle more cases here.
2171 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2172 ExitBr->getSuccessor(1) != L->getHeader() &&
2173 ExitBr->getParent() != L->getHeader())
2174 return UnknownValue;
2175
2176 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2177
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002178 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002179 // Note that ICmpInst deals with pointer comparisons too so we must check
2180 // the type of the operand.
2181 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002182 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 ExitBr->getSuccessor(0) == ExitBlock);
2184
2185 // If the condition was exit on true, convert the condition to exit on false
2186 ICmpInst::Predicate Cond;
2187 if (ExitBr->getSuccessor(1) == ExitBlock)
2188 Cond = ExitCond->getPredicate();
2189 else
2190 Cond = ExitCond->getInversePredicate();
2191
2192 // Handle common loops like: for (X = "string"; *X; ++X)
2193 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2194 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2195 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002196 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002197 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2198 }
2199
2200 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2201 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2202
2203 // Try to evaluate any dependencies out of the loop.
2204 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2205 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2206 Tmp = getSCEVAtScope(RHS, L);
2207 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2208
2209 // At this point, we would like to compute how many iterations of the
2210 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002211 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2212 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002213 std::swap(LHS, RHS);
2214 Cond = ICmpInst::getSwappedPredicate(Cond);
2215 }
2216
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002217 // If we have a comparison of a chrec against a constant, try to use value
2218 // ranges to answer this query.
2219 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2220 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2221 if (AddRec->getLoop() == L) {
2222 // Form the comparison range using the constant of the correct type so
2223 // that the ConstantRange class knows to do a signed or unsigned
2224 // comparison.
2225 ConstantInt *CompVal = RHSC->getValue();
2226 const Type *RealTy = ExitCond->getOperand(0)->getType();
2227 CompVal = dyn_cast<ConstantInt>(
2228 ConstantExpr::getBitCast(CompVal, RealTy));
2229 if (CompVal) {
2230 // Form the constant range.
2231 ConstantRange CompRange(
2232 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2233
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002234 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2236 }
2237 }
2238
2239 switch (Cond) {
2240 case ICmpInst::ICMP_NE: { // while (X != Y)
2241 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002242 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002243 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2244 break;
2245 }
2246 case ICmpInst::ICMP_EQ: {
2247 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002248 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002249 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2250 break;
2251 }
2252 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002253 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2254 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255 break;
2256 }
2257 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002258 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2259 getNotSCEV(RHS), L, true);
2260 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002261 break;
2262 }
2263 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002264 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2265 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002266 break;
2267 }
2268 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002269 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2270 getNotSCEV(RHS), L, false);
2271 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272 break;
2273 }
2274 default:
2275#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002276 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002278 errs() << "[unsigned] ";
2279 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002280 << Instruction::getOpcodeName(Instruction::ICmp)
2281 << " " << *RHS << "\n";
2282#endif
2283 break;
2284 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002285 return
2286 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2287 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002288}
2289
2290static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002291EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2292 ScalarEvolution &SE) {
2293 SCEVHandle InVal = SE.getConstant(C);
2294 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295 assert(isa<SCEVConstant>(Val) &&
2296 "Evaluation of SCEV at constant didn't fold correctly?");
2297 return cast<SCEVConstant>(Val)->getValue();
2298}
2299
2300/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2301/// and a GEP expression (missing the pointer index) indexing into it, return
2302/// the addressed element of the initializer or null if the index expression is
2303/// invalid.
2304static Constant *
2305GetAddressedElementFromGlobal(GlobalVariable *GV,
2306 const std::vector<ConstantInt*> &Indices) {
2307 Constant *Init = GV->getInitializer();
2308 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2309 uint64_t Idx = Indices[i]->getZExtValue();
2310 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2311 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2312 Init = cast<Constant>(CS->getOperand(Idx));
2313 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2314 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2315 Init = cast<Constant>(CA->getOperand(Idx));
2316 } else if (isa<ConstantAggregateZero>(Init)) {
2317 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2318 assert(Idx < STy->getNumElements() && "Bad struct index!");
2319 Init = Constant::getNullValue(STy->getElementType(Idx));
2320 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2321 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2322 Init = Constant::getNullValue(ATy->getElementType());
2323 } else {
2324 assert(0 && "Unknown constant aggregate type!");
2325 }
2326 return 0;
2327 } else {
2328 return 0; // Unknown initializer type
2329 }
2330 }
2331 return Init;
2332}
2333
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002334/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2335/// 'icmp op load X, cst', try to see if we can compute the backedge
2336/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002337SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002338ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2339 const Loop *L,
2340 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341 if (LI->isVolatile()) return UnknownValue;
2342
2343 // Check to see if the loaded pointer is a getelementptr of a global.
2344 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2345 if (!GEP) return UnknownValue;
2346
2347 // Make sure that it is really a constant global we are gepping, with an
2348 // initializer, and make sure the first IDX is really 0.
2349 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2350 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2351 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2352 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2353 return UnknownValue;
2354
2355 // Okay, we allow one non-constant index into the GEP instruction.
2356 Value *VarIdx = 0;
2357 std::vector<ConstantInt*> Indexes;
2358 unsigned VarIdxNum = 0;
2359 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2360 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2361 Indexes.push_back(CI);
2362 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2363 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2364 VarIdx = GEP->getOperand(i);
2365 VarIdxNum = i-2;
2366 Indexes.push_back(0);
2367 }
2368
2369 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2370 // Check to see if X is a loop variant variable value now.
2371 SCEVHandle Idx = getSCEV(VarIdx);
2372 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2373 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2374
2375 // We can only recognize very limited forms of loop index expressions, in
2376 // particular, only affine AddRec's like {C1,+,C2}.
2377 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2378 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2379 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2380 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2381 return UnknownValue;
2382
2383 unsigned MaxSteps = MaxBruteForceIterations;
2384 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2385 ConstantInt *ItCst =
2386 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002387 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002388
2389 // Form the GEP offset.
2390 Indexes[VarIdxNum] = Val;
2391
2392 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2393 if (Result == 0) break; // Cannot compute!
2394
2395 // Evaluate the condition for this iteration.
2396 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2397 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2398 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2399#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002400 errs() << "\n***\n*** Computed loop count " << *ItCst
2401 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2402 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002403#endif
2404 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002405 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002406 }
2407 }
2408 return UnknownValue;
2409}
2410
2411
2412/// CanConstantFold - Return true if we can constant fold an instruction of the
2413/// specified type, assuming that all operands were constants.
2414static bool CanConstantFold(const Instruction *I) {
2415 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2416 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2417 return true;
2418
2419 if (const CallInst *CI = dyn_cast<CallInst>(I))
2420 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002421 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002422 return false;
2423}
2424
2425/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2426/// in the loop that V is derived from. We allow arbitrary operations along the
2427/// way, but the operands of an operation must either be constants or a value
2428/// derived from a constant PHI. If this expression does not fit with these
2429/// constraints, return null.
2430static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2431 // If this is not an instruction, or if this is an instruction outside of the
2432 // loop, it can't be derived from a loop PHI.
2433 Instruction *I = dyn_cast<Instruction>(V);
2434 if (I == 0 || !L->contains(I->getParent())) return 0;
2435
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002436 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002437 if (L->getHeader() == I->getParent())
2438 return PN;
2439 else
2440 // We don't currently keep track of the control flow needed to evaluate
2441 // PHIs, so we cannot handle PHIs inside of loops.
2442 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002443 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002444
2445 // If we won't be able to constant fold this expression even if the operands
2446 // are constants, return early.
2447 if (!CanConstantFold(I)) return 0;
2448
2449 // Otherwise, we can evaluate this instruction if all of its operands are
2450 // constant or derived from a PHI node themselves.
2451 PHINode *PHI = 0;
2452 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2453 if (!(isa<Constant>(I->getOperand(Op)) ||
2454 isa<GlobalValue>(I->getOperand(Op)))) {
2455 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2456 if (P == 0) return 0; // Not evolving from PHI
2457 if (PHI == 0)
2458 PHI = P;
2459 else if (PHI != P)
2460 return 0; // Evolving from multiple different PHIs.
2461 }
2462
2463 // This is a expression evolving from a constant PHI!
2464 return PHI;
2465}
2466
2467/// EvaluateExpression - Given an expression that passes the
2468/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2469/// in the loop has the value PHIVal. If we can't fold this expression for some
2470/// reason, return null.
2471static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2472 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002474 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002475 Instruction *I = cast<Instruction>(V);
2476
2477 std::vector<Constant*> Operands;
2478 Operands.resize(I->getNumOperands());
2479
2480 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2481 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2482 if (Operands[i] == 0) return 0;
2483 }
2484
Chris Lattnerd6e56912007-12-10 22:53:04 +00002485 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2486 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2487 &Operands[0], Operands.size());
2488 else
2489 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2490 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491}
2492
2493/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2494/// in the header of its containing loop, we know the loop executes a
2495/// constant number of times, and the PHI node is just a recurrence
2496/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002497Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002498getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499 std::map<PHINode*, Constant*>::iterator I =
2500 ConstantEvolutionLoopExitValue.find(PN);
2501 if (I != ConstantEvolutionLoopExitValue.end())
2502 return I->second;
2503
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002504 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2506
2507 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2508
2509 // Since the loop is canonicalized, the PHI node must have two entries. One
2510 // entry must be a constant (coming in from outside of the loop), and the
2511 // second must be derived from the same PHI.
2512 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2513 Constant *StartCST =
2514 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2515 if (StartCST == 0)
2516 return RetVal = 0; // Must be a constant.
2517
2518 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2519 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2520 if (PN2 != PN)
2521 return RetVal = 0; // Not derived from same PHI.
2522
2523 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002524 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2526
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002527 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002528 unsigned IterationNum = 0;
2529 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2530 if (IterationNum == NumIterations)
2531 return RetVal = PHIVal; // Got exit value!
2532
2533 // Compute the value of the PHI node for the next iteration.
2534 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2535 if (NextPHI == PHIVal)
2536 return RetVal = NextPHI; // Stopped evolving!
2537 if (NextPHI == 0)
2538 return 0; // Couldn't evaluate!
2539 PHIVal = NextPHI;
2540 }
2541}
2542
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002543/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002544/// constant number of times (the condition evolves only from constants),
2545/// try to evaluate a few iterations of the loop until we get the exit
2546/// condition gets a value of ExitWhen (true or false). If we cannot
2547/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002548SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002549ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2551 if (PN == 0) return UnknownValue;
2552
2553 // Since the loop is canonicalized, the PHI node must have two entries. One
2554 // entry must be a constant (coming in from outside of the loop), and the
2555 // second must be derived from the same PHI.
2556 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2557 Constant *StartCST =
2558 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2559 if (StartCST == 0) return UnknownValue; // Must be a constant.
2560
2561 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2562 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2563 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2564
2565 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2566 // the loop symbolically to determine when the condition gets a value of
2567 // "ExitWhen".
2568 unsigned IterationNum = 0;
2569 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2570 for (Constant *PHIVal = StartCST;
2571 IterationNum != MaxIterations; ++IterationNum) {
2572 ConstantInt *CondVal =
2573 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2574
2575 // Couldn't symbolically evaluate.
2576 if (!CondVal) return UnknownValue;
2577
2578 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2579 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2580 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002581 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002582 }
2583
2584 // Compute the value of the PHI node for the next iteration.
2585 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2586 if (NextPHI == 0 || NextPHI == PHIVal)
2587 return UnknownValue; // Couldn't evaluate or not making progress...
2588 PHIVal = NextPHI;
2589 }
2590
2591 // Too many iterations were needed to evaluate.
2592 return UnknownValue;
2593}
2594
2595/// getSCEVAtScope - Compute the value of the specified expression within the
2596/// indicated loop (which may be null to indicate in no loop). If the
2597/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002598SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002599 // FIXME: this should be turned into a virtual method on SCEV!
2600
2601 if (isa<SCEVConstant>(V)) return V;
2602
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002603 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002604 // exit value from the loop without using SCEVs.
2605 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2606 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002607 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002608 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2609 if (PHINode *PN = dyn_cast<PHINode>(I))
2610 if (PN->getParent() == LI->getHeader()) {
2611 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002612 // to see if the loop that contains it has a known backedge-taken
2613 // count. If so, we may be able to force computation of the exit
2614 // value.
2615 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2616 if (SCEVConstant *BTCC =
2617 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002618 // Okay, we know how many times the containing loop executes. If
2619 // this is a constant evolving PHI node, get the final value at
2620 // the specified iteration number.
2621 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002622 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002623 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002624 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002625 }
2626 }
2627
2628 // Okay, this is an expression that we cannot symbolically evaluate
2629 // into a SCEV. Check to see if it's possible to symbolically evaluate
2630 // the arguments into constants, and if so, try to constant propagate the
2631 // result. This is particularly useful for computing loop exit values.
2632 if (CanConstantFold(I)) {
2633 std::vector<Constant*> Operands;
2634 Operands.reserve(I->getNumOperands());
2635 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2636 Value *Op = I->getOperand(i);
2637 if (Constant *C = dyn_cast<Constant>(Op)) {
2638 Operands.push_back(C);
2639 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002640 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002641 // non-integer and non-pointer, don't even try to analyze them
2642 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002643 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002644 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002645
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002646 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman5e4eb762009-04-30 16:40:30 +00002647 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
2648 Constant *C = SC->getValue();
2649 if (C->getType() != Op->getType())
2650 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2651 Op->getType(),
2652 false),
2653 C, Op->getType());
2654 Operands.push_back(C);
2655 } else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2656 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2657 if (C->getType() != Op->getType())
2658 C =
2659 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2660 Op->getType(),
2661 false),
2662 C, Op->getType());
2663 Operands.push_back(C);
2664 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002665 return V;
2666 } else {
2667 return V;
2668 }
2669 }
2670 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002671
2672 Constant *C;
2673 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2674 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2675 &Operands[0], Operands.size());
2676 else
2677 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2678 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002679 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002680 }
2681 }
2682
2683 // This is some other type of SCEVUnknown, just return it.
2684 return V;
2685 }
2686
2687 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2688 // Avoid performing the look-up in the common case where the specified
2689 // expression has no loop-variant portions.
2690 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2691 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2692 if (OpAtScope != Comm->getOperand(i)) {
2693 if (OpAtScope == UnknownValue) return UnknownValue;
2694 // Okay, at least one of these operands is loop variant but might be
2695 // foldable. Build a new instance of the folded commutative expression.
2696 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2697 NewOps.push_back(OpAtScope);
2698
2699 for (++i; i != e; ++i) {
2700 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2701 if (OpAtScope == UnknownValue) return UnknownValue;
2702 NewOps.push_back(OpAtScope);
2703 }
2704 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002705 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002706 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002707 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002708 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002709 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002710 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002711 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002712 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713 }
2714 }
2715 // If we got here, all operands are loop invariant.
2716 return Comm;
2717 }
2718
Nick Lewycky35b56022009-01-13 09:18:58 +00002719 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2720 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002721 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002722 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002724 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2725 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002726 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002727 }
2728
2729 // If this is a loop recurrence for a loop that does not contain L, then we
2730 // are dealing with the final value computed by the loop.
2731 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2732 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2733 // To evaluate this recurrence, we need to know how many times the AddRec
2734 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002735 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2736 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737
Eli Friedman7489ec92008-08-04 23:49:06 +00002738 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002739 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002740 }
2741 return UnknownValue;
2742 }
2743
Dan Gohman78d63c82009-04-29 22:29:01 +00002744 if (SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
2745 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2746 if (Op == UnknownValue) return Op;
2747 if (Op == Cast->getOperand())
2748 return Cast; // must be loop invariant
2749 return getZeroExtendExpr(Op, Cast->getType());
2750 }
2751
2752 if (SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
2753 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2754 if (Op == UnknownValue) return Op;
2755 if (Op == Cast->getOperand())
2756 return Cast; // must be loop invariant
2757 return getSignExtendExpr(Op, Cast->getType());
2758 }
2759
2760 if (SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
2761 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2762 if (Op == UnknownValue) return Op;
2763 if (Op == Cast->getOperand())
2764 return Cast; // must be loop invariant
2765 return getTruncateExpr(Op, Cast->getType());
2766 }
2767
2768 assert(0 && "Unknown SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002769}
2770
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002771/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2772/// at the specified scope in the program. The L value specifies a loop
2773/// nest to evaluate the expression at, where null is the top-level or a
2774/// specified loop is immediately inside of the loop.
2775///
2776/// This method can be used to compute the exit value for a variable defined
2777/// in a loop by querying what the value will hold in the parent loop.
2778///
2779/// If this value is not computable at this scope, a SCEVCouldNotCompute
2780/// object is returned.
2781SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2782 return getSCEVAtScope(getSCEV(V), L);
2783}
2784
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002785/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2786/// following equation:
2787///
2788/// A * X = B (mod N)
2789///
2790/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2791/// A and B isn't important.
2792///
2793/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2794static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2795 ScalarEvolution &SE) {
2796 uint32_t BW = A.getBitWidth();
2797 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2798 assert(A != 0 && "A must be non-zero.");
2799
2800 // 1. D = gcd(A, N)
2801 //
2802 // The gcd of A and N may have only one prime factor: 2. The number of
2803 // trailing zeros in A is its multiplicity
2804 uint32_t Mult2 = A.countTrailingZeros();
2805 // D = 2^Mult2
2806
2807 // 2. Check if B is divisible by D.
2808 //
2809 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2810 // is not less than multiplicity of this prime factor for D.
2811 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002812 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002813
2814 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2815 // modulo (N / D).
2816 //
2817 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2818 // bit width during computations.
2819 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2820 APInt Mod(BW + 1, 0);
2821 Mod.set(BW - Mult2); // Mod = N / D
2822 APInt I = AD.multiplicativeInverse(Mod);
2823
2824 // 4. Compute the minimum unsigned root of the equation:
2825 // I * (B / D) mod (N / D)
2826 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2827
2828 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2829 // bits.
2830 return SE.getConstant(Result.trunc(BW));
2831}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002832
2833/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2834/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2835/// might be the same) or two SCEVCouldNotCompute objects.
2836///
2837static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002838SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002839 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2840 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2841 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2842 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2843
2844 // We currently can only solve this if the coefficients are constants.
2845 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002846 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002847 return std::make_pair(CNC, CNC);
2848 }
2849
2850 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2851 const APInt &L = LC->getValue()->getValue();
2852 const APInt &M = MC->getValue()->getValue();
2853 const APInt &N = NC->getValue()->getValue();
2854 APInt Two(BitWidth, 2);
2855 APInt Four(BitWidth, 4);
2856
2857 {
2858 using namespace APIntOps;
2859 const APInt& C = L;
2860 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2861 // The B coefficient is M-N/2
2862 APInt B(M);
2863 B -= sdiv(N,Two);
2864
2865 // The A coefficient is N/2
2866 APInt A(N.sdiv(Two));
2867
2868 // Compute the B^2-4ac term.
2869 APInt SqrtTerm(B);
2870 SqrtTerm *= B;
2871 SqrtTerm -= Four * (A * C);
2872
2873 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2874 // integer value or else APInt::sqrt() will assert.
2875 APInt SqrtVal(SqrtTerm.sqrt());
2876
2877 // Compute the two solutions for the quadratic formula.
2878 // The divisions must be performed as signed divisions.
2879 APInt NegB(-B);
2880 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002881 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002882 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002883 return std::make_pair(CNC, CNC);
2884 }
2885
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2887 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2888
Dan Gohman89f85052007-10-22 18:31:58 +00002889 return std::make_pair(SE.getConstant(Solution1),
2890 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891 } // end APIntOps namespace
2892}
2893
2894/// HowFarToZero - Return the number of times a backedge comparing the specified
2895/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002896SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002897 // If the value is a constant
2898 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2899 // If the value is already zero, the branch will execute zero times.
2900 if (C->getValue()->isZero()) return C;
2901 return UnknownValue; // Otherwise it will loop infinitely.
2902 }
2903
2904 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2905 if (!AddRec || AddRec->getLoop() != L)
2906 return UnknownValue;
2907
2908 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002909 // If this is an affine expression, the execution count of this branch is
2910 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002912 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002914 // equivalent to:
2915 //
2916 // Step*N = -Start (mod 2^BW)
2917 //
2918 // where BW is the common bit width of Start and Step.
2919
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002920 // Get the initial value for the loop.
2921 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2922 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002923
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002924 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002925
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002926 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002927 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002928
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002929 // First, handle unitary steps.
2930 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002931 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002932 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2933 return Start; // N = Start (as unsigned)
2934
2935 // Then, try to solve the above equation provided that Start is constant.
2936 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2937 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002938 -StartC->getValue()->getValue(),
2939 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940 }
2941 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2942 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2943 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002944 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2945 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002946 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2947 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2948 if (R1) {
2949#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002950 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2951 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952#endif
2953 // Pick the smallest positive root value.
2954 if (ConstantInt *CB =
2955 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2956 R1->getValue(), R2->getValue()))) {
2957 if (CB->getZExtValue() == false)
2958 std::swap(R1, R2); // R1 is the minimum root now.
2959
2960 // We can only use this value if the chrec ends up with an exact zero
2961 // value at this index. When solving for "X*X != 5", for example, we
2962 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002963 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002964 if (Val->isZero())
2965 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 }
2967 }
2968 }
2969
2970 return UnknownValue;
2971}
2972
2973/// HowFarToNonZero - Return the number of times a backedge checking the
2974/// specified value for nonzero will execute. If not computable, return
2975/// UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002976SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002977 // Loops that look like: while (X == 0) are very strange indeed. We don't
2978 // handle them yet except for the trivial case. This could be expanded in the
2979 // future as needed.
2980
2981 // If the value is a constant, check to see if it is known to be non-zero
2982 // already. If so, the backedge will execute zero times.
2983 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002984 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002985 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 return UnknownValue; // Otherwise it will loop infinitely.
2987 }
2988
2989 // We could implement others, but I really doubt anyone writes loops like
2990 // this, and if they did, they would already be constant folded.
2991 return UnknownValue;
2992}
2993
Dan Gohman1cddf972008-09-15 22:18:04 +00002994/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2995/// (which may not be an immediate predecessor) which has exactly one
2996/// successor from which BB is reachable, or null if no such block is
2997/// found.
2998///
2999BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003000ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003001 // If the block has a unique predecessor, then there is no path from the
3002 // predecessor to the block that does not go through the direct edge
3003 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003004 if (BasicBlock *Pred = BB->getSinglePredecessor())
3005 return Pred;
3006
3007 // A loop's header is defined to be a block that dominates the loop.
3008 // If the loop has a preheader, it must be a block that has exactly
3009 // one successor that can reach BB. This is slightly more strict
3010 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003011 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00003012 return L->getLoopPreheader();
3013
3014 return 0;
3015}
3016
Dan Gohmancacd2012009-02-12 22:19:27 +00003017/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003018/// a conditional between LHS and RHS. This is used to help avoid max
3019/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003020bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003021 ICmpInst::Predicate Pred,
3022 SCEV *LHS, SCEV *RHS) {
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003023 BasicBlock *Preheader = L->getLoopPreheader();
3024 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003025
Dan Gohmanab678fb2008-08-12 20:17:31 +00003026 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003027 // there are predecessors that can be found that have unique successors
3028 // leading to the original header.
3029 for (; Preheader;
3030 PreheaderDest = Preheader,
3031 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003032
3033 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003034 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003035 if (!LoopEntryPredicate ||
3036 LoopEntryPredicate->isUnconditional())
3037 continue;
3038
3039 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3040 if (!ICI) continue;
3041
3042 // Now that we found a conditional branch that dominates the loop, check to
3043 // see if it is the comparison we are looking for.
3044 Value *PreCondLHS = ICI->getOperand(0);
3045 Value *PreCondRHS = ICI->getOperand(1);
3046 ICmpInst::Predicate Cond;
3047 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3048 Cond = ICI->getPredicate();
3049 else
3050 Cond = ICI->getInversePredicate();
3051
Dan Gohmancacd2012009-02-12 22:19:27 +00003052 if (Cond == Pred)
3053 ; // An exact match.
3054 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3055 ; // The actual condition is beyond sufficient.
3056 else
3057 // Check a few special cases.
3058 switch (Cond) {
3059 case ICmpInst::ICMP_UGT:
3060 if (Pred == ICmpInst::ICMP_ULT) {
3061 std::swap(PreCondLHS, PreCondRHS);
3062 Cond = ICmpInst::ICMP_ULT;
3063 break;
3064 }
3065 continue;
3066 case ICmpInst::ICMP_SGT:
3067 if (Pred == ICmpInst::ICMP_SLT) {
3068 std::swap(PreCondLHS, PreCondRHS);
3069 Cond = ICmpInst::ICMP_SLT;
3070 break;
3071 }
3072 continue;
3073 case ICmpInst::ICMP_NE:
3074 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3075 // so check for this case by checking if the NE is comparing against
3076 // a minimum or maximum constant.
3077 if (!ICmpInst::isTrueWhenEqual(Pred))
3078 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3079 const APInt &A = CI->getValue();
3080 switch (Pred) {
3081 case ICmpInst::ICMP_SLT:
3082 if (A.isMaxSignedValue()) break;
3083 continue;
3084 case ICmpInst::ICMP_SGT:
3085 if (A.isMinSignedValue()) break;
3086 continue;
3087 case ICmpInst::ICMP_ULT:
3088 if (A.isMaxValue()) break;
3089 continue;
3090 case ICmpInst::ICMP_UGT:
3091 if (A.isMinValue()) break;
3092 continue;
3093 default:
3094 continue;
3095 }
3096 Cond = ICmpInst::ICMP_NE;
3097 // NE is symmetric but the original comparison may not be. Swap
3098 // the operands if necessary so that they match below.
3099 if (isa<SCEVConstant>(LHS))
3100 std::swap(PreCondLHS, PreCondRHS);
3101 break;
3102 }
3103 continue;
3104 default:
3105 // We weren't able to reconcile the condition.
3106 continue;
3107 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003108
3109 if (!PreCondLHS->getType()->isInteger()) continue;
3110
3111 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3112 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3113 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003114 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3115 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003116 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003117 }
3118
Dan Gohmanab678fb2008-08-12 20:17:31 +00003119 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003120}
3121
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003122/// HowManyLessThans - Return the number of times a backedge containing the
3123/// specified less-than comparison will execute. If not computable, return
3124/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003125ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Nick Lewycky35b56022009-01-13 09:18:58 +00003126HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003127 // Only handle: "ADDREC < LoopInvariant".
3128 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3129
3130 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3131 if (!AddRec || AddRec->getLoop() != L)
3132 return UnknownValue;
3133
3134 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003135 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003136 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3137 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3138 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3139
3140 // TODO: handle non-constant strides.
3141 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3142 if (!CStep || CStep->isZero())
3143 return UnknownValue;
3144 if (CStep->getValue()->getValue() == 1) {
3145 // With unit stride, the iteration never steps past the limit value.
3146 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3147 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3148 // Test whether a positive iteration iteration can step past the limit
3149 // value and past the maximum value for its type in a single step.
3150 if (isSigned) {
3151 APInt Max = APInt::getSignedMaxValue(BitWidth);
3152 if ((Max - CStep->getValue()->getValue())
3153 .slt(CLimit->getValue()->getValue()))
3154 return UnknownValue;
3155 } else {
3156 APInt Max = APInt::getMaxValue(BitWidth);
3157 if ((Max - CStep->getValue()->getValue())
3158 .ult(CLimit->getValue()->getValue()))
3159 return UnknownValue;
3160 }
3161 } else
3162 // TODO: handle non-constant limit values below.
3163 return UnknownValue;
3164 } else
3165 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003166 return UnknownValue;
3167
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003168 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3169 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3170 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003171 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003172
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003173 // First, we get the value of the LHS in the first iteration: n
3174 SCEVHandle Start = AddRec->getOperand(0);
3175
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003176 // Determine the minimum constant start value.
3177 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3178 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3179 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003180
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003181 // If we know that the condition is true in order to enter the loop,
3182 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3183 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3184 // division must round up.
3185 SCEVHandle End = RHS;
3186 if (!isLoopGuardedByCond(L,
3187 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3188 getMinusSCEV(Start, Step), RHS))
3189 End = isSigned ? getSMaxExpr(RHS, Start)
3190 : getUMaxExpr(RHS, Start);
3191
3192 // Determine the maximum constant end value.
3193 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3194 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3195 APInt::getMaxValue(BitWidth));
3196
3197 // Finally, we subtract these two values and divide, rounding up, to get
3198 // the number of times the backedge is executed.
3199 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3200 getAddExpr(Step, NegOne)),
3201 Step);
3202
3203 // The maximum backedge count is similar, except using the minimum start
3204 // value and the maximum end value.
3205 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3206 MinStart),
3207 getAddExpr(Step, NegOne)),
3208 Step);
3209
3210 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211 }
3212
3213 return UnknownValue;
3214}
3215
3216/// getNumIterationsInRange - Return the number of iterations of this loop that
3217/// produce values in the specified constant range. Another way of looking at
3218/// this is that it returns the first iteration number where the value is not in
3219/// the condition, thus computing the exit count. If the iteration count can't
3220/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003221SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3222 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003223 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003224 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003225
3226 // If the start is a non-zero constant, shift the range to simplify things.
3227 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3228 if (!SC->getValue()->isZero()) {
3229 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003230 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3231 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003232 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3233 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003234 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003235 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003236 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003237 }
3238
3239 // The only time we can solve this is when we have all constant indices.
3240 // Otherwise, we cannot determine the overflow conditions.
3241 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3242 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003243 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003244
3245
3246 // Okay at this point we know that all elements of the chrec are constants and
3247 // that the start element is zero.
3248
3249 // First check to see if the range contains zero. If not, the first
3250 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003251 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003252 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003253 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254
3255 if (isAffine()) {
3256 // If this is an affine expression then we have this situation:
3257 // Solve {0,+,A} in Range === Ax in Range
3258
3259 // We know that zero is in the range. If A is positive then we know that
3260 // the upper value of the range must be the first possible exit value.
3261 // If A is negative then the lower of the range is the last possible loop
3262 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003263 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003264 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3265 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3266
3267 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003268 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003269 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3270
3271 // Evaluate at the exit value. If we really did fall out of the valid
3272 // range, then we computed our trip count, otherwise wrap around or other
3273 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003274 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003275 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003276 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003277
3278 // Ensure that the previous value is in the range. This is a sanity check.
3279 assert(Range.contains(
3280 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003281 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003282 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003283 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003284 } else if (isQuadratic()) {
3285 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3286 // quadratic equation to solve it. To do this, we must frame our problem in
3287 // terms of figuring out when zero is crossed, instead of when
3288 // Range.getUpper() is crossed.
3289 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003290 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3291 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292
3293 // Next, solve the constructed addrec
3294 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003295 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003296 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3297 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3298 if (R1) {
3299 // Pick the smallest positive root value.
3300 if (ConstantInt *CB =
3301 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3302 R1->getValue(), R2->getValue()))) {
3303 if (CB->getZExtValue() == false)
3304 std::swap(R1, R2); // R1 is the minimum root now.
3305
3306 // Make sure the root is not off by one. The returned iteration should
3307 // not be in the range, but the previous one should be. When solving
3308 // for "X*X < 5", for example, we should not return a root of 2.
3309 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003310 R1->getValue(),
3311 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003312 if (Range.contains(R1Val->getValue())) {
3313 // The next iteration must be out of the range...
3314 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3315
Dan Gohman89f85052007-10-22 18:31:58 +00003316 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003317 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003318 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003319 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003320 }
3321
3322 // If R1 was not in the range, then it is a good return value. Make
3323 // sure that R1-1 WAS in the range though, just in case.
3324 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003325 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003326 if (Range.contains(R1Val->getValue()))
3327 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003328 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003329 }
3330 }
3331 }
3332
Dan Gohman0ad08b02009-04-18 17:58:19 +00003333 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003334}
3335
3336
3337
3338//===----------------------------------------------------------------------===//
3339// ScalarEvolution Class Implementation
3340//===----------------------------------------------------------------------===//
3341
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003342ScalarEvolution::ScalarEvolution()
3343 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3344}
3345
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003346bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003347 this->F = &F;
3348 LI = &getAnalysis<LoopInfo>();
3349 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003350 return false;
3351}
3352
3353void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003354 Scalars.clear();
3355 BackedgeTakenCounts.clear();
3356 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003357}
3358
3359void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3360 AU.setPreservesAll();
3361 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003362}
3363
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003364bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003365 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003366}
3367
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003368static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369 const Loop *L) {
3370 // Print all inner loops first
3371 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3372 PrintLoopInfo(OS, SE, *I);
3373
Nick Lewyckye5da1912008-01-02 02:49:20 +00003374 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003375
Devang Patel02451fa2007-08-21 00:31:24 +00003376 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 L->getExitBlocks(ExitBlocks);
3378 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003379 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003380
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003381 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3382 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003383 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003384 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003385 }
3386
Nick Lewyckye5da1912008-01-02 02:49:20 +00003387 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003388}
3389
Dan Gohman13058cc2009-04-21 00:47:46 +00003390void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003391 // ScalarEvolution's implementaiton of the print method is to print
3392 // out SCEV values of all instructions that are interesting. Doing
3393 // this potentially causes it to create new SCEV objects though,
3394 // which technically conflicts with the const qualifier. This isn't
3395 // observable from outside the class though (the hasSCEV function
3396 // notwithstanding), so casting away the const isn't dangerous.
3397 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003398
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003399 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003400 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003401 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003403 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003404 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 SV->print(OS);
3406 OS << "\t\t";
3407
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003408 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003409 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003410 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3412 OS << "<<Unknown>>";
3413 } else {
3414 OS << *ExitValue;
3415 }
3416 }
3417
3418
3419 OS << "\n";
3420 }
3421
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003422 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3423 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3424 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003425}
Dan Gohman13058cc2009-04-21 00:47:46 +00003426
3427void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3428 raw_os_ostream OS(o);
3429 print(OS, M);
3430}