blob: 495290d8d7317b2862b1400b66f24c20f3186cdd [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079#include "llvm/Support/InstIterator.h"
80#include "llvm/Support/ManagedStatic.h"
81#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085#include <ostream>
86#include <algorithm>
87#include <cmath>
88using namespace llvm;
89
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman089efff2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
103 cl::init(100));
104
Dan Gohman089efff2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107char ScalarEvolution::ID = 0;
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
116SCEV::~SCEV() {}
117void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125}
126
Dan Gohman7b560c42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000135SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
139 return false;
140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return 0;
145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000154 const SCEVHandle &Conc,
155 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 return this;
157}
158
Dan Gohman13058cc2009-04-21 00:47:46 +0000159void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
165}
166
167
168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value. Don't use a SCEVHandle here, or else the object will
170// never be deleted!
171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
172
173
174SCEVConstant::~SCEVConstant() {
175 SCEVConstants->erase(V);
176}
177
Dan Gohman89f85052007-10-22 18:31:58 +0000178SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 SCEVConstant *&R = (*SCEVConstants)[V];
180 if (R == 0) R = new SCEVConstant(V);
181 return R;
182}
183
Dan Gohman89f85052007-10-22 18:31:58 +0000184SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186}
187
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
189
Dan Gohman13058cc2009-04-21 00:47:46 +0000190void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 WriteAsOperand(OS, V, false);
192}
193
Dan Gohman2a381532009-04-21 01:25:57 +0000194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195 const SCEVHandle &op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
197
198SCEVCastExpr::~SCEVCastExpr() {}
199
200bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201 return Op->dominates(BB, DT);
202}
203
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205// particular input. Don't use a SCEVHandle here, or else the object will
206// never be deleted!
207static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
208 SCEVTruncateExpr*> > SCEVTruncates;
209
210SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000211 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215}
216
217SCEVTruncateExpr::~SCEVTruncateExpr() {
218 SCEVTruncates->erase(std::make_pair(Op, Ty));
219}
220
Dan Gohman13058cc2009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 OS << "(truncate " << *Op << " to " << *Ty << ")";
223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000232 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
240}
241
Dan Gohman13058cc2009-04-21 00:47:46 +0000242void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
244}
245
246// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247// particular input. Don't use a SCEVHandle here, or else the object will never
248// be deleted!
249static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
250 SCEVSignExtendExpr*> > SCEVSignExtends;
251
252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000253 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257}
258
259SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
261}
262
Dan Gohman13058cc2009-04-21 00:47:46 +0000263void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 OS << "(signextend " << *Op << " to " << *Ty << ")";
265}
266
267// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268// particular input. Don't use a SCEVHandle here, or else the object will never
269// be deleted!
270static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
271 SCEVCommutativeExpr*> > SCEVCommExprs;
272
273SCEVCommutativeExpr::~SCEVCommutativeExpr() {
274 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
275 std::vector<SCEV*>(Operands.begin(),
276 Operands.end())));
277}
278
Dan Gohman13058cc2009-04-21 00:47:46 +0000279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
286}
287
288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 if (H != getOperand(i)) {
296 std::vector<SCEVHandle> NewOps;
297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304
305 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000306 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000308 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 else
314 assert(0 && "Unknown commutative expr!");
315 }
316 }
317 return this;
318}
319
Evan Cheng98c073b2009-02-17 00:13:06 +0000320bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
324 }
325 return true;
326}
327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000333 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337}
338
Evan Cheng98c073b2009-02-17 00:13:06 +0000339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
Dan Gohman13058cc2009-04-21 00:47:46 +0000343void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000344 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345}
346
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348 return LHS->getType();
349}
350
351// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352// particular input. Don't use a SCEVHandle here, or else the object will never
353// be deleted!
354static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355 SCEVAddRecExpr*> > SCEVAddRecExprs;
356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
358 SCEVAddRecExprs->erase(std::make_pair(L,
359 std::vector<SCEV*>(Operands.begin(),
360 Operands.end())));
361}
362
Evan Cheng98c073b2009-02-17 00:13:06 +0000363bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365 if (!getOperand(i)->dominates(BB, DT))
366 return false;
367 }
368 return true;
369}
370
371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372SCEVHandle SCEVAddRecExpr::
373replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000374 const SCEVHandle &Conc,
375 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000377 SCEVHandle H =
378 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 if (H != getOperand(i)) {
380 std::vector<SCEVHandle> NewOps;
381 NewOps.reserve(getNumOperands());
382 for (unsigned j = 0; j != i; ++j)
383 NewOps.push_back(getOperand(j));
384 NewOps.push_back(H);
385 for (++i; i != e; ++i)
386 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000387 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388
Dan Gohman89f85052007-10-22 18:31:58 +0000389 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 }
391 }
392 return this;
393}
394
395
396bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
397 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
398 // contain L and if the start is invariant.
399 return !QueryLoop->contains(L->getHeader()) &&
400 getOperand(0)->isLoopInvariant(QueryLoop);
401}
402
403
Dan Gohman13058cc2009-04-21 00:47:46 +0000404void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 OS << "{" << *Operands[0];
406 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
407 OS << ",+," << *Operands[i];
408 OS << "}<" << L->getHeader()->getName() + ">";
409}
410
411// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
412// value. Don't use a SCEVHandle here, or else the object will never be
413// deleted!
414static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
415
416SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
417
418bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
419 // All non-instruction values are loop invariant. All instructions are loop
420 // invariant if they are not contained in the specified loop.
421 if (Instruction *I = dyn_cast<Instruction>(V))
422 return !L->contains(I->getParent());
423 return true;
424}
425
Evan Cheng98c073b2009-02-17 00:13:06 +0000426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
430}
431
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432const Type *SCEVUnknown::getType() const {
433 return V->getType();
434}
435
Dan Gohman13058cc2009-04-21 00:47:46 +0000436void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000437 if (isa<PointerType>(V->getType()))
438 OS << "(ptrtoint " << *V->getType() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 WriteAsOperand(OS, V, false);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000440 if (isa<PointerType>(V->getType()))
441 OS << " to iPTR)";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442}
443
444//===----------------------------------------------------------------------===//
445// SCEV Utilities
446//===----------------------------------------------------------------------===//
447
448namespace {
449 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450 /// than the complexity of the RHS. This comparator is used to canonicalize
451 /// expressions.
452 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000453 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 return LHS->getSCEVType() < RHS->getSCEVType();
455 }
456 };
457}
458
459/// GroupByComplexity - Given a list of SCEV objects, order them by their
460/// complexity, and group objects of the same complexity together by value.
461/// When this routine is finished, we know that any duplicates in the vector are
462/// consecutive and that complexity is monotonically increasing.
463///
464/// Note that we go take special precautions to ensure that we get determinstic
465/// results from this routine. In other words, we don't want the results of
466/// this to depend on where the addresses of various SCEV objects happened to
467/// land in memory.
468///
469static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
470 if (Ops.size() < 2) return; // Noop
471 if (Ops.size() == 2) {
472 // This is the common case, which also happens to be trivially simple.
473 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000474 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 std::swap(Ops[0], Ops[1]);
476 return;
477 }
478
479 // Do the rough sort by complexity.
480 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
481
482 // Now that we are sorted by complexity, group elements of the same
483 // complexity. Note that this is, at worst, N^2, but the vector is likely to
484 // be extremely short in practice. Note that we take this approach because we
485 // do not want to depend on the addresses of the objects we are grouping.
486 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
487 SCEV *S = Ops[i];
488 unsigned Complexity = S->getSCEVType();
489
490 // If there are any objects of the same complexity and same value as this
491 // one, group them.
492 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
493 if (Ops[j] == S) { // Found a duplicate.
494 // Move it to immediately after i'th element.
495 std::swap(Ops[i+1], Ops[j]);
496 ++i; // no need to rescan it.
497 if (i == e-2) return; // Done!
498 }
499 }
500 }
501}
502
503
504
505//===----------------------------------------------------------------------===//
506// Simple SCEV method implementations
507//===----------------------------------------------------------------------===//
508
Eli Friedman7489ec92008-08-04 23:49:06 +0000509/// BinomialCoefficient - Compute BC(It, K). The result has width W.
510// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000511static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000512 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000513 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000514 // Handle the simplest case efficiently.
515 if (K == 1)
516 return SE.getTruncateOrZeroExtend(It, ResultTy);
517
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000518 // We are using the following formula for BC(It, K):
519 //
520 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
521 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000522 // Suppose, W is the bitwidth of the return value. We must be prepared for
523 // overflow. Hence, we must assure that the result of our computation is
524 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
525 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000526 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000527 // However, this code doesn't use exactly that formula; the formula it uses
528 // is something like the following, where T is the number of factors of 2 in
529 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
530 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000531 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000532 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000533 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000534 // This formula is trivially equivalent to the previous formula. However,
535 // this formula can be implemented much more efficiently. The trick is that
536 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
537 // arithmetic. To do exact division in modular arithmetic, all we have
538 // to do is multiply by the inverse. Therefore, this step can be done at
539 // width W.
540 //
541 // The next issue is how to safely do the division by 2^T. The way this
542 // is done is by doing the multiplication step at a width of at least W + T
543 // bits. This way, the bottom W+T bits of the product are accurate. Then,
544 // when we perform the division by 2^T (which is equivalent to a right shift
545 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
546 // truncated out after the division by 2^T.
547 //
548 // In comparison to just directly using the first formula, this technique
549 // is much more efficient; using the first formula requires W * K bits,
550 // but this formula less than W + K bits. Also, the first formula requires
551 // a division step, whereas this formula only requires multiplies and shifts.
552 //
553 // It doesn't matter whether the subtraction step is done in the calculation
554 // width or the input iteration count's width; if the subtraction overflows,
555 // the result must be zero anyway. We prefer here to do it in the width of
556 // the induction variable because it helps a lot for certain cases; CodeGen
557 // isn't smart enough to ignore the overflow, which leads to much less
558 // efficient code if the width of the subtraction is wider than the native
559 // register width.
560 //
561 // (It's possible to not widen at all by pulling out factors of 2 before
562 // the multiplication; for example, K=2 can be calculated as
563 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
564 // extra arithmetic, so it's not an obvious win, and it gets
565 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000566
Eli Friedman7489ec92008-08-04 23:49:06 +0000567 // Protection from insane SCEVs; this bound is conservative,
568 // but it probably doesn't matter.
569 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000570 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000571
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000572 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000573
Eli Friedman7489ec92008-08-04 23:49:06 +0000574 // Calculate K! / 2^T and T; we divide out the factors of two before
575 // multiplying for calculating K! / 2^T to avoid overflow.
576 // Other overflow doesn't matter because we only care about the bottom
577 // W bits of the result.
578 APInt OddFactorial(W, 1);
579 unsigned T = 1;
580 for (unsigned i = 3; i <= K; ++i) {
581 APInt Mult(W, i);
582 unsigned TwoFactors = Mult.countTrailingZeros();
583 T += TwoFactors;
584 Mult = Mult.lshr(TwoFactors);
585 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000587
Eli Friedman7489ec92008-08-04 23:49:06 +0000588 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000589 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000590
591 // Calcuate 2^T, at width T+W.
592 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
593
594 // Calculate the multiplicative inverse of K! / 2^T;
595 // this multiplication factor will perform the exact division by
596 // K! / 2^T.
597 APInt Mod = APInt::getSignedMinValue(W+1);
598 APInt MultiplyFactor = OddFactorial.zext(W+1);
599 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
600 MultiplyFactor = MultiplyFactor.trunc(W);
601
602 // Calculate the product, at width T+W
603 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
604 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
605 for (unsigned i = 1; i != K; ++i) {
606 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
607 Dividend = SE.getMulExpr(Dividend,
608 SE.getTruncateOrZeroExtend(S, CalculationTy));
609 }
610
611 // Divide by 2^T
612 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
613
614 // Truncate the result, and divide by K! / 2^T.
615
616 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
617 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618}
619
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620/// evaluateAtIteration - Return the value of this chain of recurrences at
621/// the specified iteration number. We can evaluate this recurrence by
622/// multiplying each element in the chain by the binomial coefficient
623/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
624///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000625/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000627/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628///
Dan Gohman89f85052007-10-22 18:31:58 +0000629SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
630 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000633 // The computation is correct in the face of overflow provided that the
634 // multiplication is performed _after_ the evaluation of the binomial
635 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000636 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000637 if (isa<SCEVCouldNotCompute>(Coeff))
638 return Coeff;
639
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 }
642 return Result;
643}
644
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645//===----------------------------------------------------------------------===//
646// SCEV Expression folder implementations
647//===----------------------------------------------------------------------===//
648
Dan Gohman89f85052007-10-22 18:31:58 +0000649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000650 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000651 "This is not a truncating conversion!");
652
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000654 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 ConstantExpr::getTrunc(SC->getValue(), Ty));
656
Dan Gohman1a5c4992009-04-22 16:20:48 +0000657 // trunc(trunc(x)) --> trunc(x)
658 if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
659 return getTruncateExpr(ST->getOperand(), Ty);
660
Nick Lewycky37d04642009-04-23 05:15:08 +0000661 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
662 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
663 return getTruncateOrSignExtend(SS->getOperand(), Ty);
664
665 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
666 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
667 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
668
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 // If the input value is a chrec scev made out of constants, truncate
670 // all of the constants.
671 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
672 std::vector<SCEVHandle> Operands;
673 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
674 // FIXME: This should allow truncation of other expression types!
675 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000676 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 else
678 break;
679 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000680 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 }
682
683 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
684 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
685 return Result;
686}
687
Dan Gohman36d40922009-04-16 19:25:55 +0000688SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
689 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000690 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000691 "This is not an extending conversion!");
692
Dan Gohman01c2ee72009-04-16 03:18:22 +0000693 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000694 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000695 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
696 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
697 return getUnknown(C);
698 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699
Dan Gohman1a5c4992009-04-22 16:20:48 +0000700 // zext(zext(x)) --> zext(x)
701 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
702 return getZeroExtendExpr(SZ->getOperand(), Ty);
703
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 // FIXME: If the input value is a chrec scev, and we can prove that the value
705 // did not overflow the old, smaller, value, we can zero extend all of the
706 // operands (often constants). This would allow analysis of something like
707 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
708
709 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
710 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
711 return Result;
712}
713
Dan Gohman89f85052007-10-22 18:31:58 +0000714SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000715 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000716 "This is not an extending conversion!");
717
Dan Gohman01c2ee72009-04-16 03:18:22 +0000718 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000719 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000720 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
721 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
722 return getUnknown(C);
723 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724
Dan Gohman1a5c4992009-04-22 16:20:48 +0000725 // sext(sext(x)) --> sext(x)
726 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
727 return getSignExtendExpr(SS->getOperand(), Ty);
728
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 // FIXME: If the input value is a chrec scev, and we can prove that the value
730 // did not overflow the old, smaller, value, we can sign extend all of the
731 // operands (often constants). This would allow analysis of something like
732 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
733
734 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
735 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
736 return Result;
737}
738
739// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000740SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 assert(!Ops.empty() && "Cannot get empty add!");
742 if (Ops.size() == 1) return Ops[0];
743
744 // Sort by complexity, this groups all similar expression types together.
745 GroupByComplexity(Ops);
746
747 // If there are any constants, fold them together.
748 unsigned Idx = 0;
749 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
750 ++Idx;
751 assert(Idx < Ops.size());
752 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
753 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000754 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
755 RHSC->getValue()->getValue());
756 Ops[0] = getConstant(Fold);
757 Ops.erase(Ops.begin()+1); // Erase the folded element
758 if (Ops.size() == 1) return Ops[0];
759 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 }
761
762 // If we are left with a constant zero being added, strip it off.
763 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
764 Ops.erase(Ops.begin());
765 --Idx;
766 }
767 }
768
769 if (Ops.size() == 1) return Ops[0];
770
771 // Okay, check to see if the same value occurs in the operand list twice. If
772 // so, merge them together into an multiply expression. Since we sorted the
773 // list, these values are required to be adjacent.
774 const Type *Ty = Ops[0]->getType();
775 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
776 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
777 // Found a match, merge the two values into a multiply, and add any
778 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000779 SCEVHandle Two = getIntegerSCEV(2, Ty);
780 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 if (Ops.size() == 2)
782 return Mul;
783 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
784 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000785 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 }
787
788 // Now we know the first non-constant operand. Skip past any cast SCEVs.
789 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
790 ++Idx;
791
792 // If there are add operands they would be next.
793 if (Idx < Ops.size()) {
794 bool DeletedAdd = false;
795 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
796 // If we have an add, expand the add operands onto the end of the operands
797 // list.
798 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
799 Ops.erase(Ops.begin()+Idx);
800 DeletedAdd = true;
801 }
802
803 // If we deleted at least one add, we added operands to the end of the list,
804 // and they are not necessarily sorted. Recurse to resort and resimplify
805 // any operands we just aquired.
806 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000807 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 }
809
810 // Skip over the add expression until we get to a multiply.
811 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
812 ++Idx;
813
814 // If we are adding something to a multiply expression, make sure the
815 // something is not already an operand of the multiply. If so, merge it into
816 // the multiply.
817 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
818 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
819 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
820 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
821 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
822 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
823 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
824 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
825 if (Mul->getNumOperands() != 2) {
826 // If the multiply has more than two operands, we must get the
827 // Y*Z term.
828 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
829 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000830 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 }
Dan Gohman89f85052007-10-22 18:31:58 +0000832 SCEVHandle One = getIntegerSCEV(1, Ty);
833 SCEVHandle AddOne = getAddExpr(InnerMul, One);
834 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 if (Ops.size() == 2) return OuterMul;
836 if (AddOp < Idx) {
837 Ops.erase(Ops.begin()+AddOp);
838 Ops.erase(Ops.begin()+Idx-1);
839 } else {
840 Ops.erase(Ops.begin()+Idx);
841 Ops.erase(Ops.begin()+AddOp-1);
842 }
843 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000844 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 }
846
847 // Check this multiply against other multiplies being added together.
848 for (unsigned OtherMulIdx = Idx+1;
849 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
850 ++OtherMulIdx) {
851 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
852 // If MulOp occurs in OtherMul, we can fold the two multiplies
853 // together.
854 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
855 OMulOp != e; ++OMulOp)
856 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
857 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
858 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
859 if (Mul->getNumOperands() != 2) {
860 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
861 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000862 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 }
864 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
865 if (OtherMul->getNumOperands() != 2) {
866 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
867 OtherMul->op_end());
868 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000869 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 }
Dan Gohman89f85052007-10-22 18:31:58 +0000871 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
872 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873 if (Ops.size() == 2) return OuterMul;
874 Ops.erase(Ops.begin()+Idx);
875 Ops.erase(Ops.begin()+OtherMulIdx-1);
876 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000877 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878 }
879 }
880 }
881 }
882
883 // If there are any add recurrences in the operands list, see if any other
884 // added values are loop invariant. If so, we can fold them into the
885 // recurrence.
886 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
887 ++Idx;
888
889 // Scan over all recurrences, trying to fold loop invariants into them.
890 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
891 // Scan all of the other operands to this add and add them to the vector if
892 // they are loop invariant w.r.t. the recurrence.
893 std::vector<SCEVHandle> LIOps;
894 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
895 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
896 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
897 LIOps.push_back(Ops[i]);
898 Ops.erase(Ops.begin()+i);
899 --i; --e;
900 }
901
902 // If we found some loop invariants, fold them into the recurrence.
903 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000904 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 LIOps.push_back(AddRec->getStart());
906
907 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000908 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909
Dan Gohman89f85052007-10-22 18:31:58 +0000910 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000911 // If all of the other operands were loop invariant, we are done.
912 if (Ops.size() == 1) return NewRec;
913
914 // Otherwise, add the folded AddRec by the non-liv parts.
915 for (unsigned i = 0;; ++i)
916 if (Ops[i] == AddRec) {
917 Ops[i] = NewRec;
918 break;
919 }
Dan Gohman89f85052007-10-22 18:31:58 +0000920 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 }
922
923 // Okay, if there weren't any loop invariants to be folded, check to see if
924 // there are multiple AddRec's with the same loop induction variable being
925 // added together. If so, we can fold them.
926 for (unsigned OtherIdx = Idx+1;
927 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
928 if (OtherIdx != Idx) {
929 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
930 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
931 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
932 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
933 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
934 if (i >= NewOps.size()) {
935 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
936 OtherAddRec->op_end());
937 break;
938 }
Dan Gohman89f85052007-10-22 18:31:58 +0000939 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940 }
Dan Gohman89f85052007-10-22 18:31:58 +0000941 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942
943 if (Ops.size() == 2) return NewAddRec;
944
945 Ops.erase(Ops.begin()+Idx);
946 Ops.erase(Ops.begin()+OtherIdx-1);
947 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000948 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 }
950 }
951
952 // Otherwise couldn't fold anything into this recurrence. Move onto the
953 // next one.
954 }
955
956 // Okay, it looks like we really DO need an add expr. Check to see if we
957 // already have one, otherwise create a new one.
958 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
959 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
960 SCEVOps)];
961 if (Result == 0) Result = new SCEVAddExpr(Ops);
962 return Result;
963}
964
965
Dan Gohman89f85052007-10-22 18:31:58 +0000966SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 assert(!Ops.empty() && "Cannot get empty mul!");
968
969 // Sort by complexity, this groups all similar expression types together.
970 GroupByComplexity(Ops);
971
972 // If there are any constants, fold them together.
973 unsigned Idx = 0;
974 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
975
976 // C1*(C2+V) -> C1*C2 + C1*V
977 if (Ops.size() == 2)
978 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
979 if (Add->getNumOperands() == 2 &&
980 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000981 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
982 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983
984
985 ++Idx;
986 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
987 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000988 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
989 RHSC->getValue()->getValue());
990 Ops[0] = getConstant(Fold);
991 Ops.erase(Ops.begin()+1); // Erase the folded element
992 if (Ops.size() == 1) return Ops[0];
993 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 }
995
996 // If we are left with a constant one being multiplied, strip it off.
997 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
998 Ops.erase(Ops.begin());
999 --Idx;
1000 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1001 // If we have a multiply of zero, it will always be zero.
1002 return Ops[0];
1003 }
1004 }
1005
1006 // Skip over the add expression until we get to a multiply.
1007 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1008 ++Idx;
1009
1010 if (Ops.size() == 1)
1011 return Ops[0];
1012
1013 // If there are mul operands inline them all into this expression.
1014 if (Idx < Ops.size()) {
1015 bool DeletedMul = false;
1016 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1017 // If we have an mul, expand the mul operands onto the end of the operands
1018 // list.
1019 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1020 Ops.erase(Ops.begin()+Idx);
1021 DeletedMul = true;
1022 }
1023
1024 // If we deleted at least one mul, we added operands to the end of the list,
1025 // and they are not necessarily sorted. Recurse to resort and resimplify
1026 // any operands we just aquired.
1027 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001028 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 }
1030
1031 // If there are any add recurrences in the operands list, see if any other
1032 // added values are loop invariant. If so, we can fold them into the
1033 // recurrence.
1034 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1035 ++Idx;
1036
1037 // Scan over all recurrences, trying to fold loop invariants into them.
1038 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1039 // Scan all of the other operands to this mul and add them to the vector if
1040 // they are loop invariant w.r.t. the recurrence.
1041 std::vector<SCEVHandle> LIOps;
1042 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1043 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1044 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1045 LIOps.push_back(Ops[i]);
1046 Ops.erase(Ops.begin()+i);
1047 --i; --e;
1048 }
1049
1050 // If we found some loop invariants, fold them into the recurrence.
1051 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001052 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 std::vector<SCEVHandle> NewOps;
1054 NewOps.reserve(AddRec->getNumOperands());
1055 if (LIOps.size() == 1) {
1056 SCEV *Scale = LIOps[0];
1057 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001058 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 } else {
1060 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1061 std::vector<SCEVHandle> MulOps(LIOps);
1062 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001063 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 }
1065 }
1066
Dan Gohman89f85052007-10-22 18:31:58 +00001067 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068
1069 // If all of the other operands were loop invariant, we are done.
1070 if (Ops.size() == 1) return NewRec;
1071
1072 // Otherwise, multiply the folded AddRec by the non-liv parts.
1073 for (unsigned i = 0;; ++i)
1074 if (Ops[i] == AddRec) {
1075 Ops[i] = NewRec;
1076 break;
1077 }
Dan Gohman89f85052007-10-22 18:31:58 +00001078 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 }
1080
1081 // Okay, if there weren't any loop invariants to be folded, check to see if
1082 // there are multiple AddRec's with the same loop induction variable being
1083 // multiplied together. If so, we can fold them.
1084 for (unsigned OtherIdx = Idx+1;
1085 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1086 if (OtherIdx != Idx) {
1087 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1088 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1089 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1090 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001091 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001093 SCEVHandle B = F->getStepRecurrence(*this);
1094 SCEVHandle D = G->getStepRecurrence(*this);
1095 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1096 getMulExpr(G, B),
1097 getMulExpr(B, D));
1098 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1099 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 if (Ops.size() == 2) return NewAddRec;
1101
1102 Ops.erase(Ops.begin()+Idx);
1103 Ops.erase(Ops.begin()+OtherIdx-1);
1104 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001105 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106 }
1107 }
1108
1109 // Otherwise couldn't fold anything into this recurrence. Move onto the
1110 // next one.
1111 }
1112
1113 // Okay, it looks like we really DO need an mul expr. Check to see if we
1114 // already have one, otherwise create a new one.
1115 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1116 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1117 SCEVOps)];
1118 if (Result == 0)
1119 Result = new SCEVMulExpr(Ops);
1120 return Result;
1121}
1122
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001123SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1125 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001126 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127
1128 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1129 Constant *LHSCV = LHSC->getValue();
1130 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001131 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 }
1133 }
1134
Nick Lewycky35b56022009-01-13 09:18:58 +00001135 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1136
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001137 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1138 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139 return Result;
1140}
1141
1142
1143/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1144/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001145SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 const SCEVHandle &Step, const Loop *L) {
1147 std::vector<SCEVHandle> Operands;
1148 Operands.push_back(Start);
1149 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1150 if (StepChrec->getLoop() == L) {
1151 Operands.insert(Operands.end(), StepChrec->op_begin(),
1152 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001153 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 }
1155
1156 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001157 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158}
1159
1160/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1161/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001162SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001163 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 if (Operands.size() == 1) return Operands[0];
1165
Dan Gohman7b560c42008-06-18 16:23:07 +00001166 if (Operands.back()->isZero()) {
1167 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001168 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001169 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170
Dan Gohman42936882008-08-08 18:33:12 +00001171 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1172 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1173 const Loop* NestedLoop = NestedAR->getLoop();
1174 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1175 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1176 NestedAR->op_end());
1177 SCEVHandle NestedARHandle(NestedAR);
1178 Operands[0] = NestedAR->getStart();
1179 NestedOperands[0] = getAddRecExpr(Operands, L);
1180 return getAddRecExpr(NestedOperands, NestedLoop);
1181 }
1182 }
1183
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 SCEVAddRecExpr *&Result =
1185 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1186 Operands.end()))];
1187 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1188 return Result;
1189}
1190
Nick Lewycky711640a2007-11-25 22:41:31 +00001191SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1192 const SCEVHandle &RHS) {
1193 std::vector<SCEVHandle> Ops;
1194 Ops.push_back(LHS);
1195 Ops.push_back(RHS);
1196 return getSMaxExpr(Ops);
1197}
1198
1199SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1200 assert(!Ops.empty() && "Cannot get empty smax!");
1201 if (Ops.size() == 1) return Ops[0];
1202
1203 // Sort by complexity, this groups all similar expression types together.
1204 GroupByComplexity(Ops);
1205
1206 // If there are any constants, fold them together.
1207 unsigned Idx = 0;
1208 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1209 ++Idx;
1210 assert(Idx < Ops.size());
1211 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1212 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001213 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001214 APIntOps::smax(LHSC->getValue()->getValue(),
1215 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001216 Ops[0] = getConstant(Fold);
1217 Ops.erase(Ops.begin()+1); // Erase the folded element
1218 if (Ops.size() == 1) return Ops[0];
1219 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001220 }
1221
1222 // If we are left with a constant -inf, strip it off.
1223 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1224 Ops.erase(Ops.begin());
1225 --Idx;
1226 }
1227 }
1228
1229 if (Ops.size() == 1) return Ops[0];
1230
1231 // Find the first SMax
1232 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1233 ++Idx;
1234
1235 // Check to see if one of the operands is an SMax. If so, expand its operands
1236 // onto our operand list, and recurse to simplify.
1237 if (Idx < Ops.size()) {
1238 bool DeletedSMax = false;
1239 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1240 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1241 Ops.erase(Ops.begin()+Idx);
1242 DeletedSMax = true;
1243 }
1244
1245 if (DeletedSMax)
1246 return getSMaxExpr(Ops);
1247 }
1248
1249 // Okay, check to see if the same value occurs in the operand list twice. If
1250 // so, delete one. Since we sorted the list, these values are required to
1251 // be adjacent.
1252 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1253 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1254 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1255 --i; --e;
1256 }
1257
1258 if (Ops.size() == 1) return Ops[0];
1259
1260 assert(!Ops.empty() && "Reduced smax down to nothing!");
1261
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001262 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001263 // already have one, otherwise create a new one.
1264 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1265 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1266 SCEVOps)];
1267 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1268 return Result;
1269}
1270
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001271SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1272 const SCEVHandle &RHS) {
1273 std::vector<SCEVHandle> Ops;
1274 Ops.push_back(LHS);
1275 Ops.push_back(RHS);
1276 return getUMaxExpr(Ops);
1277}
1278
1279SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1280 assert(!Ops.empty() && "Cannot get empty umax!");
1281 if (Ops.size() == 1) return Ops[0];
1282
1283 // Sort by complexity, this groups all similar expression types together.
1284 GroupByComplexity(Ops);
1285
1286 // If there are any constants, fold them together.
1287 unsigned Idx = 0;
1288 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1289 ++Idx;
1290 assert(Idx < Ops.size());
1291 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1292 // We found two constants, fold them together!
1293 ConstantInt *Fold = ConstantInt::get(
1294 APIntOps::umax(LHSC->getValue()->getValue(),
1295 RHSC->getValue()->getValue()));
1296 Ops[0] = getConstant(Fold);
1297 Ops.erase(Ops.begin()+1); // Erase the folded element
1298 if (Ops.size() == 1) return Ops[0];
1299 LHSC = cast<SCEVConstant>(Ops[0]);
1300 }
1301
1302 // If we are left with a constant zero, strip it off.
1303 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1304 Ops.erase(Ops.begin());
1305 --Idx;
1306 }
1307 }
1308
1309 if (Ops.size() == 1) return Ops[0];
1310
1311 // Find the first UMax
1312 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1313 ++Idx;
1314
1315 // Check to see if one of the operands is a UMax. If so, expand its operands
1316 // onto our operand list, and recurse to simplify.
1317 if (Idx < Ops.size()) {
1318 bool DeletedUMax = false;
1319 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1320 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1321 Ops.erase(Ops.begin()+Idx);
1322 DeletedUMax = true;
1323 }
1324
1325 if (DeletedUMax)
1326 return getUMaxExpr(Ops);
1327 }
1328
1329 // Okay, check to see if the same value occurs in the operand list twice. If
1330 // so, delete one. Since we sorted the list, these values are required to
1331 // be adjacent.
1332 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1333 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1334 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1335 --i; --e;
1336 }
1337
1338 if (Ops.size() == 1) return Ops[0];
1339
1340 assert(!Ops.empty() && "Reduced umax down to nothing!");
1341
1342 // Okay, it looks like we really DO need a umax expr. Check to see if we
1343 // already have one, otherwise create a new one.
1344 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1345 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1346 SCEVOps)];
1347 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1348 return Result;
1349}
1350
Dan Gohman89f85052007-10-22 18:31:58 +00001351SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001353 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001354 if (isa<ConstantPointerNull>(V))
1355 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1357 if (Result == 0) Result = new SCEVUnknown(V);
1358 return Result;
1359}
1360
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362// Basic SCEV Analysis and PHI Idiom Recognition Code
1363//
1364
1365/// deleteValueFromRecords - This method should be called by the
1366/// client before it removes an instruction from the program, to make sure
1367/// that no dangling references are left around.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001368void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 SmallVector<Value *, 16> Worklist;
1370
1371 if (Scalars.erase(V)) {
1372 if (PHINode *PN = dyn_cast<PHINode>(V))
1373 ConstantEvolutionLoopExitValue.erase(PN);
1374 Worklist.push_back(V);
1375 }
1376
1377 while (!Worklist.empty()) {
1378 Value *VV = Worklist.back();
1379 Worklist.pop_back();
1380
1381 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1382 UI != UE; ++UI) {
1383 Instruction *Inst = cast<Instruction>(*UI);
1384 if (Scalars.erase(Inst)) {
1385 if (PHINode *PN = dyn_cast<PHINode>(VV))
1386 ConstantEvolutionLoopExitValue.erase(PN);
1387 Worklist.push_back(Inst);
1388 }
1389 }
1390 }
1391}
1392
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001393/// isSCEVable - Test if values of the given type are analyzable within
1394/// the SCEV framework. This primarily includes integer types, and it
1395/// can optionally include pointer types if the ScalarEvolution class
1396/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001397bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001398 // Integers are always SCEVable.
1399 if (Ty->isInteger())
1400 return true;
1401
1402 // Pointers are SCEVable if TargetData information is available
1403 // to provide pointer size information.
1404 if (isa<PointerType>(Ty))
1405 return TD != NULL;
1406
1407 // Otherwise it's not SCEVable.
1408 return false;
1409}
1410
1411/// getTypeSizeInBits - Return the size in bits of the specified type,
1412/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001413uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001414 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1415
1416 // If we have a TargetData, use it!
1417 if (TD)
1418 return TD->getTypeSizeInBits(Ty);
1419
1420 // Otherwise, we support only integer types.
1421 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1422 return Ty->getPrimitiveSizeInBits();
1423}
1424
1425/// getEffectiveSCEVType - Return a type with the same bitwidth as
1426/// the given type and which represents how SCEV will treat the given
1427/// type, for which isSCEVable must return true. For pointer types,
1428/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001429const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001430 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1431
1432 if (Ty->isInteger())
1433 return Ty;
1434
1435 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1436 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001437}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001439SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001440 return UnknownValue;
1441}
1442
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1444/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001445SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001446 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447
1448 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1449 if (I != Scalars.end()) return I->second;
1450 SCEVHandle S = createSCEV(V);
1451 Scalars.insert(std::make_pair(V, S));
1452 return S;
1453}
1454
Dan Gohman01c2ee72009-04-16 03:18:22 +00001455/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1456/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001457SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1458 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001459 Constant *C;
1460 if (Val == 0)
1461 C = Constant::getNullValue(Ty);
1462 else if (Ty->isFloatingPoint())
1463 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1464 APFloat::IEEEdouble, Val));
1465 else
1466 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001467 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001468}
1469
1470/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1471///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001472SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001473 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001474 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001475
1476 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001477 Ty = getEffectiveSCEVType(Ty);
1478 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001479}
1480
1481/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001482SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001483 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001484 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001485
1486 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001487 Ty = getEffectiveSCEVType(Ty);
1488 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001489 return getMinusSCEV(AllOnes, V);
1490}
1491
1492/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1493///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001494SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001495 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001496 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001497 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001498}
1499
1500/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1501/// input value to the specified type. If the type must be extended, it is zero
1502/// extended.
1503SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001504ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001505 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001506 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001507 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1508 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001509 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001510 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001511 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001512 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001513 return getTruncateExpr(V, Ty);
1514 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001515}
1516
1517/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1518/// input value to the specified type. If the type must be extended, it is sign
1519/// extended.
1520SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001521ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001522 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001523 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001524 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1525 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001526 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001527 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001528 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001529 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001530 return getTruncateExpr(V, Ty);
1531 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001532}
1533
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1535/// the specified instruction and replaces any references to the symbolic value
1536/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001537void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1539 const SCEVHandle &NewVal) {
1540 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1541 if (SI == Scalars.end()) return;
1542
1543 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001544 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545 if (NV == SI->second) return; // No change.
1546
1547 SI->second = NV; // Update the scalars map!
1548
1549 // Any instruction values that use this instruction might also need to be
1550 // updated!
1551 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1552 UI != E; ++UI)
1553 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1554}
1555
1556/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1557/// a loop header, making it a potential recurrence, or it doesn't.
1558///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001559SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001561 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001562 if (L->getHeader() == PN->getParent()) {
1563 // If it lives in the loop header, it has two incoming values, one
1564 // from outside the loop, and one from inside.
1565 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1566 unsigned BackEdge = IncomingEdge^1;
1567
1568 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001569 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001570 assert(Scalars.find(PN) == Scalars.end() &&
1571 "PHI node already processed?");
1572 Scalars.insert(std::make_pair(PN, SymbolicName));
1573
1574 // Using this symbolic name for the PHI, analyze the value coming around
1575 // the back-edge.
1576 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1577
1578 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1579 // has a special value for the first iteration of the loop.
1580
1581 // If the value coming around the backedge is an add with the symbolic
1582 // value we just inserted, then we found a simple induction variable!
1583 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1584 // If there is a single occurrence of the symbolic value, replace it
1585 // with a recurrence.
1586 unsigned FoundIndex = Add->getNumOperands();
1587 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1588 if (Add->getOperand(i) == SymbolicName)
1589 if (FoundIndex == e) {
1590 FoundIndex = i;
1591 break;
1592 }
1593
1594 if (FoundIndex != Add->getNumOperands()) {
1595 // Create an add with everything but the specified operand.
1596 std::vector<SCEVHandle> Ops;
1597 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1598 if (i != FoundIndex)
1599 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001600 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001601
1602 // This is not a valid addrec if the step amount is varying each
1603 // loop iteration, but is not itself an addrec in this loop.
1604 if (Accum->isLoopInvariant(L) ||
1605 (isa<SCEVAddRecExpr>(Accum) &&
1606 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1607 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001608 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001609
1610 // Okay, for the entire analysis of this edge we assumed the PHI
1611 // to be symbolic. We now need to go back and update all of the
1612 // entries for the scalars that use the PHI (except for the PHI
1613 // itself) to use the new analyzed value instead of the "symbolic"
1614 // value.
1615 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1616 return PHISCEV;
1617 }
1618 }
1619 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1620 // Otherwise, this could be a loop like this:
1621 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1622 // In this case, j = {1,+,1} and BEValue is j.
1623 // Because the other in-value of i (0) fits the evolution of BEValue
1624 // i really is an addrec evolution.
1625 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1626 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1627
1628 // If StartVal = j.start - j.stride, we can use StartVal as the
1629 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001630 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001631 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001632 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001633 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634
1635 // Okay, for the entire analysis of this edge we assumed the PHI
1636 // to be symbolic. We now need to go back and update all of the
1637 // entries for the scalars that use the PHI (except for the PHI
1638 // itself) to use the new analyzed value instead of the "symbolic"
1639 // value.
1640 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1641 return PHISCEV;
1642 }
1643 }
1644 }
1645
1646 return SymbolicName;
1647 }
1648
1649 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001650 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001651}
1652
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001653/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1654/// guaranteed to end in (at every loop iteration). It is, at the same time,
1655/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1656/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001657static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001658 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001659 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001661 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001662 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1663 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001664
1665 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001666 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1667 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1668 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001669 }
1670
1671 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001672 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1673 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1674 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001675 }
1676
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001677 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001678 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001679 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001680 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001681 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001682 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683 }
1684
1685 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001686 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001687 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1688 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001689 for (unsigned i = 1, e = M->getNumOperands();
1690 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001691 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001692 BitWidth);
1693 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001695
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001697 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001698 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001699 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001700 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001701 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001703
Nick Lewycky711640a2007-11-25 22:41:31 +00001704 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1705 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001706 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001707 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001708 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001709 return MinOpRes;
1710 }
1711
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001712 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1713 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001714 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001715 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001716 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001717 return MinOpRes;
1718 }
1719
Nick Lewycky35b56022009-01-13 09:18:58 +00001720 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001721 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722}
1723
1724/// createSCEV - We know that there is no SCEV for the specified value.
1725/// Analyze the expression.
1726///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001727SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001728 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001729 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001730
Dan Gohman3996f472008-06-22 19:56:46 +00001731 unsigned Opcode = Instruction::UserOp1;
1732 if (Instruction *I = dyn_cast<Instruction>(V))
1733 Opcode = I->getOpcode();
1734 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1735 Opcode = CE->getOpcode();
1736 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001737 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738
Dan Gohman3996f472008-06-22 19:56:46 +00001739 User *U = cast<User>(V);
1740 switch (Opcode) {
1741 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001742 return getAddExpr(getSCEV(U->getOperand(0)),
1743 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001744 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001745 return getMulExpr(getSCEV(U->getOperand(0)),
1746 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001747 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001748 return getUDivExpr(getSCEV(U->getOperand(0)),
1749 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001750 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001751 return getMinusSCEV(getSCEV(U->getOperand(0)),
1752 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001753 case Instruction::And:
1754 // For an expression like x&255 that merely masks off the high bits,
1755 // use zext(trunc(x)) as the SCEV expression.
1756 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001757 if (CI->isNullValue())
1758 return getSCEV(U->getOperand(1));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001759 const APInt &A = CI->getValue();
1760 unsigned Ones = A.countTrailingOnes();
1761 if (APIntOps::isMask(Ones, A))
1762 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001763 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1764 IntegerType::get(Ones)),
1765 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001766 }
1767 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001768 case Instruction::Or:
1769 // If the RHS of the Or is a constant, we may have something like:
1770 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1771 // optimizations will transparently handle this case.
1772 //
1773 // In order for this transformation to be safe, the LHS must be of the
1774 // form X*(2^n) and the Or constant must be less than 2^n.
1775 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1776 SCEVHandle LHS = getSCEV(U->getOperand(0));
1777 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001778 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001779 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001780 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781 }
Dan Gohman3996f472008-06-22 19:56:46 +00001782 break;
1783 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001784 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001785 // If the RHS of the xor is a signbit, then this is just an add.
1786 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001787 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001788 return getAddExpr(getSCEV(U->getOperand(0)),
1789 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001790
1791 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001792 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001793 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001794 }
1795 break;
1796
1797 case Instruction::Shl:
1798 // Turn shift left of a constant amount into a multiply.
1799 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1800 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1801 Constant *X = ConstantInt::get(
1802 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001803 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001804 }
1805 break;
1806
Nick Lewycky7fd27892008-07-07 06:15:49 +00001807 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001808 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001809 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1810 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1811 Constant *X = ConstantInt::get(
1812 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001813 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001814 }
1815 break;
1816
Dan Gohman53bf64a2009-04-21 02:26:00 +00001817 case Instruction::AShr:
1818 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1819 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1820 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1821 if (L->getOpcode() == Instruction::Shl &&
1822 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001823 unsigned BitWidth = getTypeSizeInBits(U->getType());
1824 uint64_t Amt = BitWidth - CI->getZExtValue();
1825 if (Amt == BitWidth)
1826 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1827 if (Amt > BitWidth)
1828 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001829 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001830 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001831 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001832 U->getType());
1833 }
1834 break;
1835
Dan Gohman3996f472008-06-22 19:56:46 +00001836 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001837 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001838
1839 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001840 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001841
1842 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001843 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001844
1845 case Instruction::BitCast:
1846 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001847 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001848 return getSCEV(U->getOperand(0));
1849 break;
1850
Dan Gohman01c2ee72009-04-16 03:18:22 +00001851 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001852 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001853 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001854 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001855
1856 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001857 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001858 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1859 U->getType());
1860
1861 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001862 if (!TD) break; // Without TD we can't analyze pointers.
1863 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001864 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001865 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001866 gep_type_iterator GTI = gep_type_begin(U);
1867 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1868 E = U->op_end();
1869 I != E; ++I) {
1870 Value *Index = *I;
1871 // Compute the (potentially symbolic) offset in bytes for this index.
1872 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1873 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001874 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001875 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1876 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001877 TotalOffset = getAddExpr(TotalOffset,
1878 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001879 } else {
1880 // For an array, add the element offset, explicitly scaled.
1881 SCEVHandle LocalOffset = getSCEV(Index);
1882 if (!isa<PointerType>(LocalOffset->getType()))
1883 // Getelementptr indicies are signed.
1884 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1885 IntPtrTy);
1886 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001887 getMulExpr(LocalOffset,
1888 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1889 IntPtrTy));
1890 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001891 }
1892 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001893 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001894 }
1895
Dan Gohman3996f472008-06-22 19:56:46 +00001896 case Instruction::PHI:
1897 return createNodeForPHI(cast<PHINode>(U));
1898
1899 case Instruction::Select:
1900 // This could be a smax or umax that was lowered earlier.
1901 // Try to recover it.
1902 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1903 Value *LHS = ICI->getOperand(0);
1904 Value *RHS = ICI->getOperand(1);
1905 switch (ICI->getPredicate()) {
1906 case ICmpInst::ICMP_SLT:
1907 case ICmpInst::ICMP_SLE:
1908 std::swap(LHS, RHS);
1909 // fall through
1910 case ICmpInst::ICMP_SGT:
1911 case ICmpInst::ICMP_SGE:
1912 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001913 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001914 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00001915 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001916 return getNotSCEV(getSMaxExpr(
1917 getNotSCEV(getSCEV(LHS)),
1918 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001919 break;
1920 case ICmpInst::ICMP_ULT:
1921 case ICmpInst::ICMP_ULE:
1922 std::swap(LHS, RHS);
1923 // fall through
1924 case ICmpInst::ICMP_UGT:
1925 case ICmpInst::ICMP_UGE:
1926 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001927 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001928 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1929 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001930 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
1931 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001932 break;
1933 default:
1934 break;
1935 }
1936 }
1937
1938 default: // We cannot analyze this expression.
1939 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001940 }
1941
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001942 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001943}
1944
1945
1946
1947//===----------------------------------------------------------------------===//
1948// Iteration Count Computation Code
1949//
1950
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001951/// getBackedgeTakenCount - If the specified loop has a predictable
1952/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1953/// object. The backedge-taken count is the number of times the loop header
1954/// will be branched to from within the loop. This is one less than the
1955/// trip count of the loop, since it doesn't count the first iteration,
1956/// when the header is branched to from outside the loop.
1957///
1958/// Note that it is not valid to call this method on a loop without a
1959/// loop-invariant backedge-taken count (see
1960/// hasLoopInvariantBackedgeTakenCount).
1961///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001962SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001963 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
1964 if (I == BackedgeTakenCounts.end()) {
1965 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
1966 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001967 if (ItCount != UnknownValue) {
1968 assert(ItCount->isLoopInvariant(L) &&
1969 "Computed trip count isn't loop invariant for loop!");
1970 ++NumTripCountsComputed;
1971 } else if (isa<PHINode>(L->getHeader()->begin())) {
1972 // Only count loops that have phi nodes as not being computable.
1973 ++NumTripCountsNotComputed;
1974 }
1975 }
1976 return I->second;
1977}
1978
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001979/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001980/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001981/// ScalarEvolution's ability to compute a trip count, or if the loop
1982/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001983void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001984 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001985}
1986
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001987/// ComputeBackedgeTakenCount - Compute the number of times the backedge
1988/// of the specified loop will execute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001989SCEVHandle ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001990 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00001991 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 L->getExitBlocks(ExitBlocks);
1993 if (ExitBlocks.size() != 1) return UnknownValue;
1994
1995 // Okay, there is one exit block. Try to find the condition that causes the
1996 // loop to be exited.
1997 BasicBlock *ExitBlock = ExitBlocks[0];
1998
1999 BasicBlock *ExitingBlock = 0;
2000 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2001 PI != E; ++PI)
2002 if (L->contains(*PI)) {
2003 if (ExitingBlock == 0)
2004 ExitingBlock = *PI;
2005 else
2006 return UnknownValue; // More than one block exiting!
2007 }
2008 assert(ExitingBlock && "No exits from loop, something is broken!");
2009
2010 // Okay, we've computed the exiting block. See what condition causes us to
2011 // exit.
2012 //
2013 // FIXME: we should be able to handle switch instructions (with a single exit)
2014 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2015 if (ExitBr == 0) return UnknownValue;
2016 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2017
2018 // At this point, we know we have a conditional branch that determines whether
2019 // the loop is exited. However, we don't know if the branch is executed each
2020 // time through the loop. If not, then the execution count of the branch will
2021 // not be equal to the trip count of the loop.
2022 //
2023 // Currently we check for this by checking to see if the Exit branch goes to
2024 // the loop header. If so, we know it will always execute the same number of
2025 // times as the loop. We also handle the case where the exit block *is* the
2026 // loop header. This is common for un-rotated loops. More extensive analysis
2027 // could be done to handle more cases here.
2028 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2029 ExitBr->getSuccessor(1) != L->getHeader() &&
2030 ExitBr->getParent() != L->getHeader())
2031 return UnknownValue;
2032
2033 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2034
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002035 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002036 // Note that ICmpInst deals with pointer comparisons too so we must check
2037 // the type of the operand.
2038 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002039 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002040 ExitBr->getSuccessor(0) == ExitBlock);
2041
2042 // If the condition was exit on true, convert the condition to exit on false
2043 ICmpInst::Predicate Cond;
2044 if (ExitBr->getSuccessor(1) == ExitBlock)
2045 Cond = ExitCond->getPredicate();
2046 else
2047 Cond = ExitCond->getInversePredicate();
2048
2049 // Handle common loops like: for (X = "string"; *X; ++X)
2050 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2051 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2052 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002053 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002054 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2055 }
2056
2057 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2058 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2059
2060 // Try to evaluate any dependencies out of the loop.
2061 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2062 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2063 Tmp = getSCEVAtScope(RHS, L);
2064 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2065
2066 // At this point, we would like to compute how many iterations of the
2067 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002068 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2069 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070 std::swap(LHS, RHS);
2071 Cond = ICmpInst::getSwappedPredicate(Cond);
2072 }
2073
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002074 // If we have a comparison of a chrec against a constant, try to use value
2075 // ranges to answer this query.
2076 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2077 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2078 if (AddRec->getLoop() == L) {
2079 // Form the comparison range using the constant of the correct type so
2080 // that the ConstantRange class knows to do a signed or unsigned
2081 // comparison.
2082 ConstantInt *CompVal = RHSC->getValue();
2083 const Type *RealTy = ExitCond->getOperand(0)->getType();
2084 CompVal = dyn_cast<ConstantInt>(
2085 ConstantExpr::getBitCast(CompVal, RealTy));
2086 if (CompVal) {
2087 // Form the constant range.
2088 ConstantRange CompRange(
2089 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2090
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002091 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2093 }
2094 }
2095
2096 switch (Cond) {
2097 case ICmpInst::ICMP_NE: { // while (X != Y)
2098 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002099 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2101 break;
2102 }
2103 case ICmpInst::ICMP_EQ: {
2104 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002105 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002106 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2107 break;
2108 }
2109 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002110 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002111 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2112 break;
2113 }
2114 case ICmpInst::ICMP_SGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002115 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2116 getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002117 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2118 break;
2119 }
2120 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002121 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002122 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2123 break;
2124 }
2125 case ICmpInst::ICMP_UGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002126 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2127 getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002128 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2129 break;
2130 }
2131 default:
2132#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002133 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002134 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002135 errs() << "[unsigned] ";
2136 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002137 << Instruction::getOpcodeName(Instruction::ICmp)
2138 << " " << *RHS << "\n";
2139#endif
2140 break;
2141 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002142 return
2143 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2144 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002145}
2146
2147static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002148EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2149 ScalarEvolution &SE) {
2150 SCEVHandle InVal = SE.getConstant(C);
2151 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002152 assert(isa<SCEVConstant>(Val) &&
2153 "Evaluation of SCEV at constant didn't fold correctly?");
2154 return cast<SCEVConstant>(Val)->getValue();
2155}
2156
2157/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2158/// and a GEP expression (missing the pointer index) indexing into it, return
2159/// the addressed element of the initializer or null if the index expression is
2160/// invalid.
2161static Constant *
2162GetAddressedElementFromGlobal(GlobalVariable *GV,
2163 const std::vector<ConstantInt*> &Indices) {
2164 Constant *Init = GV->getInitializer();
2165 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2166 uint64_t Idx = Indices[i]->getZExtValue();
2167 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2168 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2169 Init = cast<Constant>(CS->getOperand(Idx));
2170 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2171 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2172 Init = cast<Constant>(CA->getOperand(Idx));
2173 } else if (isa<ConstantAggregateZero>(Init)) {
2174 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2175 assert(Idx < STy->getNumElements() && "Bad struct index!");
2176 Init = Constant::getNullValue(STy->getElementType(Idx));
2177 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2178 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2179 Init = Constant::getNullValue(ATy->getElementType());
2180 } else {
2181 assert(0 && "Unknown constant aggregate type!");
2182 }
2183 return 0;
2184 } else {
2185 return 0; // Unknown initializer type
2186 }
2187 }
2188 return Init;
2189}
2190
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002191/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2192/// 'icmp op load X, cst', try to see if we can compute the backedge
2193/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002194SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002195ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2196 const Loop *L,
2197 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002198 if (LI->isVolatile()) return UnknownValue;
2199
2200 // Check to see if the loaded pointer is a getelementptr of a global.
2201 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2202 if (!GEP) return UnknownValue;
2203
2204 // Make sure that it is really a constant global we are gepping, with an
2205 // initializer, and make sure the first IDX is really 0.
2206 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2207 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2208 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2209 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2210 return UnknownValue;
2211
2212 // Okay, we allow one non-constant index into the GEP instruction.
2213 Value *VarIdx = 0;
2214 std::vector<ConstantInt*> Indexes;
2215 unsigned VarIdxNum = 0;
2216 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2217 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2218 Indexes.push_back(CI);
2219 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2220 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2221 VarIdx = GEP->getOperand(i);
2222 VarIdxNum = i-2;
2223 Indexes.push_back(0);
2224 }
2225
2226 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2227 // Check to see if X is a loop variant variable value now.
2228 SCEVHandle Idx = getSCEV(VarIdx);
2229 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2230 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2231
2232 // We can only recognize very limited forms of loop index expressions, in
2233 // particular, only affine AddRec's like {C1,+,C2}.
2234 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2235 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2236 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2237 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2238 return UnknownValue;
2239
2240 unsigned MaxSteps = MaxBruteForceIterations;
2241 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2242 ConstantInt *ItCst =
2243 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002244 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002245
2246 // Form the GEP offset.
2247 Indexes[VarIdxNum] = Val;
2248
2249 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2250 if (Result == 0) break; // Cannot compute!
2251
2252 // Evaluate the condition for this iteration.
2253 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2254 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2255 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2256#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002257 errs() << "\n***\n*** Computed loop count " << *ItCst
2258 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2259 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260#endif
2261 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002262 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 }
2264 }
2265 return UnknownValue;
2266}
2267
2268
2269/// CanConstantFold - Return true if we can constant fold an instruction of the
2270/// specified type, assuming that all operands were constants.
2271static bool CanConstantFold(const Instruction *I) {
2272 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2273 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2274 return true;
2275
2276 if (const CallInst *CI = dyn_cast<CallInst>(I))
2277 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002278 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279 return false;
2280}
2281
2282/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2283/// in the loop that V is derived from. We allow arbitrary operations along the
2284/// way, but the operands of an operation must either be constants or a value
2285/// derived from a constant PHI. If this expression does not fit with these
2286/// constraints, return null.
2287static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2288 // If this is not an instruction, or if this is an instruction outside of the
2289 // loop, it can't be derived from a loop PHI.
2290 Instruction *I = dyn_cast<Instruction>(V);
2291 if (I == 0 || !L->contains(I->getParent())) return 0;
2292
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002293 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002294 if (L->getHeader() == I->getParent())
2295 return PN;
2296 else
2297 // We don't currently keep track of the control flow needed to evaluate
2298 // PHIs, so we cannot handle PHIs inside of loops.
2299 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002300 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002301
2302 // If we won't be able to constant fold this expression even if the operands
2303 // are constants, return early.
2304 if (!CanConstantFold(I)) return 0;
2305
2306 // Otherwise, we can evaluate this instruction if all of its operands are
2307 // constant or derived from a PHI node themselves.
2308 PHINode *PHI = 0;
2309 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2310 if (!(isa<Constant>(I->getOperand(Op)) ||
2311 isa<GlobalValue>(I->getOperand(Op)))) {
2312 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2313 if (P == 0) return 0; // Not evolving from PHI
2314 if (PHI == 0)
2315 PHI = P;
2316 else if (PHI != P)
2317 return 0; // Evolving from multiple different PHIs.
2318 }
2319
2320 // This is a expression evolving from a constant PHI!
2321 return PHI;
2322}
2323
2324/// EvaluateExpression - Given an expression that passes the
2325/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2326/// in the loop has the value PHIVal. If we can't fold this expression for some
2327/// reason, return null.
2328static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2329 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002330 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002331 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002332 Instruction *I = cast<Instruction>(V);
2333
2334 std::vector<Constant*> Operands;
2335 Operands.resize(I->getNumOperands());
2336
2337 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2338 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2339 if (Operands[i] == 0) return 0;
2340 }
2341
Chris Lattnerd6e56912007-12-10 22:53:04 +00002342 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2343 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2344 &Operands[0], Operands.size());
2345 else
2346 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2347 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002348}
2349
2350/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2351/// in the header of its containing loop, we know the loop executes a
2352/// constant number of times, and the PHI node is just a recurrence
2353/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002354Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002355getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002356 std::map<PHINode*, Constant*>::iterator I =
2357 ConstantEvolutionLoopExitValue.find(PN);
2358 if (I != ConstantEvolutionLoopExitValue.end())
2359 return I->second;
2360
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002361 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002362 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2363
2364 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2365
2366 // Since the loop is canonicalized, the PHI node must have two entries. One
2367 // entry must be a constant (coming in from outside of the loop), and the
2368 // second must be derived from the same PHI.
2369 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2370 Constant *StartCST =
2371 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2372 if (StartCST == 0)
2373 return RetVal = 0; // Must be a constant.
2374
2375 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2376 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2377 if (PN2 != PN)
2378 return RetVal = 0; // Not derived from same PHI.
2379
2380 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002381 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002382 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2383
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002384 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002385 unsigned IterationNum = 0;
2386 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2387 if (IterationNum == NumIterations)
2388 return RetVal = PHIVal; // Got exit value!
2389
2390 // Compute the value of the PHI node for the next iteration.
2391 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2392 if (NextPHI == PHIVal)
2393 return RetVal = NextPHI; // Stopped evolving!
2394 if (NextPHI == 0)
2395 return 0; // Couldn't evaluate!
2396 PHIVal = NextPHI;
2397 }
2398}
2399
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002400/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002401/// constant number of times (the condition evolves only from constants),
2402/// try to evaluate a few iterations of the loop until we get the exit
2403/// condition gets a value of ExitWhen (true or false). If we cannot
2404/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002405SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002406ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002407 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2408 if (PN == 0) return UnknownValue;
2409
2410 // Since the loop is canonicalized, the PHI node must have two entries. One
2411 // entry must be a constant (coming in from outside of the loop), and the
2412 // second must be derived from the same PHI.
2413 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2414 Constant *StartCST =
2415 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2416 if (StartCST == 0) return UnknownValue; // Must be a constant.
2417
2418 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2419 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2420 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2421
2422 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2423 // the loop symbolically to determine when the condition gets a value of
2424 // "ExitWhen".
2425 unsigned IterationNum = 0;
2426 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2427 for (Constant *PHIVal = StartCST;
2428 IterationNum != MaxIterations; ++IterationNum) {
2429 ConstantInt *CondVal =
2430 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2431
2432 // Couldn't symbolically evaluate.
2433 if (!CondVal) return UnknownValue;
2434
2435 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2436 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2437 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002438 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002439 }
2440
2441 // Compute the value of the PHI node for the next iteration.
2442 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2443 if (NextPHI == 0 || NextPHI == PHIVal)
2444 return UnknownValue; // Couldn't evaluate or not making progress...
2445 PHIVal = NextPHI;
2446 }
2447
2448 // Too many iterations were needed to evaluate.
2449 return UnknownValue;
2450}
2451
2452/// getSCEVAtScope - Compute the value of the specified expression within the
2453/// indicated loop (which may be null to indicate in no loop). If the
2454/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002455SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002456 // FIXME: this should be turned into a virtual method on SCEV!
2457
2458 if (isa<SCEVConstant>(V)) return V;
2459
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002460 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002461 // exit value from the loop without using SCEVs.
2462 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2463 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002464 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2466 if (PHINode *PN = dyn_cast<PHINode>(I))
2467 if (PN->getParent() == LI->getHeader()) {
2468 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002469 // to see if the loop that contains it has a known backedge-taken
2470 // count. If so, we may be able to force computation of the exit
2471 // value.
2472 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2473 if (SCEVConstant *BTCC =
2474 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002475 // Okay, we know how many times the containing loop executes. If
2476 // this is a constant evolving PHI node, get the final value at
2477 // the specified iteration number.
2478 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002479 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002480 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002481 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002482 }
2483 }
2484
2485 // Okay, this is an expression that we cannot symbolically evaluate
2486 // into a SCEV. Check to see if it's possible to symbolically evaluate
2487 // the arguments into constants, and if so, try to constant propagate the
2488 // result. This is particularly useful for computing loop exit values.
2489 if (CanConstantFold(I)) {
2490 std::vector<Constant*> Operands;
2491 Operands.reserve(I->getNumOperands());
2492 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2493 Value *Op = I->getOperand(i);
2494 if (Constant *C = dyn_cast<Constant>(Op)) {
2495 Operands.push_back(C);
2496 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002497 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002498 // non-integer and non-pointer, don't even try to analyze them
2499 // with scev techniques.
2500 if (!isa<IntegerType>(Op->getType()) &&
2501 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002502 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002503
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2505 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2506 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2507 Op->getType(),
2508 false));
2509 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2510 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2511 Operands.push_back(ConstantExpr::getIntegerCast(C,
2512 Op->getType(),
2513 false));
2514 else
2515 return V;
2516 } else {
2517 return V;
2518 }
2519 }
2520 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002521
2522 Constant *C;
2523 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2524 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2525 &Operands[0], Operands.size());
2526 else
2527 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2528 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002529 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530 }
2531 }
2532
2533 // This is some other type of SCEVUnknown, just return it.
2534 return V;
2535 }
2536
2537 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2538 // Avoid performing the look-up in the common case where the specified
2539 // expression has no loop-variant portions.
2540 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2541 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2542 if (OpAtScope != Comm->getOperand(i)) {
2543 if (OpAtScope == UnknownValue) return UnknownValue;
2544 // Okay, at least one of these operands is loop variant but might be
2545 // foldable. Build a new instance of the folded commutative expression.
2546 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2547 NewOps.push_back(OpAtScope);
2548
2549 for (++i; i != e; ++i) {
2550 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2551 if (OpAtScope == UnknownValue) return UnknownValue;
2552 NewOps.push_back(OpAtScope);
2553 }
2554 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002555 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002556 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002557 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002558 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002559 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002560 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002561 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002562 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002563 }
2564 }
2565 // If we got here, all operands are loop invariant.
2566 return Comm;
2567 }
2568
Nick Lewycky35b56022009-01-13 09:18:58 +00002569 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2570 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002571 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002572 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002573 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002574 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2575 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002576 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002577 }
2578
2579 // If this is a loop recurrence for a loop that does not contain L, then we
2580 // are dealing with the final value computed by the loop.
2581 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2582 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2583 // To evaluate this recurrence, we need to know how many times the AddRec
2584 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002585 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2586 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002587
Eli Friedman7489ec92008-08-04 23:49:06 +00002588 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002589 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590 }
2591 return UnknownValue;
2592 }
2593
2594 //assert(0 && "Unknown SCEV type!");
2595 return UnknownValue;
2596}
2597
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002598/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2599/// at the specified scope in the program. The L value specifies a loop
2600/// nest to evaluate the expression at, where null is the top-level or a
2601/// specified loop is immediately inside of the loop.
2602///
2603/// This method can be used to compute the exit value for a variable defined
2604/// in a loop by querying what the value will hold in the parent loop.
2605///
2606/// If this value is not computable at this scope, a SCEVCouldNotCompute
2607/// object is returned.
2608SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2609 return getSCEVAtScope(getSCEV(V), L);
2610}
2611
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002612/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2613/// following equation:
2614///
2615/// A * X = B (mod N)
2616///
2617/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2618/// A and B isn't important.
2619///
2620/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2621static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2622 ScalarEvolution &SE) {
2623 uint32_t BW = A.getBitWidth();
2624 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2625 assert(A != 0 && "A must be non-zero.");
2626
2627 // 1. D = gcd(A, N)
2628 //
2629 // The gcd of A and N may have only one prime factor: 2. The number of
2630 // trailing zeros in A is its multiplicity
2631 uint32_t Mult2 = A.countTrailingZeros();
2632 // D = 2^Mult2
2633
2634 // 2. Check if B is divisible by D.
2635 //
2636 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2637 // is not less than multiplicity of this prime factor for D.
2638 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002639 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002640
2641 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2642 // modulo (N / D).
2643 //
2644 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2645 // bit width during computations.
2646 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2647 APInt Mod(BW + 1, 0);
2648 Mod.set(BW - Mult2); // Mod = N / D
2649 APInt I = AD.multiplicativeInverse(Mod);
2650
2651 // 4. Compute the minimum unsigned root of the equation:
2652 // I * (B / D) mod (N / D)
2653 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2654
2655 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2656 // bits.
2657 return SE.getConstant(Result.trunc(BW));
2658}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002659
2660/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2661/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2662/// might be the same) or two SCEVCouldNotCompute objects.
2663///
2664static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002665SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002666 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2667 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2668 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2669 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2670
2671 // We currently can only solve this if the coefficients are constants.
2672 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002673 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674 return std::make_pair(CNC, CNC);
2675 }
2676
2677 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2678 const APInt &L = LC->getValue()->getValue();
2679 const APInt &M = MC->getValue()->getValue();
2680 const APInt &N = NC->getValue()->getValue();
2681 APInt Two(BitWidth, 2);
2682 APInt Four(BitWidth, 4);
2683
2684 {
2685 using namespace APIntOps;
2686 const APInt& C = L;
2687 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2688 // The B coefficient is M-N/2
2689 APInt B(M);
2690 B -= sdiv(N,Two);
2691
2692 // The A coefficient is N/2
2693 APInt A(N.sdiv(Two));
2694
2695 // Compute the B^2-4ac term.
2696 APInt SqrtTerm(B);
2697 SqrtTerm *= B;
2698 SqrtTerm -= Four * (A * C);
2699
2700 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2701 // integer value or else APInt::sqrt() will assert.
2702 APInt SqrtVal(SqrtTerm.sqrt());
2703
2704 // Compute the two solutions for the quadratic formula.
2705 // The divisions must be performed as signed divisions.
2706 APInt NegB(-B);
2707 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002708 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002709 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002710 return std::make_pair(CNC, CNC);
2711 }
2712
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2714 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2715
Dan Gohman89f85052007-10-22 18:31:58 +00002716 return std::make_pair(SE.getConstant(Solution1),
2717 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002718 } // end APIntOps namespace
2719}
2720
2721/// HowFarToZero - Return the number of times a backedge comparing the specified
2722/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002723SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002724 // If the value is a constant
2725 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2726 // If the value is already zero, the branch will execute zero times.
2727 if (C->getValue()->isZero()) return C;
2728 return UnknownValue; // Otherwise it will loop infinitely.
2729 }
2730
2731 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2732 if (!AddRec || AddRec->getLoop() != L)
2733 return UnknownValue;
2734
2735 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002736 // If this is an affine expression, the execution count of this branch is
2737 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002738 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002739 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002740 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002741 // equivalent to:
2742 //
2743 // Step*N = -Start (mod 2^BW)
2744 //
2745 // where BW is the common bit width of Start and Step.
2746
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002747 // Get the initial value for the loop.
2748 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2749 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002750
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002751 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002754 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002756 // First, handle unitary steps.
2757 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002758 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002759 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2760 return Start; // N = Start (as unsigned)
2761
2762 // Then, try to solve the above equation provided that Start is constant.
2763 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2764 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002765 -StartC->getValue()->getValue(),
2766 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002767 }
2768 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2769 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2770 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002771 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2772 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002773 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2774 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2775 if (R1) {
2776#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002777 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2778 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779#endif
2780 // Pick the smallest positive root value.
2781 if (ConstantInt *CB =
2782 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2783 R1->getValue(), R2->getValue()))) {
2784 if (CB->getZExtValue() == false)
2785 std::swap(R1, R2); // R1 is the minimum root now.
2786
2787 // We can only use this value if the chrec ends up with an exact zero
2788 // value at this index. When solving for "X*X != 5", for example, we
2789 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002790 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002791 if (Val->isZero())
2792 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002793 }
2794 }
2795 }
2796
2797 return UnknownValue;
2798}
2799
2800/// HowFarToNonZero - Return the number of times a backedge checking the
2801/// specified value for nonzero will execute. If not computable, return
2802/// UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002803SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804 // Loops that look like: while (X == 0) are very strange indeed. We don't
2805 // handle them yet except for the trivial case. This could be expanded in the
2806 // future as needed.
2807
2808 // If the value is a constant, check to see if it is known to be non-zero
2809 // already. If so, the backedge will execute zero times.
2810 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002811 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002812 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813 return UnknownValue; // Otherwise it will loop infinitely.
2814 }
2815
2816 // We could implement others, but I really doubt anyone writes loops like
2817 // this, and if they did, they would already be constant folded.
2818 return UnknownValue;
2819}
2820
Dan Gohman1cddf972008-09-15 22:18:04 +00002821/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2822/// (which may not be an immediate predecessor) which has exactly one
2823/// successor from which BB is reachable, or null if no such block is
2824/// found.
2825///
2826BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002827ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1cddf972008-09-15 22:18:04 +00002828 // If the block has a unique predecessor, the predecessor must have
2829 // no other successors from which BB is reachable.
2830 if (BasicBlock *Pred = BB->getSinglePredecessor())
2831 return Pred;
2832
2833 // A loop's header is defined to be a block that dominates the loop.
2834 // If the loop has a preheader, it must be a block that has exactly
2835 // one successor that can reach BB. This is slightly more strict
2836 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002837 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00002838 return L->getLoopPreheader();
2839
2840 return 0;
2841}
2842
Dan Gohmancacd2012009-02-12 22:19:27 +00002843/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002844/// a conditional between LHS and RHS.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002845bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohmancacd2012009-02-12 22:19:27 +00002846 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002847 SCEV *LHS, SCEV *RHS) {
2848 BasicBlock *Preheader = L->getLoopPreheader();
2849 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002850
Dan Gohmanab678fb2008-08-12 20:17:31 +00002851 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002852 // there are predecessors that can be found that have unique successors
2853 // leading to the original header.
2854 for (; Preheader;
2855 PreheaderDest = Preheader,
2856 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002857
2858 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002859 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002860 if (!LoopEntryPredicate ||
2861 LoopEntryPredicate->isUnconditional())
2862 continue;
2863
2864 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2865 if (!ICI) continue;
2866
2867 // Now that we found a conditional branch that dominates the loop, check to
2868 // see if it is the comparison we are looking for.
2869 Value *PreCondLHS = ICI->getOperand(0);
2870 Value *PreCondRHS = ICI->getOperand(1);
2871 ICmpInst::Predicate Cond;
2872 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2873 Cond = ICI->getPredicate();
2874 else
2875 Cond = ICI->getInversePredicate();
2876
Dan Gohmancacd2012009-02-12 22:19:27 +00002877 if (Cond == Pred)
2878 ; // An exact match.
2879 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2880 ; // The actual condition is beyond sufficient.
2881 else
2882 // Check a few special cases.
2883 switch (Cond) {
2884 case ICmpInst::ICMP_UGT:
2885 if (Pred == ICmpInst::ICMP_ULT) {
2886 std::swap(PreCondLHS, PreCondRHS);
2887 Cond = ICmpInst::ICMP_ULT;
2888 break;
2889 }
2890 continue;
2891 case ICmpInst::ICMP_SGT:
2892 if (Pred == ICmpInst::ICMP_SLT) {
2893 std::swap(PreCondLHS, PreCondRHS);
2894 Cond = ICmpInst::ICMP_SLT;
2895 break;
2896 }
2897 continue;
2898 case ICmpInst::ICMP_NE:
2899 // Expressions like (x >u 0) are often canonicalized to (x != 0),
2900 // so check for this case by checking if the NE is comparing against
2901 // a minimum or maximum constant.
2902 if (!ICmpInst::isTrueWhenEqual(Pred))
2903 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2904 const APInt &A = CI->getValue();
2905 switch (Pred) {
2906 case ICmpInst::ICMP_SLT:
2907 if (A.isMaxSignedValue()) break;
2908 continue;
2909 case ICmpInst::ICMP_SGT:
2910 if (A.isMinSignedValue()) break;
2911 continue;
2912 case ICmpInst::ICMP_ULT:
2913 if (A.isMaxValue()) break;
2914 continue;
2915 case ICmpInst::ICMP_UGT:
2916 if (A.isMinValue()) break;
2917 continue;
2918 default:
2919 continue;
2920 }
2921 Cond = ICmpInst::ICMP_NE;
2922 // NE is symmetric but the original comparison may not be. Swap
2923 // the operands if necessary so that they match below.
2924 if (isa<SCEVConstant>(LHS))
2925 std::swap(PreCondLHS, PreCondRHS);
2926 break;
2927 }
2928 continue;
2929 default:
2930 // We weren't able to reconcile the condition.
2931 continue;
2932 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00002933
2934 if (!PreCondLHS->getType()->isInteger()) continue;
2935
2936 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2937 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2938 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002939 (LHS == getNotSCEV(PreCondRHSSCEV) &&
2940 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00002941 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002942 }
2943
Dan Gohmanab678fb2008-08-12 20:17:31 +00002944 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002945}
2946
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002947/// HowManyLessThans - Return the number of times a backedge containing the
2948/// specified less-than comparison will execute. If not computable, return
2949/// UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002950SCEVHandle ScalarEvolution::
Nick Lewycky35b56022009-01-13 09:18:58 +00002951HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952 // Only handle: "ADDREC < LoopInvariant".
2953 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2954
2955 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2956 if (!AddRec || AddRec->getLoop() != L)
2957 return UnknownValue;
2958
2959 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002960 // FORNOW: We only support unit strides.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002961 SCEVHandle One = getIntegerSCEV(1, RHS->getType());
Nick Lewycky35b56022009-01-13 09:18:58 +00002962 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002963 return UnknownValue;
2964
Nick Lewycky35b56022009-01-13 09:18:58 +00002965 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2966 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2967 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00002968 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002970 // First, we get the value of the LHS in the first iteration: n
2971 SCEVHandle Start = AddRec->getOperand(0);
2972
Dan Gohmancacd2012009-02-12 22:19:27 +00002973 if (isLoopGuardedByCond(L,
2974 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002975 getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002976 // Since we know that the condition is true in order to enter the loop,
2977 // we know that it will run exactly m-n times.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002978 return getMinusSCEV(RHS, Start);
Nick Lewycky35b56022009-01-13 09:18:58 +00002979 } else {
2980 // Then, we get the value of the LHS in the first iteration in which the
2981 // above condition doesn't hold. This equals to max(m,n).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002982 SCEVHandle End = isSigned ? getSMaxExpr(RHS, Start)
2983 : getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002984
Nick Lewycky35b56022009-01-13 09:18:58 +00002985 // Finally, we subtract these two values to get the number of times the
2986 // backedge is executed: max(m,n)-n.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002987 return getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00002988 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002989 }
2990
2991 return UnknownValue;
2992}
2993
2994/// getNumIterationsInRange - Return the number of iterations of this loop that
2995/// produce values in the specified constant range. Another way of looking at
2996/// this is that it returns the first iteration number where the value is not in
2997/// the condition, thus computing the exit count. If the iteration count can't
2998/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00002999SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3000 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003001 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003002 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003
3004 // If the start is a non-zero constant, shift the range to simplify things.
3005 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3006 if (!SC->getValue()->isZero()) {
3007 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003008 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3009 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3011 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003012 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003014 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003015 }
3016
3017 // The only time we can solve this is when we have all constant indices.
3018 // Otherwise, we cannot determine the overflow conditions.
3019 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3020 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003021 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003022
3023
3024 // Okay at this point we know that all elements of the chrec are constants and
3025 // that the start element is zero.
3026
3027 // First check to see if the range contains zero. If not, the first
3028 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003029 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003030 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003031 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003032
3033 if (isAffine()) {
3034 // If this is an affine expression then we have this situation:
3035 // Solve {0,+,A} in Range === Ax in Range
3036
3037 // We know that zero is in the range. If A is positive then we know that
3038 // the upper value of the range must be the first possible exit value.
3039 // If A is negative then the lower of the range is the last possible loop
3040 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003041 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003042 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3043 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3044
3045 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003046 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3048
3049 // Evaluate at the exit value. If we really did fall out of the valid
3050 // range, then we computed our trip count, otherwise wrap around or other
3051 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003052 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003053 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003054 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003055
3056 // Ensure that the previous value is in the range. This is a sanity check.
3057 assert(Range.contains(
3058 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003059 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003060 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003061 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003062 } else if (isQuadratic()) {
3063 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3064 // quadratic equation to solve it. To do this, we must frame our problem in
3065 // terms of figuring out when zero is crossed, instead of when
3066 // Range.getUpper() is crossed.
3067 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003068 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3069 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003070
3071 // Next, solve the constructed addrec
3072 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003073 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003074 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3075 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3076 if (R1) {
3077 // Pick the smallest positive root value.
3078 if (ConstantInt *CB =
3079 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3080 R1->getValue(), R2->getValue()))) {
3081 if (CB->getZExtValue() == false)
3082 std::swap(R1, R2); // R1 is the minimum root now.
3083
3084 // Make sure the root is not off by one. The returned iteration should
3085 // not be in the range, but the previous one should be. When solving
3086 // for "X*X < 5", for example, we should not return a root of 2.
3087 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003088 R1->getValue(),
3089 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003090 if (Range.contains(R1Val->getValue())) {
3091 // The next iteration must be out of the range...
3092 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3093
Dan Gohman89f85052007-10-22 18:31:58 +00003094 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003096 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003097 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003098 }
3099
3100 // If R1 was not in the range, then it is a good return value. Make
3101 // sure that R1-1 WAS in the range though, just in case.
3102 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003103 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003104 if (Range.contains(R1Val->getValue()))
3105 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003106 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 }
3108 }
3109 }
3110
Dan Gohman0ad08b02009-04-18 17:58:19 +00003111 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003112}
3113
3114
3115
3116//===----------------------------------------------------------------------===//
3117// ScalarEvolution Class Implementation
3118//===----------------------------------------------------------------------===//
3119
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003120ScalarEvolution::ScalarEvolution()
3121 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3122}
3123
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003124bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003125 this->F = &F;
3126 LI = &getAnalysis<LoopInfo>();
3127 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128 return false;
3129}
3130
3131void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003132 Scalars.clear();
3133 BackedgeTakenCounts.clear();
3134 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003135}
3136
3137void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3138 AU.setPreservesAll();
3139 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003140}
3141
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003142bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003143 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003144}
3145
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003146static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 const Loop *L) {
3148 // Print all inner loops first
3149 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3150 PrintLoopInfo(OS, SE, *I);
3151
Nick Lewyckye5da1912008-01-02 02:49:20 +00003152 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003153
Devang Patel02451fa2007-08-21 00:31:24 +00003154 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 L->getExitBlocks(ExitBlocks);
3156 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003157 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003158
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003159 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3160 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003162 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003163 }
3164
Nick Lewyckye5da1912008-01-02 02:49:20 +00003165 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003166}
3167
Dan Gohman13058cc2009-04-21 00:47:46 +00003168void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003169 // ScalarEvolution's implementaiton of the print method is to print
3170 // out SCEV values of all instructions that are interesting. Doing
3171 // this potentially causes it to create new SCEV objects though,
3172 // which technically conflicts with the const qualifier. This isn't
3173 // observable from outside the class though (the hasSCEV function
3174 // notwithstanding), so casting away the const isn't dangerous.
3175 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003177 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003178 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3179 if (I->getType()->isInteger()) {
3180 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003181 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003182 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003183 SV->print(OS);
3184 OS << "\t\t";
3185
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003186 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003187 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003188 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003189 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3190 OS << "<<Unknown>>";
3191 } else {
3192 OS << *ExitValue;
3193 }
3194 }
3195
3196
3197 OS << "\n";
3198 }
3199
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003200 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3201 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3202 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203}
Dan Gohman13058cc2009-04-21 00:47:46 +00003204
3205void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3206 raw_os_ostream OS(o);
3207 print(OS, M);
3208}