blob: 27158e5dddeb01718cd1d8d5681aac2062fd0ecc [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
69#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
73#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
77#include "llvm/Support/ManagedStatic.h"
78#include "llvm/Support/MathExtras.h"
79#include "llvm/Support/Streams.h"
80#include "llvm/ADT/Statistic.h"
81#include <ostream>
82#include <algorithm>
83#include <cmath>
84using namespace llvm;
85
86STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
98cl::opt<unsigned>
99MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
104namespace {
105 RegisterPass<ScalarEvolution>
106 R("scalar-evolution", "Scalar Evolution Analysis");
107}
108char ScalarEvolution::ID = 0;
109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
117SCEV::~SCEV() {}
118void SCEV::dump() const {
119 print(cerr);
120}
121
122/// getValueRange - Return the tightest constant bounds that this value is
123/// known to have. This method is only valid on integer SCEV objects.
124ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
127 // Default to a full range if no better information is available.
128 return ConstantRange(getBitWidth());
129}
130
131uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
134 return 0;
135}
136
137
138SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142 return false;
143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 return 0;
148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
155SCEVHandle SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 return this;
160}
161
162void SCEVCouldNotCompute::print(std::ostream &OS) const {
163 OS << "***COULDNOTCOMPUTE***";
164}
165
166bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
168}
169
170
171// SCEVConstants - Only allow the creation of one SCEVConstant for any
172// particular value. Don't use a SCEVHandle here, or else the object will
173// never be deleted!
174static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
175
176
177SCEVConstant::~SCEVConstant() {
178 SCEVConstants->erase(V);
179}
180
Dan Gohman89f85052007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 SCEVConstant *&R = (*SCEVConstants)[V];
183 if (R == 0) R = new SCEVConstant(V);
184 return R;
185}
186
Dan Gohman89f85052007-10-22 18:31:58 +0000187SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
188 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189}
190
191ConstantRange SCEVConstant::getValueRange() const {
192 return ConstantRange(V->getValue());
193}
194
195const Type *SCEVConstant::getType() const { return V->getType(); }
196
197void SCEVConstant::print(std::ostream &OS) const {
198 WriteAsOperand(OS, V, false);
199}
200
201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
204static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
205 SCEVTruncateExpr*> > SCEVTruncates;
206
207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
208 : SCEV(scTruncate), Op(op), Ty(ty) {
209 assert(Op->getType()->isInteger() && Ty->isInteger() &&
210 "Cannot truncate non-integer value!");
211 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
212 && "This is not a truncating conversion!");
213}
214
215SCEVTruncateExpr::~SCEVTruncateExpr() {
216 SCEVTruncates->erase(std::make_pair(Op, Ty));
217}
218
219ConstantRange SCEVTruncateExpr::getValueRange() const {
220 return getOperand()->getValueRange().truncate(getBitWidth());
221}
222
223void SCEVTruncateExpr::print(std::ostream &OS) const {
224 OS << "(truncate " << *Op << " to " << *Ty << ")";
225}
226
227// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
228// particular input. Don't use a SCEVHandle here, or else the object will never
229// be deleted!
230static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
232
233SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
234 : SCEV(scZeroExtend), Op(op), Ty(ty) {
235 assert(Op->getType()->isInteger() && Ty->isInteger() &&
236 "Cannot zero extend non-integer value!");
237 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
238 && "This is not an extending conversion!");
239}
240
241SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
242 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
243}
244
245ConstantRange SCEVZeroExtendExpr::getValueRange() const {
246 return getOperand()->getValueRange().zeroExtend(getBitWidth());
247}
248
249void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
251}
252
253// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254// particular input. Don't use a SCEVHandle here, or else the object will never
255// be deleted!
256static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
257 SCEVSignExtendExpr*> > SCEVSignExtends;
258
259SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
260 : SCEV(scSignExtend), Op(op), Ty(ty) {
261 assert(Op->getType()->isInteger() && Ty->isInteger() &&
262 "Cannot sign extend non-integer value!");
263 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
264 && "This is not an extending conversion!");
265}
266
267SCEVSignExtendExpr::~SCEVSignExtendExpr() {
268 SCEVSignExtends->erase(std::make_pair(Op, Ty));
269}
270
271ConstantRange SCEVSignExtendExpr::getValueRange() const {
272 return getOperand()->getValueRange().signExtend(getBitWidth());
273}
274
275void SCEVSignExtendExpr::print(std::ostream &OS) const {
276 OS << "(signextend " << *Op << " to " << *Ty << ")";
277}
278
279// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
280// particular input. Don't use a SCEVHandle here, or else the object will never
281// be deleted!
282static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
283 SCEVCommutativeExpr*> > SCEVCommExprs;
284
285SCEVCommutativeExpr::~SCEVCommutativeExpr() {
286 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
287 std::vector<SCEV*>(Operands.begin(),
288 Operands.end())));
289}
290
291void SCEVCommutativeExpr::print(std::ostream &OS) const {
292 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
293 const char *OpStr = getOperationStr();
294 OS << "(" << *Operands[0];
295 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
296 OS << OpStr << *Operands[i];
297 OS << ")";
298}
299
300SCEVHandle SCEVCommutativeExpr::
301replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000302 const SCEVHandle &Conc,
303 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000305 SCEVHandle H =
306 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 if (H != getOperand(i)) {
308 std::vector<SCEVHandle> NewOps;
309 NewOps.reserve(getNumOperands());
310 for (unsigned j = 0; j != i; ++j)
311 NewOps.push_back(getOperand(j));
312 NewOps.push_back(H);
313 for (++i; i != e; ++i)
314 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000315 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316
317 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000318 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000320 return SE.getMulExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 else
322 assert(0 && "Unknown commutative expr!");
323 }
324 }
325 return this;
326}
327
328
329// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
333 SCEVSDivExpr*> > SCEVSDivs;
334
335SCEVSDivExpr::~SCEVSDivExpr() {
336 SCEVSDivs->erase(std::make_pair(LHS, RHS));
337}
338
339void SCEVSDivExpr::print(std::ostream &OS) const {
340 OS << "(" << *LHS << " /s " << *RHS << ")";
341}
342
343const Type *SCEVSDivExpr::getType() const {
344 return LHS->getType();
345}
346
347// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
348// particular input. Don't use a SCEVHandle here, or else the object will never
349// be deleted!
350static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
351 SCEVAddRecExpr*> > SCEVAddRecExprs;
352
353SCEVAddRecExpr::~SCEVAddRecExpr() {
354 SCEVAddRecExprs->erase(std::make_pair(L,
355 std::vector<SCEV*>(Operands.begin(),
356 Operands.end())));
357}
358
359SCEVHandle SCEVAddRecExpr::
360replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000361 const SCEVHandle &Conc,
362 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000364 SCEVHandle H =
365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 if (H != getOperand(i)) {
367 std::vector<SCEVHandle> NewOps;
368 NewOps.reserve(getNumOperands());
369 for (unsigned j = 0; j != i; ++j)
370 NewOps.push_back(getOperand(j));
371 NewOps.push_back(H);
372 for (++i; i != e; ++i)
373 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375
Dan Gohman89f85052007-10-22 18:31:58 +0000376 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 }
378 }
379 return this;
380}
381
382
383bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
385 // contain L and if the start is invariant.
386 return !QueryLoop->contains(L->getHeader()) &&
387 getOperand(0)->isLoopInvariant(QueryLoop);
388}
389
390
391void SCEVAddRecExpr::print(std::ostream &OS) const {
392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
396}
397
398// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
399// value. Don't use a SCEVHandle here, or else the object will never be
400// deleted!
401static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
402
403SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
404
405bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return !L->contains(I->getParent());
410 return true;
411}
412
413const Type *SCEVUnknown::getType() const {
414 return V->getType();
415}
416
417void SCEVUnknown::print(std::ostream &OS) const {
418 WriteAsOperand(OS, V, false);
419}
420
421//===----------------------------------------------------------------------===//
422// SCEV Utilities
423//===----------------------------------------------------------------------===//
424
425namespace {
426 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
427 /// than the complexity of the RHS. This comparator is used to canonicalize
428 /// expressions.
429 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
430 bool operator()(SCEV *LHS, SCEV *RHS) {
431 return LHS->getSCEVType() < RHS->getSCEVType();
432 }
433 };
434}
435
436/// GroupByComplexity - Given a list of SCEV objects, order them by their
437/// complexity, and group objects of the same complexity together by value.
438/// When this routine is finished, we know that any duplicates in the vector are
439/// consecutive and that complexity is monotonically increasing.
440///
441/// Note that we go take special precautions to ensure that we get determinstic
442/// results from this routine. In other words, we don't want the results of
443/// this to depend on where the addresses of various SCEV objects happened to
444/// land in memory.
445///
446static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
447 if (Ops.size() < 2) return; // Noop
448 if (Ops.size() == 2) {
449 // This is the common case, which also happens to be trivially simple.
450 // Special case it.
451 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
452 std::swap(Ops[0], Ops[1]);
453 return;
454 }
455
456 // Do the rough sort by complexity.
457 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
458
459 // Now that we are sorted by complexity, group elements of the same
460 // complexity. Note that this is, at worst, N^2, but the vector is likely to
461 // be extremely short in practice. Note that we take this approach because we
462 // do not want to depend on the addresses of the objects we are grouping.
463 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
464 SCEV *S = Ops[i];
465 unsigned Complexity = S->getSCEVType();
466
467 // If there are any objects of the same complexity and same value as this
468 // one, group them.
469 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
470 if (Ops[j] == S) { // Found a duplicate.
471 // Move it to immediately after i'th element.
472 std::swap(Ops[i+1], Ops[j]);
473 ++i; // no need to rescan it.
474 if (i == e-2) return; // Done!
475 }
476 }
477 }
478}
479
480
481
482//===----------------------------------------------------------------------===//
483// Simple SCEV method implementations
484//===----------------------------------------------------------------------===//
485
486/// getIntegerSCEV - Given an integer or FP type, create a constant for the
487/// specified signed integer value and return a SCEV for the constant.
Dan Gohman89f85052007-10-22 18:31:58 +0000488SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 Constant *C;
490 if (Val == 0)
491 C = Constant::getNullValue(Ty);
492 else if (Ty->isFloatingPoint())
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000493 C = ConstantFP::get(Ty, APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
494 APFloat::IEEEdouble, Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 else
496 C = ConstantInt::get(Ty, Val);
Dan Gohman89f85052007-10-22 18:31:58 +0000497 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498}
499
500/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
501/// input value to the specified type. If the type must be extended, it is zero
502/// extended.
Dan Gohman89f85052007-10-22 18:31:58 +0000503static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty,
504 ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 const Type *SrcTy = V->getType();
506 assert(SrcTy->isInteger() && Ty->isInteger() &&
507 "Cannot truncate or zero extend with non-integer arguments!");
508 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
509 return V; // No conversion
510 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Dan Gohman89f85052007-10-22 18:31:58 +0000511 return SE.getTruncateExpr(V, Ty);
512 return SE.getZeroExtendExpr(V, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513}
514
515/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
516///
Dan Gohman89f85052007-10-22 18:31:58 +0000517SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman89f85052007-10-22 18:31:58 +0000519 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520
Dan Gohman89f85052007-10-22 18:31:58 +0000521 return getMulExpr(V, getIntegerSCEV(-1, V->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522}
523
524/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
525///
Dan Gohman89f85052007-10-22 18:31:58 +0000526SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
527 const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 // X - Y --> X + -Y
Dan Gohman89f85052007-10-22 18:31:58 +0000529 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530}
531
532
533/// PartialFact - Compute V!/(V-NumSteps)!
Dan Gohman89f85052007-10-22 18:31:58 +0000534static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps,
535 ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 // Handle this case efficiently, it is common to have constant iteration
537 // counts while computing loop exit values.
538 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
539 const APInt& Val = SC->getValue()->getValue();
540 APInt Result(Val.getBitWidth(), 1);
541 for (; NumSteps; --NumSteps)
542 Result *= Val-(NumSteps-1);
Dan Gohman89f85052007-10-22 18:31:58 +0000543 return SE.getConstant(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 }
545
546 const Type *Ty = V->getType();
547 if (NumSteps == 0)
Dan Gohman89f85052007-10-22 18:31:58 +0000548 return SE.getIntegerSCEV(1, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549
550 SCEVHandle Result = V;
551 for (unsigned i = 1; i != NumSteps; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +0000552 Result = SE.getMulExpr(Result, SE.getMinusSCEV(V,
553 SE.getIntegerSCEV(i, Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 return Result;
555}
556
557
558/// evaluateAtIteration - Return the value of this chain of recurrences at
559/// the specified iteration number. We can evaluate this recurrence by
560/// multiplying each element in the chain by the binomial coefficient
561/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
562///
563/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
564///
565/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
566/// Is the binomial equation safe using modular arithmetic??
567///
Dan Gohman89f85052007-10-22 18:31:58 +0000568SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
569 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000570 SCEVHandle Result = getStart();
571 int Divisor = 1;
572 const Type *Ty = It->getType();
573 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000574 SCEVHandle BC = PartialFact(It, i, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 Divisor *= i;
Anton Korobeynikoveb61bf52007-11-15 18:33:16 +0000576 SCEVHandle Val = SE.getSDivExpr(SE.getMulExpr(BC, getOperand(i)),
Dan Gohman89f85052007-10-22 18:31:58 +0000577 SE.getIntegerSCEV(Divisor,Ty));
578 Result = SE.getAddExpr(Result, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 }
580 return Result;
581}
582
583
584//===----------------------------------------------------------------------===//
585// SCEV Expression folder implementations
586//===----------------------------------------------------------------------===//
587
Dan Gohman89f85052007-10-22 18:31:58 +0000588SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000590 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591 ConstantExpr::getTrunc(SC->getValue(), Ty));
592
593 // If the input value is a chrec scev made out of constants, truncate
594 // all of the constants.
595 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
596 std::vector<SCEVHandle> Operands;
597 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
598 // FIXME: This should allow truncation of other expression types!
599 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000600 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 else
602 break;
603 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000604 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 }
606
607 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
608 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
609 return Result;
610}
611
Dan Gohman89f85052007-10-22 18:31:58 +0000612SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000614 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615 ConstantExpr::getZExt(SC->getValue(), Ty));
616
617 // FIXME: If the input value is a chrec scev, and we can prove that the value
618 // did not overflow the old, smaller, value, we can zero extend all of the
619 // operands (often constants). This would allow analysis of something like
620 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
621
622 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
623 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
624 return Result;
625}
626
Dan Gohman89f85052007-10-22 18:31:58 +0000627SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000629 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 ConstantExpr::getSExt(SC->getValue(), Ty));
631
632 // FIXME: If the input value is a chrec scev, and we can prove that the value
633 // did not overflow the old, smaller, value, we can sign extend all of the
634 // operands (often constants). This would allow analysis of something like
635 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
636
637 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
638 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
639 return Result;
640}
641
642// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000643SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 assert(!Ops.empty() && "Cannot get empty add!");
645 if (Ops.size() == 1) return Ops[0];
646
647 // Sort by complexity, this groups all similar expression types together.
648 GroupByComplexity(Ops);
649
650 // If there are any constants, fold them together.
651 unsigned Idx = 0;
652 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
653 ++Idx;
654 assert(Idx < Ops.size());
655 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
656 // We found two constants, fold them together!
657 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
658 RHSC->getValue()->getValue());
659 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000660 Ops[0] = getConstant(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 Ops.erase(Ops.begin()+1); // Erase the folded element
662 if (Ops.size() == 1) return Ops[0];
663 LHSC = cast<SCEVConstant>(Ops[0]);
664 } else {
665 // If we couldn't fold the expression, move to the next constant. Note
666 // that this is impossible to happen in practice because we always
667 // constant fold constant ints to constant ints.
668 ++Idx;
669 }
670 }
671
672 // If we are left with a constant zero being added, strip it off.
673 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
674 Ops.erase(Ops.begin());
675 --Idx;
676 }
677 }
678
679 if (Ops.size() == 1) return Ops[0];
680
681 // Okay, check to see if the same value occurs in the operand list twice. If
682 // so, merge them together into an multiply expression. Since we sorted the
683 // list, these values are required to be adjacent.
684 const Type *Ty = Ops[0]->getType();
685 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
686 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
687 // Found a match, merge the two values into a multiply, and add any
688 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000689 SCEVHandle Two = getIntegerSCEV(2, Ty);
690 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 if (Ops.size() == 2)
692 return Mul;
693 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
694 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000695 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 }
697
698 // Now we know the first non-constant operand. Skip past any cast SCEVs.
699 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
700 ++Idx;
701
702 // If there are add operands they would be next.
703 if (Idx < Ops.size()) {
704 bool DeletedAdd = false;
705 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
706 // If we have an add, expand the add operands onto the end of the operands
707 // list.
708 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
709 Ops.erase(Ops.begin()+Idx);
710 DeletedAdd = true;
711 }
712
713 // If we deleted at least one add, we added operands to the end of the list,
714 // and they are not necessarily sorted. Recurse to resort and resimplify
715 // any operands we just aquired.
716 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000717 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 }
719
720 // Skip over the add expression until we get to a multiply.
721 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
722 ++Idx;
723
724 // If we are adding something to a multiply expression, make sure the
725 // something is not already an operand of the multiply. If so, merge it into
726 // the multiply.
727 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
728 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
729 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
730 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
731 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
732 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
733 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
734 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
735 if (Mul->getNumOperands() != 2) {
736 // If the multiply has more than two operands, we must get the
737 // Y*Z term.
738 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
739 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000740 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 }
Dan Gohman89f85052007-10-22 18:31:58 +0000742 SCEVHandle One = getIntegerSCEV(1, Ty);
743 SCEVHandle AddOne = getAddExpr(InnerMul, One);
744 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 if (Ops.size() == 2) return OuterMul;
746 if (AddOp < Idx) {
747 Ops.erase(Ops.begin()+AddOp);
748 Ops.erase(Ops.begin()+Idx-1);
749 } else {
750 Ops.erase(Ops.begin()+Idx);
751 Ops.erase(Ops.begin()+AddOp-1);
752 }
753 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000754 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755 }
756
757 // Check this multiply against other multiplies being added together.
758 for (unsigned OtherMulIdx = Idx+1;
759 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
760 ++OtherMulIdx) {
761 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
762 // If MulOp occurs in OtherMul, we can fold the two multiplies
763 // together.
764 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
765 OMulOp != e; ++OMulOp)
766 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
767 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
768 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
769 if (Mul->getNumOperands() != 2) {
770 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
771 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000772 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 }
774 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
775 if (OtherMul->getNumOperands() != 2) {
776 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
777 OtherMul->op_end());
778 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000779 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 }
Dan Gohman89f85052007-10-22 18:31:58 +0000781 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
782 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 if (Ops.size() == 2) return OuterMul;
784 Ops.erase(Ops.begin()+Idx);
785 Ops.erase(Ops.begin()+OtherMulIdx-1);
786 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000787 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 }
789 }
790 }
791 }
792
793 // If there are any add recurrences in the operands list, see if any other
794 // added values are loop invariant. If so, we can fold them into the
795 // recurrence.
796 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
797 ++Idx;
798
799 // Scan over all recurrences, trying to fold loop invariants into them.
800 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
801 // Scan all of the other operands to this add and add them to the vector if
802 // they are loop invariant w.r.t. the recurrence.
803 std::vector<SCEVHandle> LIOps;
804 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
805 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
806 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
807 LIOps.push_back(Ops[i]);
808 Ops.erase(Ops.begin()+i);
809 --i; --e;
810 }
811
812 // If we found some loop invariants, fold them into the recurrence.
813 if (!LIOps.empty()) {
814 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
815 LIOps.push_back(AddRec->getStart());
816
817 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000818 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819
Dan Gohman89f85052007-10-22 18:31:58 +0000820 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 // If all of the other operands were loop invariant, we are done.
822 if (Ops.size() == 1) return NewRec;
823
824 // Otherwise, add the folded AddRec by the non-liv parts.
825 for (unsigned i = 0;; ++i)
826 if (Ops[i] == AddRec) {
827 Ops[i] = NewRec;
828 break;
829 }
Dan Gohman89f85052007-10-22 18:31:58 +0000830 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 }
832
833 // Okay, if there weren't any loop invariants to be folded, check to see if
834 // there are multiple AddRec's with the same loop induction variable being
835 // added together. If so, we can fold them.
836 for (unsigned OtherIdx = Idx+1;
837 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
838 if (OtherIdx != Idx) {
839 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
840 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
841 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
842 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
843 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
844 if (i >= NewOps.size()) {
845 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
846 OtherAddRec->op_end());
847 break;
848 }
Dan Gohman89f85052007-10-22 18:31:58 +0000849 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 }
Dan Gohman89f85052007-10-22 18:31:58 +0000851 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852
853 if (Ops.size() == 2) return NewAddRec;
854
855 Ops.erase(Ops.begin()+Idx);
856 Ops.erase(Ops.begin()+OtherIdx-1);
857 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000858 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859 }
860 }
861
862 // Otherwise couldn't fold anything into this recurrence. Move onto the
863 // next one.
864 }
865
866 // Okay, it looks like we really DO need an add expr. Check to see if we
867 // already have one, otherwise create a new one.
868 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
869 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
870 SCEVOps)];
871 if (Result == 0) Result = new SCEVAddExpr(Ops);
872 return Result;
873}
874
875
Dan Gohman89f85052007-10-22 18:31:58 +0000876SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 assert(!Ops.empty() && "Cannot get empty mul!");
878
879 // Sort by complexity, this groups all similar expression types together.
880 GroupByComplexity(Ops);
881
882 // If there are any constants, fold them together.
883 unsigned Idx = 0;
884 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
885
886 // C1*(C2+V) -> C1*C2 + C1*V
887 if (Ops.size() == 2)
888 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
889 if (Add->getNumOperands() == 2 &&
890 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000891 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
892 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893
894
895 ++Idx;
896 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
897 // We found two constants, fold them together!
898 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
899 RHSC->getValue()->getValue());
900 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000901 Ops[0] = getConstant(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 Ops.erase(Ops.begin()+1); // Erase the folded element
903 if (Ops.size() == 1) return Ops[0];
904 LHSC = cast<SCEVConstant>(Ops[0]);
905 } else {
906 // If we couldn't fold the expression, move to the next constant. Note
907 // that this is impossible to happen in practice because we always
908 // constant fold constant ints to constant ints.
909 ++Idx;
910 }
911 }
912
913 // If we are left with a constant one being multiplied, strip it off.
914 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
915 Ops.erase(Ops.begin());
916 --Idx;
917 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
918 // If we have a multiply of zero, it will always be zero.
919 return Ops[0];
920 }
921 }
922
923 // Skip over the add expression until we get to a multiply.
924 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
925 ++Idx;
926
927 if (Ops.size() == 1)
928 return Ops[0];
929
930 // If there are mul operands inline them all into this expression.
931 if (Idx < Ops.size()) {
932 bool DeletedMul = false;
933 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
934 // If we have an mul, expand the mul operands onto the end of the operands
935 // list.
936 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
937 Ops.erase(Ops.begin()+Idx);
938 DeletedMul = true;
939 }
940
941 // If we deleted at least one mul, we added operands to the end of the list,
942 // and they are not necessarily sorted. Recurse to resort and resimplify
943 // any operands we just aquired.
944 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +0000945 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 }
947
948 // If there are any add recurrences in the operands list, see if any other
949 // added values are loop invariant. If so, we can fold them into the
950 // recurrence.
951 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
952 ++Idx;
953
954 // Scan over all recurrences, trying to fold loop invariants into them.
955 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
956 // Scan all of the other operands to this mul and add them to the vector if
957 // they are loop invariant w.r.t. the recurrence.
958 std::vector<SCEVHandle> LIOps;
959 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
960 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
961 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
962 LIOps.push_back(Ops[i]);
963 Ops.erase(Ops.begin()+i);
964 --i; --e;
965 }
966
967 // If we found some loop invariants, fold them into the recurrence.
968 if (!LIOps.empty()) {
969 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
970 std::vector<SCEVHandle> NewOps;
971 NewOps.reserve(AddRec->getNumOperands());
972 if (LIOps.size() == 1) {
973 SCEV *Scale = LIOps[0];
974 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +0000975 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 } else {
977 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
978 std::vector<SCEVHandle> MulOps(LIOps);
979 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +0000980 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 }
982 }
983
Dan Gohman89f85052007-10-22 18:31:58 +0000984 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985
986 // If all of the other operands were loop invariant, we are done.
987 if (Ops.size() == 1) return NewRec;
988
989 // Otherwise, multiply the folded AddRec by the non-liv parts.
990 for (unsigned i = 0;; ++i)
991 if (Ops[i] == AddRec) {
992 Ops[i] = NewRec;
993 break;
994 }
Dan Gohman89f85052007-10-22 18:31:58 +0000995 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 }
997
998 // Okay, if there weren't any loop invariants to be folded, check to see if
999 // there are multiple AddRec's with the same loop induction variable being
1000 // multiplied together. If so, we can fold them.
1001 for (unsigned OtherIdx = Idx+1;
1002 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1003 if (OtherIdx != Idx) {
1004 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1005 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1006 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1007 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001008 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001010 SCEVHandle B = F->getStepRecurrence(*this);
1011 SCEVHandle D = G->getStepRecurrence(*this);
1012 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1013 getMulExpr(G, B),
1014 getMulExpr(B, D));
1015 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1016 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001017 if (Ops.size() == 2) return NewAddRec;
1018
1019 Ops.erase(Ops.begin()+Idx);
1020 Ops.erase(Ops.begin()+OtherIdx-1);
1021 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001022 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 }
1024 }
1025
1026 // Otherwise couldn't fold anything into this recurrence. Move onto the
1027 // next one.
1028 }
1029
1030 // Okay, it looks like we really DO need an mul expr. Check to see if we
1031 // already have one, otherwise create a new one.
1032 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1033 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1034 SCEVOps)];
1035 if (Result == 0)
1036 Result = new SCEVMulExpr(Ops);
1037 return Result;
1038}
1039
Anton Korobeynikoveb61bf52007-11-15 18:33:16 +00001040SCEVHandle ScalarEvolution::getSDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1042 if (RHSC->getValue()->equalsInt(1))
1043 return LHS; // X sdiv 1 --> x
1044 if (RHSC->getValue()->isAllOnesValue())
Dan Gohman89f85052007-10-22 18:31:58 +00001045 return getNegativeSCEV(LHS); // X sdiv -1 --> -x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046
1047 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1048 Constant *LHSCV = LHSC->getValue();
1049 Constant *RHSCV = RHSC->getValue();
Dan Gohman89f85052007-10-22 18:31:58 +00001050 return getUnknown(ConstantExpr::getSDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 }
1052 }
1053
1054 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1055
1056 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1057 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1058 return Result;
1059}
1060
1061
1062/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1063/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001064SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 const SCEVHandle &Step, const Loop *L) {
1066 std::vector<SCEVHandle> Operands;
1067 Operands.push_back(Start);
1068 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1069 if (StepChrec->getLoop() == L) {
1070 Operands.insert(Operands.end(), StepChrec->op_begin(),
1071 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001072 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 }
1074
1075 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001076 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077}
1078
1079/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1080/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001081SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 const Loop *L) {
1083 if (Operands.size() == 1) return Operands[0];
1084
1085 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1086 if (StepC->getValue()->isZero()) {
1087 Operands.pop_back();
Dan Gohman89f85052007-10-22 18:31:58 +00001088 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 }
1090
1091 SCEVAddRecExpr *&Result =
1092 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1093 Operands.end()))];
1094 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1095 return Result;
1096}
1097
Dan Gohman89f85052007-10-22 18:31:58 +00001098SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001100 return getConstant(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1102 if (Result == 0) Result = new SCEVUnknown(V);
1103 return Result;
1104}
1105
1106
1107//===----------------------------------------------------------------------===//
1108// ScalarEvolutionsImpl Definition and Implementation
1109//===----------------------------------------------------------------------===//
1110//
1111/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1112/// evolution code.
1113///
1114namespace {
1115 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001116 /// SE - A reference to the public ScalarEvolution object.
1117 ScalarEvolution &SE;
1118
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 /// F - The function we are analyzing.
1120 ///
1121 Function &F;
1122
1123 /// LI - The loop information for the function we are currently analyzing.
1124 ///
1125 LoopInfo &LI;
1126
1127 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1128 /// things.
1129 SCEVHandle UnknownValue;
1130
1131 /// Scalars - This is a cache of the scalars we have analyzed so far.
1132 ///
1133 std::map<Value*, SCEVHandle> Scalars;
1134
1135 /// IterationCounts - Cache the iteration count of the loops for this
1136 /// function as they are computed.
1137 std::map<const Loop*, SCEVHandle> IterationCounts;
1138
1139 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1140 /// the PHI instructions that we attempt to compute constant evolutions for.
1141 /// This allows us to avoid potentially expensive recomputation of these
1142 /// properties. An instruction maps to null if we are unable to compute its
1143 /// exit value.
1144 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1145
1146 public:
Dan Gohman89f85052007-10-22 18:31:58 +00001147 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1148 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149
1150 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1151 /// expression and create a new one.
1152 SCEVHandle getSCEV(Value *V);
1153
1154 /// hasSCEV - Return true if the SCEV for this value has already been
1155 /// computed.
1156 bool hasSCEV(Value *V) const {
1157 return Scalars.count(V);
1158 }
1159
1160 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1161 /// the specified value.
1162 void setSCEV(Value *V, const SCEVHandle &H) {
1163 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1164 assert(isNew && "This entry already existed!");
1165 }
1166
1167
1168 /// getSCEVAtScope - Compute the value of the specified expression within
1169 /// the indicated loop (which may be null to indicate in no loop). If the
1170 /// expression cannot be evaluated, return UnknownValue itself.
1171 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1172
1173
1174 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1175 /// an analyzable loop-invariant iteration count.
1176 bool hasLoopInvariantIterationCount(const Loop *L);
1177
1178 /// getIterationCount - If the specified loop has a predictable iteration
1179 /// count, return it. Note that it is not valid to call this method on a
1180 /// loop without a loop-invariant iteration count.
1181 SCEVHandle getIterationCount(const Loop *L);
1182
1183 /// deleteValueFromRecords - This method should be called by the
1184 /// client before it removes a value from the program, to make sure
1185 /// that no dangling references are left around.
1186 void deleteValueFromRecords(Value *V);
1187
1188 private:
1189 /// createSCEV - We know that there is no SCEV for the specified value.
1190 /// Analyze the expression.
1191 SCEVHandle createSCEV(Value *V);
1192
1193 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1194 /// SCEVs.
1195 SCEVHandle createNodeForPHI(PHINode *PN);
1196
1197 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1198 /// for the specified instruction and replaces any references to the
1199 /// symbolic value SymName with the specified value. This is used during
1200 /// PHI resolution.
1201 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1202 const SCEVHandle &SymName,
1203 const SCEVHandle &NewVal);
1204
1205 /// ComputeIterationCount - Compute the number of times the specified loop
1206 /// will iterate.
1207 SCEVHandle ComputeIterationCount(const Loop *L);
1208
1209 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001210 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1212 Constant *RHS,
1213 const Loop *L,
1214 ICmpInst::Predicate p);
1215
1216 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1217 /// constant number of times (the condition evolves only from constants),
1218 /// try to evaluate a few iterations of the loop until we get the exit
1219 /// condition gets a value of ExitWhen (true or false). If we cannot
1220 /// evaluate the trip count of the loop, return UnknownValue.
1221 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1222 bool ExitWhen);
1223
1224 /// HowFarToZero - Return the number of times a backedge comparing the
1225 /// specified value to zero will execute. If not computable, return
1226 /// UnknownValue.
1227 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1228
1229 /// HowFarToNonZero - Return the number of times a backedge checking the
1230 /// specified value for nonzero will execute. If not computable, return
1231 /// UnknownValue.
1232 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1233
1234 /// HowManyLessThans - Return the number of times a backedge containing the
1235 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001236 /// UnknownValue. isSigned specifies whether the less-than is signed.
1237 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1238 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239
1240 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1241 /// in the header of its containing loop, we know the loop executes a
1242 /// constant number of times, and the PHI node is just a recurrence
1243 /// involving constants, fold it.
1244 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1245 const Loop *L);
1246 };
1247}
1248
1249//===----------------------------------------------------------------------===//
1250// Basic SCEV Analysis and PHI Idiom Recognition Code
1251//
1252
1253/// deleteValueFromRecords - This method should be called by the
1254/// client before it removes an instruction from the program, to make sure
1255/// that no dangling references are left around.
1256void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1257 SmallVector<Value *, 16> Worklist;
1258
1259 if (Scalars.erase(V)) {
1260 if (PHINode *PN = dyn_cast<PHINode>(V))
1261 ConstantEvolutionLoopExitValue.erase(PN);
1262 Worklist.push_back(V);
1263 }
1264
1265 while (!Worklist.empty()) {
1266 Value *VV = Worklist.back();
1267 Worklist.pop_back();
1268
1269 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1270 UI != UE; ++UI) {
1271 Instruction *Inst = cast<Instruction>(*UI);
1272 if (Scalars.erase(Inst)) {
1273 if (PHINode *PN = dyn_cast<PHINode>(VV))
1274 ConstantEvolutionLoopExitValue.erase(PN);
1275 Worklist.push_back(Inst);
1276 }
1277 }
1278 }
1279}
1280
1281
1282/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1283/// expression and create a new one.
1284SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1285 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1286
1287 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1288 if (I != Scalars.end()) return I->second;
1289 SCEVHandle S = createSCEV(V);
1290 Scalars.insert(std::make_pair(V, S));
1291 return S;
1292}
1293
1294/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1295/// the specified instruction and replaces any references to the symbolic value
1296/// SymName with the specified value. This is used during PHI resolution.
1297void ScalarEvolutionsImpl::
1298ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1299 const SCEVHandle &NewVal) {
1300 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1301 if (SI == Scalars.end()) return;
1302
1303 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001304 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 if (NV == SI->second) return; // No change.
1306
1307 SI->second = NV; // Update the scalars map!
1308
1309 // Any instruction values that use this instruction might also need to be
1310 // updated!
1311 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1312 UI != E; ++UI)
1313 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1314}
1315
1316/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1317/// a loop header, making it a potential recurrence, or it doesn't.
1318///
1319SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1320 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1321 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1322 if (L->getHeader() == PN->getParent()) {
1323 // If it lives in the loop header, it has two incoming values, one
1324 // from outside the loop, and one from inside.
1325 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1326 unsigned BackEdge = IncomingEdge^1;
1327
1328 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001329 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 assert(Scalars.find(PN) == Scalars.end() &&
1331 "PHI node already processed?");
1332 Scalars.insert(std::make_pair(PN, SymbolicName));
1333
1334 // Using this symbolic name for the PHI, analyze the value coming around
1335 // the back-edge.
1336 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1337
1338 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1339 // has a special value for the first iteration of the loop.
1340
1341 // If the value coming around the backedge is an add with the symbolic
1342 // value we just inserted, then we found a simple induction variable!
1343 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1344 // If there is a single occurrence of the symbolic value, replace it
1345 // with a recurrence.
1346 unsigned FoundIndex = Add->getNumOperands();
1347 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1348 if (Add->getOperand(i) == SymbolicName)
1349 if (FoundIndex == e) {
1350 FoundIndex = i;
1351 break;
1352 }
1353
1354 if (FoundIndex != Add->getNumOperands()) {
1355 // Create an add with everything but the specified operand.
1356 std::vector<SCEVHandle> Ops;
1357 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1358 if (i != FoundIndex)
1359 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001360 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361
1362 // This is not a valid addrec if the step amount is varying each
1363 // loop iteration, but is not itself an addrec in this loop.
1364 if (Accum->isLoopInvariant(L) ||
1365 (isa<SCEVAddRecExpr>(Accum) &&
1366 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1367 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001368 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369
1370 // Okay, for the entire analysis of this edge we assumed the PHI
1371 // to be symbolic. We now need to go back and update all of the
1372 // entries for the scalars that use the PHI (except for the PHI
1373 // itself) to use the new analyzed value instead of the "symbolic"
1374 // value.
1375 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1376 return PHISCEV;
1377 }
1378 }
1379 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1380 // Otherwise, this could be a loop like this:
1381 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1382 // In this case, j = {1,+,1} and BEValue is j.
1383 // Because the other in-value of i (0) fits the evolution of BEValue
1384 // i really is an addrec evolution.
1385 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1386 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1387
1388 // If StartVal = j.start - j.stride, we can use StartVal as the
1389 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001390 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1391 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001393 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394
1395 // Okay, for the entire analysis of this edge we assumed the PHI
1396 // to be symbolic. We now need to go back and update all of the
1397 // entries for the scalars that use the PHI (except for the PHI
1398 // itself) to use the new analyzed value instead of the "symbolic"
1399 // value.
1400 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1401 return PHISCEV;
1402 }
1403 }
1404 }
1405
1406 return SymbolicName;
1407 }
1408
1409 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001410 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411}
1412
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001413/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1414/// guaranteed to end in (at every loop iteration). It is, at the same time,
1415/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1416/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1417static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1418 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001419 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001421 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001422 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1423
1424 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1425 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1426 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1427 }
1428
1429 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1430 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1431 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1432 }
1433
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001435 // The result is the min of all operands results.
1436 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1437 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1438 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1439 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440 }
1441
1442 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001443 // The result is the sum of all operands results.
1444 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1445 uint32_t BitWidth = M->getBitWidth();
1446 for (unsigned i = 1, e = M->getNumOperands();
1447 SumOpRes != BitWidth && i != e; ++i)
1448 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1449 BitWidth);
1450 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001452
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001454 // The result is the min of all operands results.
1455 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1456 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1457 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1458 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001460
1461 // SCEVSDivExpr, SCEVUnknown
1462 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463}
1464
1465/// createSCEV - We know that there is no SCEV for the specified value.
1466/// Analyze the expression.
1467///
1468SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner3fff4642007-11-23 08:46:22 +00001469 if (!isa<IntegerType>(V->getType()))
1470 return SE.getUnknown(V);
1471
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 if (Instruction *I = dyn_cast<Instruction>(V)) {
1473 switch (I->getOpcode()) {
1474 case Instruction::Add:
Dan Gohman89f85052007-10-22 18:31:58 +00001475 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1476 getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 case Instruction::Mul:
Dan Gohman89f85052007-10-22 18:31:58 +00001478 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1479 getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001480 case Instruction::SDiv:
Dan Gohman89f85052007-10-22 18:31:58 +00001481 return SE.getSDivExpr(getSCEV(I->getOperand(0)),
1482 getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483 case Instruction::Sub:
Dan Gohman89f85052007-10-22 18:31:58 +00001484 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1485 getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001486 case Instruction::Or:
1487 // If the RHS of the Or is a constant, we may have something like:
Nick Lewyckyef947492007-11-20 08:24:44 +00001488 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 // optimizations will transparently handle this case.
Nick Lewyckyef947492007-11-20 08:24:44 +00001490 //
1491 // In order for this transformation to be safe, the LHS must be of the
1492 // form X*(2^n) and the Or constant must be less than 2^n.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1494 SCEVHandle LHS = getSCEV(I->getOperand(0));
Nick Lewyckyef947492007-11-20 08:24:44 +00001495 const APInt &CIVal = CI->getValue();
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001496 if (GetMinTrailingZeros(LHS) >=
Nick Lewyckyef947492007-11-20 08:24:44 +00001497 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001498 return SE.getAddExpr(LHS, getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001499 }
1500 break;
1501 case Instruction::Xor:
1502 // If the RHS of the xor is a signbit, then this is just an add.
1503 // Instcombine turns add of signbit into xor as a strength reduction step.
1504 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1505 if (CI->getValue().isSignBit())
Dan Gohman89f85052007-10-22 18:31:58 +00001506 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1507 getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001508 }
1509 break;
1510
1511 case Instruction::Shl:
1512 // Turn shift left of a constant amount into a multiply.
1513 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1514 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1515 Constant *X = ConstantInt::get(
1516 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohman89f85052007-10-22 18:31:58 +00001517 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518 }
1519 break;
1520
1521 case Instruction::Trunc:
Dan Gohman89f85052007-10-22 18:31:58 +00001522 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523
1524 case Instruction::ZExt:
Dan Gohman89f85052007-10-22 18:31:58 +00001525 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526
1527 case Instruction::SExt:
Dan Gohman89f85052007-10-22 18:31:58 +00001528 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529
1530 case Instruction::BitCast:
1531 // BitCasts are no-op casts so we just eliminate the cast.
1532 if (I->getType()->isInteger() &&
1533 I->getOperand(0)->getType()->isInteger())
1534 return getSCEV(I->getOperand(0));
1535 break;
1536
1537 case Instruction::PHI:
1538 return createNodeForPHI(cast<PHINode>(I));
1539
1540 default: // We cannot analyze this expression.
1541 break;
1542 }
1543 }
1544
Dan Gohman89f85052007-10-22 18:31:58 +00001545 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546}
1547
1548
1549
1550//===----------------------------------------------------------------------===//
1551// Iteration Count Computation Code
1552//
1553
1554/// getIterationCount - If the specified loop has a predictable iteration
1555/// count, return it. Note that it is not valid to call this method on a
1556/// loop without a loop-invariant iteration count.
1557SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1558 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1559 if (I == IterationCounts.end()) {
1560 SCEVHandle ItCount = ComputeIterationCount(L);
1561 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1562 if (ItCount != UnknownValue) {
1563 assert(ItCount->isLoopInvariant(L) &&
1564 "Computed trip count isn't loop invariant for loop!");
1565 ++NumTripCountsComputed;
1566 } else if (isa<PHINode>(L->getHeader()->begin())) {
1567 // Only count loops that have phi nodes as not being computable.
1568 ++NumTripCountsNotComputed;
1569 }
1570 }
1571 return I->second;
1572}
1573
1574/// ComputeIterationCount - Compute the number of times the specified loop
1575/// will iterate.
1576SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1577 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00001578 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001579 L->getExitBlocks(ExitBlocks);
1580 if (ExitBlocks.size() != 1) return UnknownValue;
1581
1582 // Okay, there is one exit block. Try to find the condition that causes the
1583 // loop to be exited.
1584 BasicBlock *ExitBlock = ExitBlocks[0];
1585
1586 BasicBlock *ExitingBlock = 0;
1587 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1588 PI != E; ++PI)
1589 if (L->contains(*PI)) {
1590 if (ExitingBlock == 0)
1591 ExitingBlock = *PI;
1592 else
1593 return UnknownValue; // More than one block exiting!
1594 }
1595 assert(ExitingBlock && "No exits from loop, something is broken!");
1596
1597 // Okay, we've computed the exiting block. See what condition causes us to
1598 // exit.
1599 //
1600 // FIXME: we should be able to handle switch instructions (with a single exit)
1601 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1602 if (ExitBr == 0) return UnknownValue;
1603 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1604
1605 // At this point, we know we have a conditional branch that determines whether
1606 // the loop is exited. However, we don't know if the branch is executed each
1607 // time through the loop. If not, then the execution count of the branch will
1608 // not be equal to the trip count of the loop.
1609 //
1610 // Currently we check for this by checking to see if the Exit branch goes to
1611 // the loop header. If so, we know it will always execute the same number of
1612 // times as the loop. We also handle the case where the exit block *is* the
1613 // loop header. This is common for un-rotated loops. More extensive analysis
1614 // could be done to handle more cases here.
1615 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1616 ExitBr->getSuccessor(1) != L->getHeader() &&
1617 ExitBr->getParent() != L->getHeader())
1618 return UnknownValue;
1619
1620 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1621
1622 // If its not an integer comparison then compute it the hard way.
1623 // Note that ICmpInst deals with pointer comparisons too so we must check
1624 // the type of the operand.
1625 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1626 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1627 ExitBr->getSuccessor(0) == ExitBlock);
1628
1629 // If the condition was exit on true, convert the condition to exit on false
1630 ICmpInst::Predicate Cond;
1631 if (ExitBr->getSuccessor(1) == ExitBlock)
1632 Cond = ExitCond->getPredicate();
1633 else
1634 Cond = ExitCond->getInversePredicate();
1635
1636 // Handle common loops like: for (X = "string"; *X; ++X)
1637 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1638 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1639 SCEVHandle ItCnt =
1640 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1641 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1642 }
1643
1644 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1645 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1646
1647 // Try to evaluate any dependencies out of the loop.
1648 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1649 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1650 Tmp = getSCEVAtScope(RHS, L);
1651 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1652
1653 // At this point, we would like to compute how many iterations of the
1654 // loop the predicate will return true for these inputs.
1655 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1656 // If there is a constant, force it into the RHS.
1657 std::swap(LHS, RHS);
1658 Cond = ICmpInst::getSwappedPredicate(Cond);
1659 }
1660
1661 // FIXME: think about handling pointer comparisons! i.e.:
1662 // while (P != P+100) ++P;
1663
1664 // If we have a comparison of a chrec against a constant, try to use value
1665 // ranges to answer this query.
1666 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1667 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1668 if (AddRec->getLoop() == L) {
1669 // Form the comparison range using the constant of the correct type so
1670 // that the ConstantRange class knows to do a signed or unsigned
1671 // comparison.
1672 ConstantInt *CompVal = RHSC->getValue();
1673 const Type *RealTy = ExitCond->getOperand(0)->getType();
1674 CompVal = dyn_cast<ConstantInt>(
1675 ConstantExpr::getBitCast(CompVal, RealTy));
1676 if (CompVal) {
1677 // Form the constant range.
1678 ConstantRange CompRange(
1679 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1680
Dan Gohman89f85052007-10-22 18:31:58 +00001681 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1683 }
1684 }
1685
1686 switch (Cond) {
1687 case ICmpInst::ICMP_NE: { // while (X != Y)
1688 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00001689 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1691 break;
1692 }
1693 case ICmpInst::ICMP_EQ: {
1694 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00001695 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1697 break;
1698 }
1699 case ICmpInst::ICMP_SLT: {
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001700 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1702 break;
1703 }
1704 case ICmpInst::ICMP_SGT: {
Dan Gohman89f85052007-10-22 18:31:58 +00001705 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1706 SE.getNegativeSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001707 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1708 break;
1709 }
1710 case ICmpInst::ICMP_ULT: {
1711 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1712 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1713 break;
1714 }
1715 case ICmpInst::ICMP_UGT: {
Dan Gohman89f85052007-10-22 18:31:58 +00001716 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1717 SE.getNegativeSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001718 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1719 break;
1720 }
1721 default:
1722#if 0
1723 cerr << "ComputeIterationCount ";
1724 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1725 cerr << "[unsigned] ";
1726 cerr << *LHS << " "
1727 << Instruction::getOpcodeName(Instruction::ICmp)
1728 << " " << *RHS << "\n";
1729#endif
1730 break;
1731 }
1732 return ComputeIterationCountExhaustively(L, ExitCond,
1733 ExitBr->getSuccessor(0) == ExitBlock);
1734}
1735
1736static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00001737EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
1738 ScalarEvolution &SE) {
1739 SCEVHandle InVal = SE.getConstant(C);
1740 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001741 assert(isa<SCEVConstant>(Val) &&
1742 "Evaluation of SCEV at constant didn't fold correctly?");
1743 return cast<SCEVConstant>(Val)->getValue();
1744}
1745
1746/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1747/// and a GEP expression (missing the pointer index) indexing into it, return
1748/// the addressed element of the initializer or null if the index expression is
1749/// invalid.
1750static Constant *
1751GetAddressedElementFromGlobal(GlobalVariable *GV,
1752 const std::vector<ConstantInt*> &Indices) {
1753 Constant *Init = GV->getInitializer();
1754 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1755 uint64_t Idx = Indices[i]->getZExtValue();
1756 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1757 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1758 Init = cast<Constant>(CS->getOperand(Idx));
1759 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1760 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1761 Init = cast<Constant>(CA->getOperand(Idx));
1762 } else if (isa<ConstantAggregateZero>(Init)) {
1763 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1764 assert(Idx < STy->getNumElements() && "Bad struct index!");
1765 Init = Constant::getNullValue(STy->getElementType(Idx));
1766 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1767 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1768 Init = Constant::getNullValue(ATy->getElementType());
1769 } else {
1770 assert(0 && "Unknown constant aggregate type!");
1771 }
1772 return 0;
1773 } else {
1774 return 0; // Unknown initializer type
1775 }
1776 }
1777 return Init;
1778}
1779
1780/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001781/// 'icmp op load X, cst', try to se if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001782SCEVHandle ScalarEvolutionsImpl::
1783ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
1784 const Loop *L,
1785 ICmpInst::Predicate predicate) {
1786 if (LI->isVolatile()) return UnknownValue;
1787
1788 // Check to see if the loaded pointer is a getelementptr of a global.
1789 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1790 if (!GEP) return UnknownValue;
1791
1792 // Make sure that it is really a constant global we are gepping, with an
1793 // initializer, and make sure the first IDX is really 0.
1794 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1795 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1796 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1797 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1798 return UnknownValue;
1799
1800 // Okay, we allow one non-constant index into the GEP instruction.
1801 Value *VarIdx = 0;
1802 std::vector<ConstantInt*> Indexes;
1803 unsigned VarIdxNum = 0;
1804 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1805 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1806 Indexes.push_back(CI);
1807 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1808 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1809 VarIdx = GEP->getOperand(i);
1810 VarIdxNum = i-2;
1811 Indexes.push_back(0);
1812 }
1813
1814 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1815 // Check to see if X is a loop variant variable value now.
1816 SCEVHandle Idx = getSCEV(VarIdx);
1817 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1818 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1819
1820 // We can only recognize very limited forms of loop index expressions, in
1821 // particular, only affine AddRec's like {C1,+,C2}.
1822 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1823 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1824 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1825 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1826 return UnknownValue;
1827
1828 unsigned MaxSteps = MaxBruteForceIterations;
1829 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
1830 ConstantInt *ItCst =
1831 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00001832 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001833
1834 // Form the GEP offset.
1835 Indexes[VarIdxNum] = Val;
1836
1837 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1838 if (Result == 0) break; // Cannot compute!
1839
1840 // Evaluate the condition for this iteration.
1841 Result = ConstantExpr::getICmp(predicate, Result, RHS);
1842 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
1843 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
1844#if 0
1845 cerr << "\n***\n*** Computed loop count " << *ItCst
1846 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1847 << "***\n";
1848#endif
1849 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00001850 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001851 }
1852 }
1853 return UnknownValue;
1854}
1855
1856
1857/// CanConstantFold - Return true if we can constant fold an instruction of the
1858/// specified type, assuming that all operands were constants.
1859static bool CanConstantFold(const Instruction *I) {
1860 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1861 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1862 return true;
1863
1864 if (const CallInst *CI = dyn_cast<CallInst>(I))
1865 if (const Function *F = CI->getCalledFunction())
1866 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1867 return false;
1868}
1869
1870/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1871/// in the loop that V is derived from. We allow arbitrary operations along the
1872/// way, but the operands of an operation must either be constants or a value
1873/// derived from a constant PHI. If this expression does not fit with these
1874/// constraints, return null.
1875static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1876 // If this is not an instruction, or if this is an instruction outside of the
1877 // loop, it can't be derived from a loop PHI.
1878 Instruction *I = dyn_cast<Instruction>(V);
1879 if (I == 0 || !L->contains(I->getParent())) return 0;
1880
1881 if (PHINode *PN = dyn_cast<PHINode>(I))
1882 if (L->getHeader() == I->getParent())
1883 return PN;
1884 else
1885 // We don't currently keep track of the control flow needed to evaluate
1886 // PHIs, so we cannot handle PHIs inside of loops.
1887 return 0;
1888
1889 // If we won't be able to constant fold this expression even if the operands
1890 // are constants, return early.
1891 if (!CanConstantFold(I)) return 0;
1892
1893 // Otherwise, we can evaluate this instruction if all of its operands are
1894 // constant or derived from a PHI node themselves.
1895 PHINode *PHI = 0;
1896 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1897 if (!(isa<Constant>(I->getOperand(Op)) ||
1898 isa<GlobalValue>(I->getOperand(Op)))) {
1899 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1900 if (P == 0) return 0; // Not evolving from PHI
1901 if (PHI == 0)
1902 PHI = P;
1903 else if (PHI != P)
1904 return 0; // Evolving from multiple different PHIs.
1905 }
1906
1907 // This is a expression evolving from a constant PHI!
1908 return PHI;
1909}
1910
1911/// EvaluateExpression - Given an expression that passes the
1912/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1913/// in the loop has the value PHIVal. If we can't fold this expression for some
1914/// reason, return null.
1915static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1916 if (isa<PHINode>(V)) return PHIVal;
1917 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1918 return GV;
1919 if (Constant *C = dyn_cast<Constant>(V)) return C;
1920 Instruction *I = cast<Instruction>(V);
1921
1922 std::vector<Constant*> Operands;
1923 Operands.resize(I->getNumOperands());
1924
1925 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1926 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1927 if (Operands[i] == 0) return 0;
1928 }
1929
1930 return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
1931}
1932
1933/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1934/// in the header of its containing loop, we know the loop executes a
1935/// constant number of times, and the PHI node is just a recurrence
1936/// involving constants, fold it.
1937Constant *ScalarEvolutionsImpl::
1938getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
1939 std::map<PHINode*, Constant*>::iterator I =
1940 ConstantEvolutionLoopExitValue.find(PN);
1941 if (I != ConstantEvolutionLoopExitValue.end())
1942 return I->second;
1943
1944 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
1945 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1946
1947 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1948
1949 // Since the loop is canonicalized, the PHI node must have two entries. One
1950 // entry must be a constant (coming in from outside of the loop), and the
1951 // second must be derived from the same PHI.
1952 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1953 Constant *StartCST =
1954 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1955 if (StartCST == 0)
1956 return RetVal = 0; // Must be a constant.
1957
1958 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1959 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1960 if (PN2 != PN)
1961 return RetVal = 0; // Not derived from same PHI.
1962
1963 // Execute the loop symbolically to determine the exit value.
1964 if (Its.getActiveBits() >= 32)
1965 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
1966
1967 unsigned NumIterations = Its.getZExtValue(); // must be in range
1968 unsigned IterationNum = 0;
1969 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1970 if (IterationNum == NumIterations)
1971 return RetVal = PHIVal; // Got exit value!
1972
1973 // Compute the value of the PHI node for the next iteration.
1974 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1975 if (NextPHI == PHIVal)
1976 return RetVal = NextPHI; // Stopped evolving!
1977 if (NextPHI == 0)
1978 return 0; // Couldn't evaluate!
1979 PHIVal = NextPHI;
1980 }
1981}
1982
1983/// ComputeIterationCountExhaustively - If the trip is known to execute a
1984/// constant number of times (the condition evolves only from constants),
1985/// try to evaluate a few iterations of the loop until we get the exit
1986/// condition gets a value of ExitWhen (true or false). If we cannot
1987/// evaluate the trip count of the loop, return UnknownValue.
1988SCEVHandle ScalarEvolutionsImpl::
1989ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1990 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1991 if (PN == 0) return UnknownValue;
1992
1993 // Since the loop is canonicalized, the PHI node must have two entries. One
1994 // entry must be a constant (coming in from outside of the loop), and the
1995 // second must be derived from the same PHI.
1996 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1997 Constant *StartCST =
1998 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1999 if (StartCST == 0) return UnknownValue; // Must be a constant.
2000
2001 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2002 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2003 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2004
2005 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2006 // the loop symbolically to determine when the condition gets a value of
2007 // "ExitWhen".
2008 unsigned IterationNum = 0;
2009 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2010 for (Constant *PHIVal = StartCST;
2011 IterationNum != MaxIterations; ++IterationNum) {
2012 ConstantInt *CondVal =
2013 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2014
2015 // Couldn't symbolically evaluate.
2016 if (!CondVal) return UnknownValue;
2017
2018 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2019 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2020 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002021 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002022 }
2023
2024 // Compute the value of the PHI node for the next iteration.
2025 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2026 if (NextPHI == 0 || NextPHI == PHIVal)
2027 return UnknownValue; // Couldn't evaluate or not making progress...
2028 PHIVal = NextPHI;
2029 }
2030
2031 // Too many iterations were needed to evaluate.
2032 return UnknownValue;
2033}
2034
2035/// getSCEVAtScope - Compute the value of the specified expression within the
2036/// indicated loop (which may be null to indicate in no loop). If the
2037/// expression cannot be evaluated, return UnknownValue.
2038SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2039 // FIXME: this should be turned into a virtual method on SCEV!
2040
2041 if (isa<SCEVConstant>(V)) return V;
2042
2043 // If this instruction is evolves from a constant-evolving PHI, compute the
2044 // exit value from the loop without using SCEVs.
2045 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2046 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2047 const Loop *LI = this->LI[I->getParent()];
2048 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2049 if (PHINode *PN = dyn_cast<PHINode>(I))
2050 if (PN->getParent() == LI->getHeader()) {
2051 // Okay, there is no closed form solution for the PHI node. Check
2052 // to see if the loop that contains it has a known iteration count.
2053 // If so, we may be able to force computation of the exit value.
2054 SCEVHandle IterationCount = getIterationCount(LI);
2055 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2056 // Okay, we know how many times the containing loop executes. If
2057 // this is a constant evolving PHI node, get the final value at
2058 // the specified iteration number.
2059 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2060 ICC->getValue()->getValue(),
2061 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002062 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063 }
2064 }
2065
2066 // Okay, this is an expression that we cannot symbolically evaluate
2067 // into a SCEV. Check to see if it's possible to symbolically evaluate
2068 // the arguments into constants, and if so, try to constant propagate the
2069 // result. This is particularly useful for computing loop exit values.
2070 if (CanConstantFold(I)) {
2071 std::vector<Constant*> Operands;
2072 Operands.reserve(I->getNumOperands());
2073 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2074 Value *Op = I->getOperand(i);
2075 if (Constant *C = dyn_cast<Constant>(Op)) {
2076 Operands.push_back(C);
2077 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002078 // If any of the operands is non-constant and if they are
2079 // non-integer, don't even try to analyze them with scev techniques.
2080 if (!isa<IntegerType>(Op->getType()))
2081 return V;
2082
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002083 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2084 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2085 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2086 Op->getType(),
2087 false));
2088 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2089 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2090 Operands.push_back(ConstantExpr::getIntegerCast(C,
2091 Op->getType(),
2092 false));
2093 else
2094 return V;
2095 } else {
2096 return V;
2097 }
2098 }
2099 }
2100 Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002101 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002102 }
2103 }
2104
2105 // This is some other type of SCEVUnknown, just return it.
2106 return V;
2107 }
2108
2109 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2110 // Avoid performing the look-up in the common case where the specified
2111 // expression has no loop-variant portions.
2112 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2113 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2114 if (OpAtScope != Comm->getOperand(i)) {
2115 if (OpAtScope == UnknownValue) return UnknownValue;
2116 // Okay, at least one of these operands is loop variant but might be
2117 // foldable. Build a new instance of the folded commutative expression.
2118 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2119 NewOps.push_back(OpAtScope);
2120
2121 for (++i; i != e; ++i) {
2122 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2123 if (OpAtScope == UnknownValue) return UnknownValue;
2124 NewOps.push_back(OpAtScope);
2125 }
2126 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002127 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002128 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
Dan Gohman89f85052007-10-22 18:31:58 +00002129 return SE.getMulExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130 }
2131 }
2132 // If we got here, all operands are loop invariant.
2133 return Comm;
2134 }
2135
2136 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2137 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2138 if (LHS == UnknownValue) return LHS;
2139 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2140 if (RHS == UnknownValue) return RHS;
2141 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2142 return Div; // must be loop invariant
Dan Gohman89f85052007-10-22 18:31:58 +00002143 return SE.getSDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002144 }
2145
2146 // If this is a loop recurrence for a loop that does not contain L, then we
2147 // are dealing with the final value computed by the loop.
2148 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2149 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2150 // To evaluate this recurrence, we need to know how many times the AddRec
2151 // loop iterates. Compute this now.
2152 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2153 if (IterationCount == UnknownValue) return UnknownValue;
2154 IterationCount = getTruncateOrZeroExtend(IterationCount,
Dan Gohman89f85052007-10-22 18:31:58 +00002155 AddRec->getType(), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002156
2157 // If the value is affine, simplify the expression evaluation to just
2158 // Start + Step*IterationCount.
2159 if (AddRec->isAffine())
Dan Gohman89f85052007-10-22 18:31:58 +00002160 return SE.getAddExpr(AddRec->getStart(),
2161 SE.getMulExpr(IterationCount,
2162 AddRec->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002163
2164 // Otherwise, evaluate it the hard way.
Dan Gohman89f85052007-10-22 18:31:58 +00002165 return AddRec->evaluateAtIteration(IterationCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166 }
2167 return UnknownValue;
2168 }
2169
2170 //assert(0 && "Unknown SCEV type!");
2171 return UnknownValue;
2172}
2173
2174
2175/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2176/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2177/// might be the same) or two SCEVCouldNotCompute objects.
2178///
2179static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002180SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002181 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2182 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2183 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2184 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2185
2186 // We currently can only solve this if the coefficients are constants.
2187 if (!LC || !MC || !NC) {
2188 SCEV *CNC = new SCEVCouldNotCompute();
2189 return std::make_pair(CNC, CNC);
2190 }
2191
2192 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2193 const APInt &L = LC->getValue()->getValue();
2194 const APInt &M = MC->getValue()->getValue();
2195 const APInt &N = NC->getValue()->getValue();
2196 APInt Two(BitWidth, 2);
2197 APInt Four(BitWidth, 4);
2198
2199 {
2200 using namespace APIntOps;
2201 const APInt& C = L;
2202 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2203 // The B coefficient is M-N/2
2204 APInt B(M);
2205 B -= sdiv(N,Two);
2206
2207 // The A coefficient is N/2
2208 APInt A(N.sdiv(Two));
2209
2210 // Compute the B^2-4ac term.
2211 APInt SqrtTerm(B);
2212 SqrtTerm *= B;
2213 SqrtTerm -= Four * (A * C);
2214
2215 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2216 // integer value or else APInt::sqrt() will assert.
2217 APInt SqrtVal(SqrtTerm.sqrt());
2218
2219 // Compute the two solutions for the quadratic formula.
2220 // The divisions must be performed as signed divisions.
2221 APInt NegB(-B);
2222 APInt TwoA( A << 1 );
2223 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2224 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2225
Dan Gohman89f85052007-10-22 18:31:58 +00002226 return std::make_pair(SE.getConstant(Solution1),
2227 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002228 } // end APIntOps namespace
2229}
2230
2231/// HowFarToZero - Return the number of times a backedge comparing the specified
2232/// value to zero will execute. If not computable, return UnknownValue
2233SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2234 // If the value is a constant
2235 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2236 // If the value is already zero, the branch will execute zero times.
2237 if (C->getValue()->isZero()) return C;
2238 return UnknownValue; // Otherwise it will loop infinitely.
2239 }
2240
2241 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2242 if (!AddRec || AddRec->getLoop() != L)
2243 return UnknownValue;
2244
2245 if (AddRec->isAffine()) {
2246 // If this is an affine expression the execution count of this branch is
2247 // equal to:
2248 //
2249 // (0 - Start/Step) iff Start % Step == 0
2250 //
2251 // Get the initial value for the loop.
2252 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2253 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2254 SCEVHandle Step = AddRec->getOperand(1);
2255
2256 Step = getSCEVAtScope(Step, L->getParentLoop());
2257
2258 // Figure out if Start % Step == 0.
2259 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2260 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2261 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Dan Gohman89f85052007-10-22 18:31:58 +00002262 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2264 return Start; // 0 - Start/-1 == Start
2265
2266 // Check to see if Start is divisible by SC with no remainder.
2267 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2268 ConstantInt *StartCC = StartC->getValue();
2269 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
2270 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
2271 if (Rem->isNullValue()) {
2272 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Dan Gohman89f85052007-10-22 18:31:58 +00002273 return SE.getUnknown(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 }
2275 }
2276 }
2277 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2278 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2279 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002280 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2282 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2283 if (R1) {
2284#if 0
2285 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2286 << " sol#2: " << *R2 << "\n";
2287#endif
2288 // Pick the smallest positive root value.
2289 if (ConstantInt *CB =
2290 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2291 R1->getValue(), R2->getValue()))) {
2292 if (CB->getZExtValue() == false)
2293 std::swap(R1, R2); // R1 is the minimum root now.
2294
2295 // We can only use this value if the chrec ends up with an exact zero
2296 // value at this index. When solving for "X*X != 5", for example, we
2297 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002298 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2300 if (EvalVal->getValue()->isZero())
2301 return R1; // We found a quadratic root!
2302 }
2303 }
2304 }
2305
2306 return UnknownValue;
2307}
2308
2309/// HowFarToNonZero - Return the number of times a backedge checking the
2310/// specified value for nonzero will execute. If not computable, return
2311/// UnknownValue
2312SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2313 // Loops that look like: while (X == 0) are very strange indeed. We don't
2314 // handle them yet except for the trivial case. This could be expanded in the
2315 // future as needed.
2316
2317 // If the value is a constant, check to see if it is known to be non-zero
2318 // already. If so, the backedge will execute zero times.
2319 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2320 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2321 Constant *NonZero =
2322 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
2323 if (NonZero == ConstantInt::getTrue())
2324 return getSCEV(Zero);
2325 return UnknownValue; // Otherwise it will loop infinitely.
2326 }
2327
2328 // We could implement others, but I really doubt anyone writes loops like
2329 // this, and if they did, they would already be constant folded.
2330 return UnknownValue;
2331}
2332
2333/// HowManyLessThans - Return the number of times a backedge containing the
2334/// specified less-than comparison will execute. If not computable, return
2335/// UnknownValue.
2336SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002337HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338 // Only handle: "ADDREC < LoopInvariant".
2339 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2340
2341 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2342 if (!AddRec || AddRec->getLoop() != L)
2343 return UnknownValue;
2344
2345 if (AddRec->isAffine()) {
2346 // FORNOW: We only support unit strides.
Dan Gohman89f85052007-10-22 18:31:58 +00002347 SCEVHandle Zero = SE.getIntegerSCEV(0, RHS->getType());
2348 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002349 if (AddRec->getOperand(1) != One)
2350 return UnknownValue;
2351
Dan Gohman89f85052007-10-22 18:31:58 +00002352 // The number of iterations for "{n,+,1} < m", is m-n. However, we don't
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002353 // know that m is >= n on input to the loop. If it is, the condition return
2354 // true zero times. What we really should return, for full generality, is
2355 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2356 // canonical loop form: most do-loops will have a check that dominates the
Dan Gohman89f85052007-10-22 18:31:58 +00002357 // loop, that only enters the loop if (n-1)<m. If we can find this check,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002358 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2359
2360 // Search for the check.
2361 BasicBlock *Preheader = L->getLoopPreheader();
2362 BasicBlock *PreheaderDest = L->getHeader();
2363 if (Preheader == 0) return UnknownValue;
2364
2365 BranchInst *LoopEntryPredicate =
2366 dyn_cast<BranchInst>(Preheader->getTerminator());
2367 if (!LoopEntryPredicate) return UnknownValue;
2368
2369 // This might be a critical edge broken out. If the loop preheader ends in
2370 // an unconditional branch to the loop, check to see if the preheader has a
2371 // single predecessor, and if so, look for its terminator.
2372 while (LoopEntryPredicate->isUnconditional()) {
2373 PreheaderDest = Preheader;
2374 Preheader = Preheader->getSinglePredecessor();
2375 if (!Preheader) return UnknownValue; // Multiple preds.
2376
2377 LoopEntryPredicate =
2378 dyn_cast<BranchInst>(Preheader->getTerminator());
2379 if (!LoopEntryPredicate) return UnknownValue;
2380 }
2381
2382 // Now that we found a conditional branch that dominates the loop, check to
2383 // see if it is the comparison we are looking for.
2384 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2385 Value *PreCondLHS = ICI->getOperand(0);
2386 Value *PreCondRHS = ICI->getOperand(1);
2387 ICmpInst::Predicate Cond;
2388 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2389 Cond = ICI->getPredicate();
2390 else
2391 Cond = ICI->getInversePredicate();
2392
2393 switch (Cond) {
2394 case ICmpInst::ICMP_UGT:
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002395 if (isSigned) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002396 std::swap(PreCondLHS, PreCondRHS);
2397 Cond = ICmpInst::ICMP_ULT;
2398 break;
2399 case ICmpInst::ICMP_SGT:
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002400 if (!isSigned) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002401 std::swap(PreCondLHS, PreCondRHS);
2402 Cond = ICmpInst::ICMP_SLT;
2403 break;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002404 case ICmpInst::ICMP_ULT:
2405 if (isSigned) return UnknownValue;
2406 break;
2407 case ICmpInst::ICMP_SLT:
2408 if (!isSigned) return UnknownValue;
2409 break;
2410 default:
2411 return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002412 }
2413
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002414 if (PreCondLHS->getType()->isInteger()) {
2415 if (RHS != getSCEV(PreCondRHS))
2416 return UnknownValue; // Not a comparison against 'm'.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417
Dan Gohman89f85052007-10-22 18:31:58 +00002418 if (SE.getMinusSCEV(AddRec->getOperand(0), One)
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002419 != getSCEV(PreCondLHS))
2420 return UnknownValue; // Not a comparison against 'n-1'.
2421 }
2422 else return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423
2424 // cerr << "Computed Loop Trip Count as: "
Dan Gohman89f85052007-10-22 18:31:58 +00002425 // << // *SE.getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2426 return SE.getMinusSCEV(RHS, AddRec->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002427 }
2428 else
2429 return UnknownValue;
2430 }
2431
2432 return UnknownValue;
2433}
2434
2435/// getNumIterationsInRange - Return the number of iterations of this loop that
2436/// produce values in the specified constant range. Another way of looking at
2437/// this is that it returns the first iteration number where the value is not in
2438/// the condition, thus computing the exit count. If the iteration count can't
2439/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00002440SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2441 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002442 if (Range.isFullSet()) // Infinite loop.
2443 return new SCEVCouldNotCompute();
2444
2445 // If the start is a non-zero constant, shift the range to simplify things.
2446 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2447 if (!SC->getValue()->isZero()) {
2448 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002449 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2450 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002451 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2452 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00002453 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002454 // This is strange and shouldn't happen.
2455 return new SCEVCouldNotCompute();
2456 }
2457
2458 // The only time we can solve this is when we have all constant indices.
2459 // Otherwise, we cannot determine the overflow conditions.
2460 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2461 if (!isa<SCEVConstant>(getOperand(i)))
2462 return new SCEVCouldNotCompute();
2463
2464
2465 // Okay at this point we know that all elements of the chrec are constants and
2466 // that the start element is zero.
2467
2468 // First check to see if the range contains zero. If not, the first
2469 // iteration exits.
2470 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman89f85052007-10-22 18:31:58 +00002471 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002472
2473 if (isAffine()) {
2474 // If this is an affine expression then we have this situation:
2475 // Solve {0,+,A} in Range === Ax in Range
2476
2477 // We know that zero is in the range. If A is positive then we know that
2478 // the upper value of the range must be the first possible exit value.
2479 // If A is negative then the lower of the range is the last possible loop
2480 // value. Also note that we already checked for a full range.
2481 APInt One(getBitWidth(),1);
2482 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2483 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2484
2485 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00002486 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002487 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2488
2489 // Evaluate at the exit value. If we really did fall out of the valid
2490 // range, then we computed our trip count, otherwise wrap around or other
2491 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00002492 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002493 if (Range.contains(Val->getValue()))
2494 return new SCEVCouldNotCompute(); // Something strange happened
2495
2496 // Ensure that the previous value is in the range. This is a sanity check.
2497 assert(Range.contains(
2498 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002499 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002500 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00002501 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002502 } else if (isQuadratic()) {
2503 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2504 // quadratic equation to solve it. To do this, we must frame our problem in
2505 // terms of figuring out when zero is crossed, instead of when
2506 // Range.getUpper() is crossed.
2507 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002508 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2509 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002510
2511 // Next, solve the constructed addrec
2512 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00002513 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002514 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2515 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2516 if (R1) {
2517 // Pick the smallest positive root value.
2518 if (ConstantInt *CB =
2519 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2520 R1->getValue(), R2->getValue()))) {
2521 if (CB->getZExtValue() == false)
2522 std::swap(R1, R2); // R1 is the minimum root now.
2523
2524 // Make sure the root is not off by one. The returned iteration should
2525 // not be in the range, but the previous one should be. When solving
2526 // for "X*X < 5", for example, we should not return a root of 2.
2527 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002528 R1->getValue(),
2529 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530 if (Range.contains(R1Val->getValue())) {
2531 // The next iteration must be out of the range...
2532 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2533
Dan Gohman89f85052007-10-22 18:31:58 +00002534 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00002536 return SE.getConstant(NextVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002537 return new SCEVCouldNotCompute(); // Something strange happened
2538 }
2539
2540 // If R1 was not in the range, then it is a good return value. Make
2541 // sure that R1-1 WAS in the range though, just in case.
2542 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00002543 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002544 if (Range.contains(R1Val->getValue()))
2545 return R1;
2546 return new SCEVCouldNotCompute(); // Something strange happened
2547 }
2548 }
2549 }
2550
2551 // Fallback, if this is a general polynomial, figure out the progression
2552 // through brute force: evaluate until we find an iteration that fails the
2553 // test. This is likely to be slow, but getting an accurate trip count is
2554 // incredibly important, we will be able to simplify the exit test a lot, and
2555 // we are almost guaranteed to get a trip count in this case.
2556 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2557 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2558 do {
2559 ++NumBruteForceEvaluations;
Dan Gohman89f85052007-10-22 18:31:58 +00002560 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002561 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2562 return new SCEVCouldNotCompute();
2563
2564 // Check to see if we found the value!
2565 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00002566 return SE.getConstant(TestVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567
2568 // Increment to test the next index.
2569 TestVal = ConstantInt::get(TestVal->getValue()+1);
2570 } while (TestVal != EndVal);
2571
2572 return new SCEVCouldNotCompute();
2573}
2574
2575
2576
2577//===----------------------------------------------------------------------===//
2578// ScalarEvolution Class Implementation
2579//===----------------------------------------------------------------------===//
2580
2581bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman89f85052007-10-22 18:31:58 +00002582 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002583 return false;
2584}
2585
2586void ScalarEvolution::releaseMemory() {
2587 delete (ScalarEvolutionsImpl*)Impl;
2588 Impl = 0;
2589}
2590
2591void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2592 AU.setPreservesAll();
2593 AU.addRequiredTransitive<LoopInfo>();
2594}
2595
2596SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2597 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2598}
2599
2600/// hasSCEV - Return true if the SCEV for this value has already been
2601/// computed.
2602bool ScalarEvolution::hasSCEV(Value *V) const {
2603 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2604}
2605
2606
2607/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2608/// the specified value.
2609void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2610 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2611}
2612
2613
2614SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2615 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2616}
2617
2618bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2619 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2620}
2621
2622SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2623 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2624}
2625
2626void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2627 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
2628}
2629
2630static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2631 const Loop *L) {
2632 // Print all inner loops first
2633 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2634 PrintLoopInfo(OS, SE, *I);
2635
2636 cerr << "Loop " << L->getHeader()->getName() << ": ";
2637
Devang Patel02451fa2007-08-21 00:31:24 +00002638 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002639 L->getExitBlocks(ExitBlocks);
2640 if (ExitBlocks.size() != 1)
2641 cerr << "<multiple exits> ";
2642
2643 if (SE->hasLoopInvariantIterationCount(L)) {
2644 cerr << *SE->getIterationCount(L) << " iterations! ";
2645 } else {
2646 cerr << "Unpredictable iteration count. ";
2647 }
2648
2649 cerr << "\n";
2650}
2651
2652void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2653 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2654 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2655
2656 OS << "Classifying expressions for: " << F.getName() << "\n";
2657 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2658 if (I->getType()->isInteger()) {
2659 OS << *I;
2660 OS << " --> ";
2661 SCEVHandle SV = getSCEV(&*I);
2662 SV->print(OS);
2663 OS << "\t\t";
2664
2665 if ((*I).getType()->isInteger()) {
2666 ConstantRange Bounds = SV->getValueRange();
2667 if (!Bounds.isFullSet())
2668 OS << "Bounds: " << Bounds << " ";
2669 }
2670
2671 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2672 OS << "Exits: ";
2673 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2674 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2675 OS << "<<Unknown>>";
2676 } else {
2677 OS << *ExitValue;
2678 }
2679 }
2680
2681
2682 OS << "\n";
2683 }
2684
2685 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2686 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2687 PrintLoopInfo(OS, this, *I);
2688}