blob: 2841200b08e35c63976cd9b91c5cd5836e138735 [file] [log] [blame]
Chris Lattnerd934c702004-04-02 20:23:17 +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// Orthogonal to the analysis of code above, this file also implements the
37// ScalarEvolutionRewriter class, which is used to emit code that represents the
38// various recurrences present in a loop, in canonical forms.
39//
40// TODO: We should use these routines and value representations to implement
41// dependence analysis!
42//
43//===----------------------------------------------------------------------===//
44//
45// There are several good references for the techniques used in this analysis.
46//
47// Chains of recurrences -- a method to expedite the evaluation
48// of closed-form functions
49// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
50//
51// On computational properties of chains of recurrences
52// Eugene V. Zima
53//
54// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
55// Robert A. van Engelen
56//
57// Efficient Symbolic Analysis for Optimizing Compilers
58// Robert A. van Engelen
59//
60// Using the chains of recurrences algebra for data dependence testing and
61// induction variable substitution
62// MS Thesis, Johnie Birch
63//
64//===----------------------------------------------------------------------===//
65
Chris Lattnerb4f681b2004-04-15 15:07:24 +000066#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000067#include "llvm/Constants.h"
68#include "llvm/DerivedTypes.h"
69#include "llvm/Instructions.h"
70#include "llvm/Type.h"
71#include "llvm/Value.h"
72#include "llvm/Analysis/LoopInfo.h"
73#include "llvm/Assembly/Writer.h"
74#include "llvm/Transforms/Scalar.h"
Chris Lattner4021d1a2004-04-17 18:36:24 +000075#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000076#include "llvm/Support/CFG.h"
77#include "llvm/Support/ConstantRange.h"
78#include "llvm/Support/InstIterator.h"
Chris Lattner4021d1a2004-04-17 18:36:24 +000079#include "Support/CommandLine.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000080#include "Support/Statistic.h"
Brian Gaeke174633b2004-04-16 15:57:32 +000081#include <cmath>
Chris Lattnerd934c702004-04-02 20:23:17 +000082using namespace llvm;
83
84namespace {
85 RegisterAnalysis<ScalarEvolution>
86 R("scalar-evolution", "Scalar Evolution Analysis Printer");
87
88 Statistic<>
89 NumBruteForceEvaluations("scalar-evolution",
90 "Number of brute force evaluations needed to calculate high-order polynomial exit values");
91 Statistic<>
92 NumTripCountsComputed("scalar-evolution",
93 "Number of loops with predictable loop counts");
94 Statistic<>
95 NumTripCountsNotComputed("scalar-evolution",
96 "Number of loops without predictable loop counts");
Chris Lattner4021d1a2004-04-17 18:36:24 +000097 Statistic<>
98 NumBruteForceTripCountsComputed("scalar-evolution",
99 "Number of loops with trip counts computed by force");
100
101 cl::opt<unsigned>
102 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
103 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
104 cl::init(100));
Chris Lattnerd934c702004-04-02 20:23:17 +0000105}
106
107//===----------------------------------------------------------------------===//
108// SCEV class definitions
109//===----------------------------------------------------------------------===//
110
111//===----------------------------------------------------------------------===//
112// Implementation of the SCEV class.
113//
114namespace {
Chris Lattnerd934c702004-04-02 20:23:17 +0000115 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
116 /// than the complexity of the RHS. If the SCEVs have identical complexity,
117 /// order them by their addresses. This comparator is used to canonicalize
118 /// expressions.
119 struct SCEVComplexityCompare {
120 bool operator()(SCEV *LHS, SCEV *RHS) {
121 if (LHS->getSCEVType() < RHS->getSCEVType())
122 return true;
123 if (LHS->getSCEVType() == RHS->getSCEVType())
124 return LHS < RHS;
125 return false;
126 }
127 };
128}
129
130SCEV::~SCEV() {}
131void SCEV::dump() const {
132 print(std::cerr);
133}
134
135/// getValueRange - Return the tightest constant bounds that this value is
136/// known to have. This method is only valid on integer SCEV objects.
137ConstantRange SCEV::getValueRange() const {
138 const Type *Ty = getType();
139 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
140 Ty = Ty->getUnsignedVersion();
141 // Default to a full range if no better information is available.
142 return ConstantRange(getType());
143}
144
145
146SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
147
148bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukman5ebc25c2004-04-05 19:00:46 +0000150 return false;
Chris Lattnerd934c702004-04-02 20:23:17 +0000151}
152
153const Type *SCEVCouldNotCompute::getType() const {
154 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukman5ebc25c2004-04-05 19:00:46 +0000155 return 0;
Chris Lattnerd934c702004-04-02 20:23:17 +0000156}
157
158bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
159 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
160 return false;
161}
162
163Value *SCEVCouldNotCompute::expandCodeFor(ScalarEvolutionRewriter &SER,
164 Instruction *InsertPt) {
165 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
166 return 0;
167}
168
169
170void SCEVCouldNotCompute::print(std::ostream &OS) const {
171 OS << "***COULDNOTCOMPUTE***";
172}
173
174bool SCEVCouldNotCompute::classof(const SCEV *S) {
175 return S->getSCEVType() == scCouldNotCompute;
176}
177
178
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000179// SCEVConstants - Only allow the creation of one SCEVConstant for any
180// particular value. Don't use a SCEVHandle here, or else the object will
181// never be deleted!
182static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
183
Chris Lattnerd934c702004-04-02 20:23:17 +0000184
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000185SCEVConstant::~SCEVConstant() {
186 SCEVConstants.erase(V);
187}
Chris Lattnerd934c702004-04-02 20:23:17 +0000188
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000189SCEVHandle SCEVConstant::get(ConstantInt *V) {
190 // Make sure that SCEVConstant instances are all unsigned.
191 if (V->getType()->isSigned()) {
192 const Type *NewTy = V->getType()->getUnsignedVersion();
193 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
194 }
195
196 SCEVConstant *&R = SCEVConstants[V];
197 if (R == 0) R = new SCEVConstant(V);
198 return R;
199}
Chris Lattnerd934c702004-04-02 20:23:17 +0000200
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000201ConstantRange SCEVConstant::getValueRange() const {
202 return ConstantRange(V);
203}
Chris Lattnerd934c702004-04-02 20:23:17 +0000204
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000205const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattnerd934c702004-04-02 20:23:17 +0000206
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000207void SCEVConstant::print(std::ostream &OS) const {
208 WriteAsOperand(OS, V, false);
209}
Chris Lattnerd934c702004-04-02 20:23:17 +0000210
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000211// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
212// particular input. Don't use a SCEVHandle here, or else the object will
213// never be deleted!
214static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
Chris Lattnerd934c702004-04-02 20:23:17 +0000215
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000216SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
217 : SCEV(scTruncate), Op(op), Ty(ty) {
218 assert(Op->getType()->isInteger() && Ty->isInteger() &&
219 Ty->isUnsigned() &&
220 "Cannot truncate non-integer value!");
221 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
222 "This is not a truncating conversion!");
223}
Chris Lattnerd934c702004-04-02 20:23:17 +0000224
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000225SCEVTruncateExpr::~SCEVTruncateExpr() {
226 SCEVTruncates.erase(std::make_pair(Op, Ty));
227}
Chris Lattnerd934c702004-04-02 20:23:17 +0000228
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000229ConstantRange SCEVTruncateExpr::getValueRange() const {
230 return getOperand()->getValueRange().truncate(getType());
231}
Chris Lattnerd934c702004-04-02 20:23:17 +0000232
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000233void SCEVTruncateExpr::print(std::ostream &OS) const {
234 OS << "(truncate " << *Op << " to " << *Ty << ")";
235}
236
237// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
238// particular input. Don't use a SCEVHandle here, or else the object will never
239// be deleted!
240static std::map<std::pair<SCEV*, const Type*>,
241 SCEVZeroExtendExpr*> SCEVZeroExtends;
242
243SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
244 : SCEV(scTruncate), Op(Op), Ty(ty) {
245 assert(Op->getType()->isInteger() && Ty->isInteger() &&
246 Ty->isUnsigned() &&
247 "Cannot zero extend non-integer value!");
248 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
249 "This is not an extending conversion!");
250}
251
252SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
253 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
254}
255
256ConstantRange SCEVZeroExtendExpr::getValueRange() const {
257 return getOperand()->getValueRange().zeroExtend(getType());
258}
259
260void SCEVZeroExtendExpr::print(std::ostream &OS) const {
261 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
262}
263
264// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
265// particular input. Don't use a SCEVHandle here, or else the object will never
266// be deleted!
267static std::map<std::pair<unsigned, std::vector<SCEV*> >,
268 SCEVCommutativeExpr*> SCEVCommExprs;
269
270SCEVCommutativeExpr::~SCEVCommutativeExpr() {
271 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
272 std::vector<SCEV*>(Operands.begin(),
273 Operands.end())));
274}
275
276void SCEVCommutativeExpr::print(std::ostream &OS) const {
277 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
278 const char *OpStr = getOperationStr();
279 OS << "(" << *Operands[0];
280 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
281 OS << OpStr << *Operands[i];
282 OS << ")";
283}
284
285// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
286// input. Don't use a SCEVHandle here, or else the object will never be
287// deleted!
288static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
289
290SCEVUDivExpr::~SCEVUDivExpr() {
291 SCEVUDivs.erase(std::make_pair(LHS, RHS));
292}
293
294void SCEVUDivExpr::print(std::ostream &OS) const {
295 OS << "(" << *LHS << " /u " << *RHS << ")";
296}
297
298const Type *SCEVUDivExpr::getType() const {
299 const Type *Ty = LHS->getType();
300 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
301 return Ty;
302}
303
304// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
305// particular input. Don't use a SCEVHandle here, or else the object will never
306// be deleted!
307static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
308 SCEVAddRecExpr*> SCEVAddRecExprs;
309
310SCEVAddRecExpr::~SCEVAddRecExpr() {
311 SCEVAddRecExprs.erase(std::make_pair(L,
312 std::vector<SCEV*>(Operands.begin(),
313 Operands.end())));
314}
315
316bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
317 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
318 // contain L.
319 return !QueryLoop->contains(L->getHeader());
Chris Lattnerd934c702004-04-02 20:23:17 +0000320}
321
322
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000323void SCEVAddRecExpr::print(std::ostream &OS) const {
324 OS << "{" << *Operands[0];
325 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
326 OS << ",+," << *Operands[i];
327 OS << "}<" << L->getHeader()->getName() + ">";
328}
Chris Lattnerd934c702004-04-02 20:23:17 +0000329
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000330// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
331// value. Don't use a SCEVHandle here, or else the object will never be
332// deleted!
333static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
Chris Lattnerd934c702004-04-02 20:23:17 +0000334
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000335SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
Chris Lattnerd934c702004-04-02 20:23:17 +0000336
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000337bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
338 // All non-instruction values are loop invariant. All instructions are loop
339 // invariant if they are not contained in the specified loop.
340 if (Instruction *I = dyn_cast<Instruction>(V))
341 return !L->contains(I->getParent());
342 return true;
343}
Chris Lattnerd934c702004-04-02 20:23:17 +0000344
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000345const Type *SCEVUnknown::getType() const {
346 return V->getType();
347}
Chris Lattnerd934c702004-04-02 20:23:17 +0000348
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000349void SCEVUnknown::print(std::ostream &OS) const {
350 WriteAsOperand(OS, V, false);
Chris Lattnerd934c702004-04-02 20:23:17 +0000351}
352
353
Chris Lattnerd934c702004-04-02 20:23:17 +0000354
355//===----------------------------------------------------------------------===//
356// Simple SCEV method implementations
357//===----------------------------------------------------------------------===//
358
359/// getIntegerSCEV - Given an integer or FP type, create a constant for the
360/// specified signed integer value and return a SCEV for the constant.
361static SCEVHandle getIntegerSCEV(int Val, const Type *Ty) {
362 Constant *C;
363 if (Val == 0)
364 C = Constant::getNullValue(Ty);
365 else if (Ty->isFloatingPoint())
366 C = ConstantFP::get(Ty, Val);
367 else if (Ty->isSigned())
368 C = ConstantSInt::get(Ty, Val);
369 else {
370 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
371 C = ConstantExpr::getCast(C, Ty);
372 }
373 return SCEVUnknown::get(C);
374}
375
376/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
377/// input value to the specified type. If the type must be extended, it is zero
378/// extended.
379static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
380 const Type *SrcTy = V->getType();
381 assert(SrcTy->isInteger() && Ty->isInteger() &&
382 "Cannot truncate or zero extend with non-integer arguments!");
383 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
384 return V; // No conversion
385 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
386 return SCEVTruncateExpr::get(V, Ty);
387 return SCEVZeroExtendExpr::get(V, Ty);
388}
389
390/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
391///
392static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
393 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
394 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
395
396 return SCEVMulExpr::get(V, getIntegerSCEV(-1, V->getType()));
397}
398
399/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
400///
401static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
402 // X - Y --> X + -Y
403 return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
404}
405
406
407/// Binomial - Evaluate N!/((N-M)!*M!) . Note that N is often large and M is
408/// often very small, so we try to reduce the number of N! terms we need to
409/// evaluate by evaluating this as (N!/(N-M)!)/M!
410static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
411 uint64_t NVal = N->getRawValue();
412 uint64_t FirstTerm = 1;
413 for (unsigned i = 0; i != M; ++i)
414 FirstTerm *= NVal-i;
415
416 unsigned MFactorial = 1;
417 for (; M; --M)
418 MFactorial *= M;
419
420 Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
421 Result = ConstantExpr::getCast(Result, N->getType());
422 assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
423 return cast<ConstantInt>(Result);
424}
425
426/// PartialFact - Compute V!/(V-NumSteps)!
427static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
428 // Handle this case efficiently, it is common to have constant iteration
429 // counts while computing loop exit values.
430 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
431 uint64_t Val = SC->getValue()->getRawValue();
432 uint64_t Result = 1;
433 for (; NumSteps; --NumSteps)
434 Result *= Val-(NumSteps-1);
435 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
436 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
437 }
438
439 const Type *Ty = V->getType();
440 if (NumSteps == 0)
441 return getIntegerSCEV(1, Ty);
442
443 SCEVHandle Result = V;
444 for (unsigned i = 1; i != NumSteps; ++i)
445 Result = SCEVMulExpr::get(Result, getMinusSCEV(V, getIntegerSCEV(i, Ty)));
446 return Result;
447}
448
449
450/// evaluateAtIteration - Return the value of this chain of recurrences at
451/// the specified iteration number. We can evaluate this recurrence by
452/// multiplying each element in the chain by the binomial coefficient
453/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
454///
455/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
456///
457/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
458/// Is the binomial equation safe using modular arithmetic??
459///
460SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
461 SCEVHandle Result = getStart();
462 int Divisor = 1;
463 const Type *Ty = It->getType();
464 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
465 SCEVHandle BC = PartialFact(It, i);
466 Divisor *= i;
467 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
468 getIntegerSCEV(Divisor, Ty));
469 Result = SCEVAddExpr::get(Result, Val);
470 }
471 return Result;
472}
473
474
475//===----------------------------------------------------------------------===//
476// SCEV Expression folder implementations
477//===----------------------------------------------------------------------===//
478
479SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
480 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
481 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
482
483 // If the input value is a chrec scev made out of constants, truncate
484 // all of the constants.
485 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
486 std::vector<SCEVHandle> Operands;
487 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
488 // FIXME: This should allow truncation of other expression types!
489 if (isa<SCEVConstant>(AddRec->getOperand(i)))
490 Operands.push_back(get(AddRec->getOperand(i), Ty));
491 else
492 break;
493 if (Operands.size() == AddRec->getNumOperands())
494 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
495 }
496
497 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
498 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
499 return Result;
500}
501
502SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
503 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
504 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
505
506 // FIXME: If the input value is a chrec scev, and we can prove that the value
507 // did not overflow the old, smaller, value, we can zero extend all of the
508 // operands (often constants). This would allow analysis of something like
509 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
510
511 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
512 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
513 return Result;
514}
515
516// get - Get a canonical add expression, or something simpler if possible.
517SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
518 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +0000519 if (Ops.size() == 1) return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +0000520
521 // Sort by complexity, this groups all similar expression types together.
522 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
523
524 // If there are any constants, fold them together.
525 unsigned Idx = 0;
526 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
527 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +0000528 assert(Idx < Ops.size());
Chris Lattnerd934c702004-04-02 20:23:17 +0000529 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
530 // We found two constants, fold them together!
531 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
532 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
533 Ops[0] = SCEVConstant::get(CI);
534 Ops.erase(Ops.begin()+1); // Erase the folded element
535 if (Ops.size() == 1) return Ops[0];
536 } else {
537 // If we couldn't fold the expression, move to the next constant. Note
538 // that this is impossible to happen in practice because we always
539 // constant fold constant ints to constant ints.
540 ++Idx;
541 }
542 }
543
544 // If we are left with a constant zero being added, strip it off.
545 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
546 Ops.erase(Ops.begin());
547 --Idx;
548 }
549 }
550
Chris Lattner74498e12004-04-07 16:16:11 +0000551 if (Ops.size() == 1) return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +0000552
553 // Okay, check to see if the same value occurs in the operand list twice. If
554 // so, merge them together into an multiply expression. Since we sorted the
555 // list, these values are required to be adjacent.
556 const Type *Ty = Ops[0]->getType();
557 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
558 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
559 // Found a match, merge the two values into a multiply, and add any
560 // remaining values to the result.
561 SCEVHandle Two = getIntegerSCEV(2, Ty);
562 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
563 if (Ops.size() == 2)
564 return Mul;
565 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
566 Ops.push_back(Mul);
567 return SCEVAddExpr::get(Ops);
568 }
569
570 // Okay, now we know the first non-constant operand. If there are add
571 // operands they would be next.
572 if (Idx < Ops.size()) {
573 bool DeletedAdd = false;
574 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
575 // If we have an add, expand the add operands onto the end of the operands
576 // list.
577 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
578 Ops.erase(Ops.begin()+Idx);
579 DeletedAdd = true;
580 }
581
582 // If we deleted at least one add, we added operands to the end of the list,
583 // and they are not necessarily sorted. Recurse to resort and resimplify
584 // any operands we just aquired.
585 if (DeletedAdd)
586 return get(Ops);
587 }
588
589 // Skip over the add expression until we get to a multiply.
590 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
591 ++Idx;
592
593 // If we are adding something to a multiply expression, make sure the
594 // something is not already an operand of the multiply. If so, merge it into
595 // the multiply.
596 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
597 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
598 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
599 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
600 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
601 if (MulOpSCEV == Ops[AddOp] &&
602 (Mul->getNumOperands() != 2 || !isa<SCEVConstant>(MulOpSCEV))) {
603 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
604 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
605 if (Mul->getNumOperands() != 2) {
606 // If the multiply has more than two operands, we must get the
607 // Y*Z term.
608 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
609 MulOps.erase(MulOps.begin()+MulOp);
610 InnerMul = SCEVMulExpr::get(MulOps);
611 }
612 SCEVHandle One = getIntegerSCEV(1, Ty);
613 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
614 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
615 if (Ops.size() == 2) return OuterMul;
616 if (AddOp < Idx) {
617 Ops.erase(Ops.begin()+AddOp);
618 Ops.erase(Ops.begin()+Idx-1);
619 } else {
620 Ops.erase(Ops.begin()+Idx);
621 Ops.erase(Ops.begin()+AddOp-1);
622 }
623 Ops.push_back(OuterMul);
624 return SCEVAddExpr::get(Ops);
625 }
626
627 // Check this multiply against other multiplies being added together.
628 for (unsigned OtherMulIdx = Idx+1;
629 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
630 ++OtherMulIdx) {
631 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
632 // If MulOp occurs in OtherMul, we can fold the two multiplies
633 // together.
634 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
635 OMulOp != e; ++OMulOp)
636 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
637 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
638 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
639 if (Mul->getNumOperands() != 2) {
640 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
641 MulOps.erase(MulOps.begin()+MulOp);
642 InnerMul1 = SCEVMulExpr::get(MulOps);
643 }
644 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
645 if (OtherMul->getNumOperands() != 2) {
646 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
647 OtherMul->op_end());
648 MulOps.erase(MulOps.begin()+OMulOp);
649 InnerMul2 = SCEVMulExpr::get(MulOps);
650 }
651 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
652 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
653 if (Ops.size() == 2) return OuterMul;
654 Ops.erase(Ops.begin()+Idx);
655 Ops.erase(Ops.begin()+OtherMulIdx-1);
656 Ops.push_back(OuterMul);
657 return SCEVAddExpr::get(Ops);
658 }
659 }
660 }
661 }
662
663 // If there are any add recurrences in the operands list, see if any other
664 // added values are loop invariant. If so, we can fold them into the
665 // recurrence.
666 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
667 ++Idx;
668
669 // Scan over all recurrences, trying to fold loop invariants into them.
670 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
671 // Scan all of the other operands to this add and add them to the vector if
672 // they are loop invariant w.r.t. the recurrence.
673 std::vector<SCEVHandle> LIOps;
674 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
675 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
676 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
677 LIOps.push_back(Ops[i]);
678 Ops.erase(Ops.begin()+i);
679 --i; --e;
680 }
681
682 // If we found some loop invariants, fold them into the recurrence.
683 if (!LIOps.empty()) {
684 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
685 LIOps.push_back(AddRec->getStart());
686
687 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
688 AddRecOps[0] = SCEVAddExpr::get(LIOps);
689
690 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
691 // If all of the other operands were loop invariant, we are done.
692 if (Ops.size() == 1) return NewRec;
693
694 // Otherwise, add the folded AddRec by the non-liv parts.
695 for (unsigned i = 0;; ++i)
696 if (Ops[i] == AddRec) {
697 Ops[i] = NewRec;
698 break;
699 }
700 return SCEVAddExpr::get(Ops);
701 }
702
703 // Okay, if there weren't any loop invariants to be folded, check to see if
704 // there are multiple AddRec's with the same loop induction variable being
705 // added together. If so, we can fold them.
706 for (unsigned OtherIdx = Idx+1;
707 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
708 if (OtherIdx != Idx) {
709 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
710 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
711 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
712 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
713 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
714 if (i >= NewOps.size()) {
715 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
716 OtherAddRec->op_end());
717 break;
718 }
719 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
720 }
721 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
722
723 if (Ops.size() == 2) return NewAddRec;
724
725 Ops.erase(Ops.begin()+Idx);
726 Ops.erase(Ops.begin()+OtherIdx-1);
727 Ops.push_back(NewAddRec);
728 return SCEVAddExpr::get(Ops);
729 }
730 }
731
732 // Otherwise couldn't fold anything into this recurrence. Move onto the
733 // next one.
734 }
735
736 // Okay, it looks like we really DO need an add expr. Check to see if we
737 // already have one, otherwise create a new one.
738 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
739 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
740 SCEVOps)];
741 if (Result == 0) Result = new SCEVAddExpr(Ops);
742 return Result;
743}
744
745
746SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
747 assert(!Ops.empty() && "Cannot get empty mul!");
748
749 // Sort by complexity, this groups all similar expression types together.
750 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
751
752 // If there are any constants, fold them together.
753 unsigned Idx = 0;
754 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
755
756 // C1*(C2+V) -> C1*C2 + C1*V
757 if (Ops.size() == 2)
758 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
759 if (Add->getNumOperands() == 2 &&
760 isa<SCEVConstant>(Add->getOperand(0)))
761 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
762 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
763
764
765 ++Idx;
766 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
767 // We found two constants, fold them together!
768 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
769 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
770 Ops[0] = SCEVConstant::get(CI);
771 Ops.erase(Ops.begin()+1); // Erase the folded element
772 if (Ops.size() == 1) return Ops[0];
773 } else {
774 // If we couldn't fold the expression, move to the next constant. Note
775 // that this is impossible to happen in practice because we always
776 // constant fold constant ints to constant ints.
777 ++Idx;
778 }
779 }
780
781 // If we are left with a constant one being multiplied, strip it off.
782 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
783 Ops.erase(Ops.begin());
784 --Idx;
785 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
786 // If we have a multiply of zero, it will always be zero.
787 return Ops[0];
788 }
789 }
790
791 // Skip over the add expression until we get to a multiply.
792 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
793 ++Idx;
794
795 if (Ops.size() == 1)
796 return Ops[0];
797
798 // If there are mul operands inline them all into this expression.
799 if (Idx < Ops.size()) {
800 bool DeletedMul = false;
801 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
802 // If we have an mul, expand the mul operands onto the end of the operands
803 // list.
804 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
805 Ops.erase(Ops.begin()+Idx);
806 DeletedMul = true;
807 }
808
809 // If we deleted at least one mul, we added operands to the end of the list,
810 // and they are not necessarily sorted. Recurse to resort and resimplify
811 // any operands we just aquired.
812 if (DeletedMul)
813 return get(Ops);
814 }
815
816 // If there are any add recurrences in the operands list, see if any other
817 // added values are loop invariant. If so, we can fold them into the
818 // recurrence.
819 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
820 ++Idx;
821
822 // Scan over all recurrences, trying to fold loop invariants into them.
823 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
824 // Scan all of the other operands to this mul and add them to the vector if
825 // they are loop invariant w.r.t. the recurrence.
826 std::vector<SCEVHandle> LIOps;
827 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
828 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
829 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
830 LIOps.push_back(Ops[i]);
831 Ops.erase(Ops.begin()+i);
832 --i; --e;
833 }
834
835 // If we found some loop invariants, fold them into the recurrence.
836 if (!LIOps.empty()) {
837 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
838 std::vector<SCEVHandle> NewOps;
839 NewOps.reserve(AddRec->getNumOperands());
840 if (LIOps.size() == 1) {
841 SCEV *Scale = LIOps[0];
842 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
843 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
844 } else {
845 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
846 std::vector<SCEVHandle> MulOps(LIOps);
847 MulOps.push_back(AddRec->getOperand(i));
848 NewOps.push_back(SCEVMulExpr::get(MulOps));
849 }
850 }
851
852 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
853
854 // If all of the other operands were loop invariant, we are done.
855 if (Ops.size() == 1) return NewRec;
856
857 // Otherwise, multiply the folded AddRec by the non-liv parts.
858 for (unsigned i = 0;; ++i)
859 if (Ops[i] == AddRec) {
860 Ops[i] = NewRec;
861 break;
862 }
863 return SCEVMulExpr::get(Ops);
864 }
865
866 // Okay, if there weren't any loop invariants to be folded, check to see if
867 // there are multiple AddRec's with the same loop induction variable being
868 // multiplied together. If so, we can fold them.
869 for (unsigned OtherIdx = Idx+1;
870 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
871 if (OtherIdx != Idx) {
872 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
873 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
874 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
875 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
876 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
877 G->getStart());
878 SCEVHandle B = F->getStepRecurrence();
879 SCEVHandle D = G->getStepRecurrence();
880 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
881 SCEVMulExpr::get(G, B),
882 SCEVMulExpr::get(B, D));
883 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
884 F->getLoop());
885 if (Ops.size() == 2) return NewAddRec;
886
887 Ops.erase(Ops.begin()+Idx);
888 Ops.erase(Ops.begin()+OtherIdx-1);
889 Ops.push_back(NewAddRec);
890 return SCEVMulExpr::get(Ops);
891 }
892 }
893
894 // Otherwise couldn't fold anything into this recurrence. Move onto the
895 // next one.
896 }
897
898 // Okay, it looks like we really DO need an mul expr. Check to see if we
899 // already have one, otherwise create a new one.
900 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
901 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
902 SCEVOps)];
903 if (Result == 0) Result = new SCEVMulExpr(Ops);
904 return Result;
905}
906
907SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
908 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
909 if (RHSC->getValue()->equalsInt(1))
910 return LHS; // X /u 1 --> x
911 if (RHSC->getValue()->isAllOnesValue())
912 return getNegativeSCEV(LHS); // X /u -1 --> -x
913
914 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
915 Constant *LHSCV = LHSC->getValue();
916 Constant *RHSCV = RHSC->getValue();
917 if (LHSCV->getType()->isSigned())
918 LHSCV = ConstantExpr::getCast(LHSCV,
919 LHSCV->getType()->getUnsignedVersion());
920 if (RHSCV->getType()->isSigned())
921 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
922 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
923 }
924 }
925
926 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
927
928 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
929 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
930 return Result;
931}
932
933
934/// SCEVAddRecExpr::get - Get a add recurrence expression for the
935/// specified loop. Simplify the expression as much as possible.
936SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
937 const SCEVHandle &Step, const Loop *L) {
938 std::vector<SCEVHandle> Operands;
939 Operands.push_back(Start);
940 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
941 if (StepChrec->getLoop() == L) {
942 Operands.insert(Operands.end(), StepChrec->op_begin(),
943 StepChrec->op_end());
944 return get(Operands, L);
945 }
946
947 Operands.push_back(Step);
948 return get(Operands, L);
949}
950
951/// SCEVAddRecExpr::get - Get a add recurrence expression for the
952/// specified loop. Simplify the expression as much as possible.
953SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
954 const Loop *L) {
955 if (Operands.size() == 1) return Operands[0];
956
957 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
958 if (StepC->getValue()->isNullValue()) {
959 Operands.pop_back();
960 return get(Operands, L); // { X,+,0 } --> X
961 }
962
963 SCEVAddRecExpr *&Result =
964 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
965 Operands.end()))];
966 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
967 return Result;
968}
969
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000970SCEVHandle SCEVUnknown::get(Value *V) {
971 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
972 return SCEVConstant::get(CI);
973 SCEVUnknown *&Result = SCEVUnknowns[V];
974 if (Result == 0) Result = new SCEVUnknown(V);
975 return Result;
976}
977
Chris Lattnerd934c702004-04-02 20:23:17 +0000978
979//===----------------------------------------------------------------------===//
980// Non-trivial closed-form SCEV Expanders
981//===----------------------------------------------------------------------===//
982
983Value *SCEVTruncateExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
984 Instruction *InsertPt) {
985 Value *V = SER.ExpandCodeFor(getOperand(), InsertPt);
986 return new CastInst(V, getType(), "tmp.", InsertPt);
987}
988
989Value *SCEVZeroExtendExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
990 Instruction *InsertPt) {
991 Value *V = SER.ExpandCodeFor(getOperand(), InsertPt,
992 getOperand()->getType()->getUnsignedVersion());
993 return new CastInst(V, getType(), "tmp.", InsertPt);
994}
995
996Value *SCEVAddExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
997 Instruction *InsertPt) {
998 const Type *Ty = getType();
999 Value *V = SER.ExpandCodeFor(getOperand(getNumOperands()-1), InsertPt, Ty);
1000
1001 // Emit a bunch of add instructions
1002 for (int i = getNumOperands()-2; i >= 0; --i)
1003 V = BinaryOperator::create(Instruction::Add, V,
1004 SER.ExpandCodeFor(getOperand(i), InsertPt, Ty),
1005 "tmp.", InsertPt);
1006 return V;
1007}
1008
1009Value *SCEVMulExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1010 Instruction *InsertPt) {
1011 const Type *Ty = getType();
1012 int FirstOp = 0; // Set if we should emit a subtract.
1013 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getOperand(0)))
1014 if (SC->getValue()->isAllOnesValue())
1015 FirstOp = 1;
1016
1017 int i = getNumOperands()-2;
1018 Value *V = SER.ExpandCodeFor(getOperand(i+1), InsertPt, Ty);
1019
1020 // Emit a bunch of multiply instructions
1021 for (; i >= FirstOp; --i)
1022 V = BinaryOperator::create(Instruction::Mul, V,
1023 SER.ExpandCodeFor(getOperand(i), InsertPt, Ty),
1024 "tmp.", InsertPt);
1025 // -1 * ... ---> 0 - ...
1026 if (FirstOp == 1)
1027 V = BinaryOperator::create(Instruction::Sub, Constant::getNullValue(Ty), V,
1028 "tmp.", InsertPt);
1029 return V;
1030}
1031
1032Value *SCEVUDivExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1033 Instruction *InsertPt) {
1034 const Type *Ty = getType();
1035 Value *LHS = SER.ExpandCodeFor(getLHS(), InsertPt, Ty);
1036 Value *RHS = SER.ExpandCodeFor(getRHS(), InsertPt, Ty);
1037 return BinaryOperator::create(Instruction::Div, LHS, RHS, "tmp.", InsertPt);
1038}
1039
1040Value *SCEVAddRecExpr::expandCodeFor(ScalarEvolutionRewriter &SER,
1041 Instruction *InsertPt) {
1042 const Type *Ty = getType();
1043 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
1044 assert(Ty->isIntegral() && "Cannot expand fp recurrences yet!");
1045
1046 // {X,+,F} --> X + {0,+,F}
1047 if (!isa<SCEVConstant>(getStart()) ||
1048 !cast<SCEVConstant>(getStart())->getValue()->isNullValue()) {
1049 Value *Start = SER.ExpandCodeFor(getStart(), InsertPt, Ty);
1050 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
1051 NewOps[0] = getIntegerSCEV(0, getType());
1052 Value *Rest = SER.ExpandCodeFor(SCEVAddRecExpr::get(NewOps, getLoop()),
1053 InsertPt, getType());
1054
1055 // FIXME: look for an existing add to use.
1056 return BinaryOperator::create(Instruction::Add, Rest, Start, "tmp.",
1057 InsertPt);
1058 }
1059
1060 // {0,+,1} --> Insert a canonical induction variable into the loop!
1061 if (getNumOperands() == 2 && getOperand(1) == getIntegerSCEV(1, getType())) {
1062 // Create and insert the PHI node for the induction variable in the
1063 // specified loop.
1064 BasicBlock *Header = getLoop()->getHeader();
1065 PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
1066 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
1067
Chris Lattner8a9fd942004-04-14 21:11:25 +00001068 pred_iterator HPI = pred_begin(Header);
1069 assert(HPI != pred_end(Header) && "Loop with zero preds???");
1070 if (!getLoop()->contains(*HPI)) ++HPI;
1071 assert(HPI != pred_end(Header) && getLoop()->contains(*HPI) &&
1072 "No backedge in loop?");
Chris Lattnerd934c702004-04-02 20:23:17 +00001073
Chris Lattner8a9fd942004-04-14 21:11:25 +00001074 // Insert a unit add instruction right before the terminator corresponding
1075 // to the back-edge.
1076 Constant *One = Ty->isFloatingPoint() ? (Constant*)ConstantFP::get(Ty, 1.0)
1077 : (Constant*)ConstantInt::get(Ty, 1);
Chris Lattnerd934c702004-04-02 20:23:17 +00001078 Instruction *Add = BinaryOperator::create(Instruction::Add, PN, One,
Chris Lattner8a9fd942004-04-14 21:11:25 +00001079 "indvar.next",
1080 (*HPI)->getTerminator());
Chris Lattnerd934c702004-04-02 20:23:17 +00001081
1082 pred_iterator PI = pred_begin(Header);
1083 if (*PI == L->getLoopPreheader())
1084 ++PI;
1085 PN->addIncoming(Add, *PI);
1086 return PN;
1087 }
1088
1089 // Get the canonical induction variable I for this loop.
1090 Value *I = SER.GetOrInsertCanonicalInductionVariable(getLoop(), Ty);
1091
1092 if (getNumOperands() == 2) { // {0,+,F} --> i*F
1093 Value *F = SER.ExpandCodeFor(getOperand(1), InsertPt, Ty);
1094 return BinaryOperator::create(Instruction::Mul, I, F, "tmp.", InsertPt);
1095 }
1096
1097 // If this is a chain of recurrences, turn it into a closed form, using the
1098 // folders, then expandCodeFor the closed form. This allows the folders to
1099 // simplify the expression without having to build a bunch of special code
1100 // into this folder.
1101 SCEVHandle IH = SCEVUnknown::get(I); // Get I as a "symbolic" SCEV.
1102
1103 SCEVHandle V = evaluateAtIteration(IH);
Chris Lattner09169212004-04-02 20:26:46 +00001104 //std::cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00001105
1106 return SER.ExpandCodeFor(V, InsertPt, Ty);
1107}
1108
1109
1110//===----------------------------------------------------------------------===//
1111// ScalarEvolutionsImpl Definition and Implementation
1112//===----------------------------------------------------------------------===//
1113//
1114/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1115/// evolution code.
1116///
1117namespace {
1118 struct ScalarEvolutionsImpl {
1119 /// 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 public:
1140 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1141 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1142
1143 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1144 /// expression and create a new one.
1145 SCEVHandle getSCEV(Value *V);
1146
1147 /// getSCEVAtScope - Compute the value of the specified expression within
1148 /// the indicated loop (which may be null to indicate in no loop). If the
1149 /// expression cannot be evaluated, return UnknownValue itself.
1150 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1151
1152
1153 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1154 /// an analyzable loop-invariant iteration count.
1155 bool hasLoopInvariantIterationCount(const Loop *L);
1156
1157 /// getIterationCount - If the specified loop has a predictable iteration
1158 /// count, return it. Note that it is not valid to call this method on a
1159 /// loop without a loop-invariant iteration count.
1160 SCEVHandle getIterationCount(const Loop *L);
1161
1162 /// deleteInstructionFromRecords - This method should be called by the
1163 /// client before it removes an instruction from the program, to make sure
1164 /// that no dangling references are left around.
1165 void deleteInstructionFromRecords(Instruction *I);
1166
1167 private:
1168 /// createSCEV - We know that there is no SCEV for the specified value.
1169 /// Analyze the expression.
1170 SCEVHandle createSCEV(Value *V);
1171 SCEVHandle createNodeForCast(CastInst *CI);
1172
1173 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1174 /// SCEVs.
1175 SCEVHandle createNodeForPHI(PHINode *PN);
1176 void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1177 std::set<Instruction*> &UpdatedInsts);
1178
1179 /// ComputeIterationCount - Compute the number of times the specified loop
1180 /// will iterate.
1181 SCEVHandle ComputeIterationCount(const Loop *L);
1182
Chris Lattner4021d1a2004-04-17 18:36:24 +00001183 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1184 /// constant number of times (the condition evolves only from constants),
1185 /// try to evaluate a few iterations of the loop until we get the exit
1186 /// condition gets a value of ExitWhen (true or false). If we cannot
1187 /// evaluate the trip count of the loop, return UnknownValue.
1188 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1189 bool ExitWhen);
1190
Chris Lattnerd934c702004-04-02 20:23:17 +00001191 /// HowFarToZero - Return the number of times a backedge comparing the
1192 /// specified value to zero will execute. If not computable, return
1193 /// UnknownValue
1194 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1195
1196 /// HowFarToNonZero - Return the number of times a backedge checking the
1197 /// specified value for nonzero will execute. If not computable, return
1198 /// UnknownValue
1199 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1200 };
1201}
1202
1203//===----------------------------------------------------------------------===//
1204// Basic SCEV Analysis and PHI Idiom Recognition Code
1205//
1206
1207/// deleteInstructionFromRecords - This method should be called by the
1208/// client before it removes an instruction from the program, to make sure
1209/// that no dangling references are left around.
1210void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1211 Scalars.erase(I);
1212}
1213
1214
1215/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1216/// expression and create a new one.
1217SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1218 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1219
1220 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1221 if (I != Scalars.end()) return I->second;
1222 SCEVHandle S = createSCEV(V);
1223 Scalars.insert(std::make_pair(V, S));
1224 return S;
1225}
1226
1227
1228/// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1229/// entries in the scalar map that refer to the "symbolic" PHI value instead of
1230/// the recurrence value. After we resolve the PHI we must loop over all of the
1231/// using instructions that have scalar map entries and update them.
1232void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1233 PHINode *PN,
1234 std::set<Instruction*> &UpdatedInsts) {
1235 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1236 if (SI == Scalars.end()) return; // This scalar wasn't previous processed.
1237 if (UpdatedInsts.insert(I).second) {
1238 Scalars.erase(SI); // Remove the old entry
1239 getSCEV(I); // Calculate the new entry
1240
1241 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1242 UI != E; ++UI)
1243 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1244 }
1245}
1246
1247
1248/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1249/// a loop header, making it a potential recurrence, or it doesn't.
1250///
1251SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1252 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1253 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1254 if (L->getHeader() == PN->getParent()) {
1255 // If it lives in the loop header, it has two incoming values, one
1256 // from outside the loop, and one from inside.
1257 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1258 unsigned BackEdge = IncomingEdge^1;
1259
1260 // While we are analyzing this PHI node, handle its value symbolically.
1261 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1262 assert(Scalars.find(PN) == Scalars.end() &&
1263 "PHI node already processed?");
1264 Scalars.insert(std::make_pair(PN, SymbolicName));
1265
1266 // Using this symbolic name for the PHI, analyze the value coming around
1267 // the back-edge.
1268 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1269
1270 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1271 // has a special value for the first iteration of the loop.
1272
1273 // If the value coming around the backedge is an add with the symbolic
1274 // value we just inserted, then we found a simple induction variable!
1275 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1276 // If there is a single occurrence of the symbolic value, replace it
1277 // with a recurrence.
1278 unsigned FoundIndex = Add->getNumOperands();
1279 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1280 if (Add->getOperand(i) == SymbolicName)
1281 if (FoundIndex == e) {
1282 FoundIndex = i;
1283 break;
1284 }
1285
1286 if (FoundIndex != Add->getNumOperands()) {
1287 // Create an add with everything but the specified operand.
1288 std::vector<SCEVHandle> Ops;
1289 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1290 if (i != FoundIndex)
1291 Ops.push_back(Add->getOperand(i));
1292 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1293
1294 // This is not a valid addrec if the step amount is varying each
1295 // loop iteration, but is not itself an addrec in this loop.
1296 if (Accum->isLoopInvariant(L) ||
1297 (isa<SCEVAddRecExpr>(Accum) &&
1298 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1299 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1300 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1301
1302 // Okay, for the entire analysis of this edge we assumed the PHI
1303 // to be symbolic. We now need to go back and update all of the
1304 // entries for the scalars that use the PHI (except for the PHI
1305 // itself) to use the new analyzed value instead of the "symbolic"
1306 // value.
1307 Scalars.find(PN)->second = PHISCEV; // Update the PHI value
1308 std::set<Instruction*> UpdatedInsts;
1309 UpdatedInsts.insert(PN);
1310 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1311 UI != E; ++UI)
1312 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1313 UpdatedInsts);
1314 return PHISCEV;
1315 }
1316 }
1317 }
1318
1319 return SymbolicName;
1320 }
1321
1322 // If it's not a loop phi, we can't handle it yet.
1323 return SCEVUnknown::get(PN);
1324}
1325
1326/// createNodeForCast - Handle the various forms of casts that we support.
1327///
1328SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1329 const Type *SrcTy = CI->getOperand(0)->getType();
1330 const Type *DestTy = CI->getType();
1331
1332 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1333 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1334 return getSCEV(CI->getOperand(0));
1335
1336 if (SrcTy->isInteger() && DestTy->isInteger()) {
1337 // Otherwise, if this is a truncating integer cast, we can represent this
1338 // cast.
1339 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1340 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1341 CI->getType()->getUnsignedVersion());
1342 if (SrcTy->isUnsigned() &&
1343 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1344 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1345 CI->getType()->getUnsignedVersion());
1346 }
1347
1348 // If this is an sign or zero extending cast and we can prove that the value
1349 // will never overflow, we could do similar transformations.
1350
1351 // Otherwise, we can't handle this cast!
1352 return SCEVUnknown::get(CI);
1353}
1354
1355
1356/// createSCEV - We know that there is no SCEV for the specified value.
1357/// Analyze the expression.
1358///
1359SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1360 if (Instruction *I = dyn_cast<Instruction>(V)) {
1361 switch (I->getOpcode()) {
1362 case Instruction::Add:
1363 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1364 getSCEV(I->getOperand(1)));
1365 case Instruction::Mul:
1366 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1367 getSCEV(I->getOperand(1)));
1368 case Instruction::Div:
1369 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1370 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1371 getSCEV(I->getOperand(1)));
1372 break;
1373
1374 case Instruction::Sub:
1375 return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1376
1377 case Instruction::Shl:
1378 // Turn shift left of a constant amount into a multiply.
1379 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1380 Constant *X = ConstantInt::get(V->getType(), 1);
1381 X = ConstantExpr::getShl(X, SA);
1382 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1383 }
1384 break;
1385
1386 case Instruction::Shr:
1387 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1388 if (V->getType()->isUnsigned()) {
1389 Constant *X = ConstantInt::get(V->getType(), 1);
1390 X = ConstantExpr::getShl(X, SA);
1391 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1392 }
1393 break;
1394
1395 case Instruction::Cast:
1396 return createNodeForCast(cast<CastInst>(I));
1397
1398 case Instruction::PHI:
1399 return createNodeForPHI(cast<PHINode>(I));
1400
1401 default: // We cannot analyze this expression.
1402 break;
1403 }
1404 }
1405
1406 return SCEVUnknown::get(V);
1407}
1408
1409
1410
1411//===----------------------------------------------------------------------===//
1412// Iteration Count Computation Code
1413//
1414
1415/// getIterationCount - If the specified loop has a predictable iteration
1416/// count, return it. Note that it is not valid to call this method on a
1417/// loop without a loop-invariant iteration count.
1418SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1419 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1420 if (I == IterationCounts.end()) {
1421 SCEVHandle ItCount = ComputeIterationCount(L);
1422 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1423 if (ItCount != UnknownValue) {
1424 assert(ItCount->isLoopInvariant(L) &&
1425 "Computed trip count isn't loop invariant for loop!");
1426 ++NumTripCountsComputed;
1427 } else if (isa<PHINode>(L->getHeader()->begin())) {
1428 // Only count loops that have phi nodes as not being computable.
1429 ++NumTripCountsNotComputed;
1430 }
1431 }
1432 return I->second;
1433}
1434
1435/// ComputeIterationCount - Compute the number of times the specified loop
1436/// will iterate.
1437SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1438 // If the loop has a non-one exit block count, we can't analyze it.
1439 if (L->getExitBlocks().size() != 1) return UnknownValue;
1440
1441 // Okay, there is one exit block. Try to find the condition that causes the
1442 // loop to be exited.
1443 BasicBlock *ExitBlock = L->getExitBlocks()[0];
1444
1445 BasicBlock *ExitingBlock = 0;
1446 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1447 PI != E; ++PI)
1448 if (L->contains(*PI)) {
1449 if (ExitingBlock == 0)
1450 ExitingBlock = *PI;
1451 else
1452 return UnknownValue; // More than one block exiting!
1453 }
1454 assert(ExitingBlock && "No exits from loop, something is broken!");
1455
1456 // Okay, we've computed the exiting block. See what condition causes us to
1457 // exit.
1458 //
1459 // FIXME: we should be able to handle switch instructions (with a single exit)
1460 // FIXME: We should handle cast of int to bool as well
1461 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1462 if (ExitBr == 0) return UnknownValue;
1463 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1464 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner4021d1a2004-04-17 18:36:24 +00001465 if (ExitCond == 0) // Not a setcc
1466 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1467 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattnerd934c702004-04-02 20:23:17 +00001468
1469 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1470 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1471
1472 // Try to evaluate any dependencies out of the loop.
1473 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1474 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1475 Tmp = getSCEVAtScope(RHS, L);
1476 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1477
1478 // If the condition was exit on true, convert the condition to exit on false.
1479 Instruction::BinaryOps Cond;
1480 if (ExitBr->getSuccessor(1) == ExitBlock)
1481 Cond = ExitCond->getOpcode();
1482 else
1483 Cond = ExitCond->getInverseCondition();
1484
1485 // At this point, we would like to compute how many iterations of the loop the
1486 // predicate will return true for these inputs.
1487 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1488 // If there is a constant, force it into the RHS.
1489 std::swap(LHS, RHS);
1490 Cond = SetCondInst::getSwappedCondition(Cond);
1491 }
1492
1493 // FIXME: think about handling pointer comparisons! i.e.:
1494 // while (P != P+100) ++P;
1495
1496 // If we have a comparison of a chrec against a constant, try to use value
1497 // ranges to answer this query.
1498 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1499 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1500 if (AddRec->getLoop() == L) {
1501 // Form the comparison range using the constant of the correct type so
1502 // that the ConstantRange class knows to do a signed or unsigned
1503 // comparison.
1504 ConstantInt *CompVal = RHSC->getValue();
1505 const Type *RealTy = ExitCond->getOperand(0)->getType();
1506 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1507 if (CompVal) {
1508 // Form the constant range.
1509 ConstantRange CompRange(Cond, CompVal);
1510
1511 // Now that we have it, if it's signed, convert it to an unsigned
1512 // range.
1513 if (CompRange.getLower()->getType()->isSigned()) {
1514 const Type *NewTy = RHSC->getValue()->getType();
1515 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1516 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1517 CompRange = ConstantRange(NewL, NewU);
1518 }
1519
1520 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1521 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1522 }
1523 }
1524
1525 switch (Cond) {
1526 case Instruction::SetNE: // while (X != Y)
1527 // Convert to: while (X-Y != 0)
Chris Lattner4021d1a2004-04-17 18:36:24 +00001528 if (LHS->getType()->isInteger()) {
1529 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1530 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1531 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001532 break;
1533 case Instruction::SetEQ:
1534 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner4021d1a2004-04-17 18:36:24 +00001535 if (LHS->getType()->isInteger()) {
1536 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1537 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1538 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001539 break;
1540 default:
Chris Lattner09169212004-04-02 20:26:46 +00001541#if 0
Chris Lattnerd934c702004-04-02 20:23:17 +00001542 std::cerr << "ComputeIterationCount ";
1543 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1544 std::cerr << "[unsigned] ";
1545 std::cerr << *LHS << " "
1546 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00001547#endif
Chris Lattner0defaa12004-04-03 00:43:03 +00001548 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00001549 }
Chris Lattner4021d1a2004-04-17 18:36:24 +00001550
1551 return ComputeIterationCountExhaustively(L, ExitCond,
1552 ExitBr->getSuccessor(0) == ExitBlock);
1553}
1554
1555
1556/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1557/// in the loop that V is derived from. We allow arbitrary operations along the
1558/// way, but the operands of an operation must either be constants or a value
1559/// derived from a constant PHI. If this expression does not fit with these
1560/// constraints, return null.
1561static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1562 // If this is not an instruction, or if this is an instruction outside of the
1563 // loop, it can't be derived from a loop PHI.
1564 Instruction *I = dyn_cast<Instruction>(V);
1565 if (I == 0 || !L->contains(I->getParent())) return 0;
1566
1567 if (PHINode *PN = dyn_cast<PHINode>(I))
1568 if (L->getHeader() == I->getParent())
1569 return PN;
1570 else
1571 // We don't currently keep track of the control flow needed to evaluate
1572 // PHIs, so we cannot handle PHIs inside of loops.
1573 return 0;
1574
1575 // If this is a call, and we have no hope of constant folding, bail early.
1576 if (CallInst *CI = dyn_cast<CallInst>(I)) {
1577 if (!CI->getCalledFunction() ||
1578 !canConstantFoldCallTo(CI->getCalledFunction()))
1579 return 0;
1580 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I))
1581 return 0;
1582
1583 // Otherwise, we can evaluate this instruction if all of its operands but one
1584 // are constant, and if the remaining one is derived from a constant evolving
1585 // PHI.
1586 unsigned Op = 0, e = I->getNumOperands();
1587 while (Op != e && (isa<Constant>(I->getOperand(Op)) ||
1588 isa<GlobalValue>(I->getOperand(Op))))
1589 ++Op; // Skip over all constant operands
1590
1591 if (Op == e) return 0; // No non-constants? Should be folded!
1592
1593 // Found the first non-constant operand.
1594 unsigned NonConstantOp = Op;
1595
1596 // Okay, all of the rest must be constants now.
1597 for (++Op; Op != e; ++Op)
1598 if (!(isa<Constant>(I->getOperand(Op)) ||
1599 isa<GlobalValue>(I->getOperand(Op))))
1600 return 0; // Too many non-constant operands!
1601
1602 // This is a expression evolving from a constant PHI if the non-constant
1603 // portion is!
1604 return getConstantEvolvingPHI(I->getOperand(NonConstantOp), L);
1605}
1606
1607/// EvaluateExpression - Given an expression that passes the
1608/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1609/// in the loop has the value PHIVal. If we can't fold this expression for some
1610/// reason, return null.
1611static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1612 if (isa<PHINode>(V)) return PHIVal;
1613 if (Constant *C = dyn_cast<Constant>(V)) return C;
1614 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1615 return ConstantPointerRef::get(GV);
1616 Instruction *I = cast<Instruction>(V);
1617
1618 std::vector<Constant*> Operands;
1619 Operands.resize(I->getNumOperands());
1620
1621 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1622 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1623 if (Operands[i] == 0) return 0;
1624 }
1625
1626 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1627 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1628
1629 switch (I->getOpcode()) {
1630 case Instruction::Cast:
1631 return ConstantExpr::getCast(Operands[0], I->getType());
1632 case Instruction::Select:
1633 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1634 case Instruction::Call:
1635 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Operands[0])) {
1636 Operands.erase(Operands.begin());
1637 return ConstantFoldCall(cast<Function>(CPR->getValue()), Operands);
1638 }
1639
1640 return 0;
1641 case Instruction::GetElementPtr:
1642 Constant *Base = Operands[0];
1643 Operands.erase(Operands.begin());
1644 return ConstantExpr::getGetElementPtr(Base, Operands);
1645 }
1646 return 0;
1647}
1648
1649
1650/// ComputeIterationCountExhaustively - If the trip is known to execute a
1651/// constant number of times (the condition evolves only from constants),
1652/// try to evaluate a few iterations of the loop until we get the exit
1653/// condition gets a value of ExitWhen (true or false). If we cannot
1654/// evaluate the trip count of the loop, return UnknownValue.
1655SCEVHandle ScalarEvolutionsImpl::
1656ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1657 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1658 if (PN == 0) return UnknownValue;
1659
1660 // Since the loop is canonicalized, the PHI node must have two entries. One
1661 // entry must be a constant (coming in from outside of the loop), and the
1662 // second must be derived from the same PHI.
1663 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1664 Constant *StartCST =
1665 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1666 if (StartCST == 0) return UnknownValue; // Must be a constant.
1667
1668 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1669 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1670 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1671
1672 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1673 // the loop symbolically to determine when the condition gets a value of
1674 // "ExitWhen".
1675 unsigned IterationNum = 0;
1676 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1677 for (Constant *PHIVal = StartCST;
1678 IterationNum != MaxIterations; ++IterationNum) {
1679 ConstantBool *CondVal =
1680 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1681 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
1682 if (CondVal->getValue() == ExitWhen) {
1683 ++NumBruteForceTripCountsComputed;
1684 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1685 }
1686
1687 // Otherwise, compute the value of the PHI node for the next iteration.
1688 Constant *Next = EvaluateExpression(BEValue, PHIVal);
1689 if (Next == 0 || Next == PHIVal)
1690 return UnknownValue; // Couldn't evaluate or not making progress...
1691 PHIVal = Next;
1692 }
1693
1694 // Too many iterations were needed to evaluate.
Chris Lattnerd934c702004-04-02 20:23:17 +00001695 return UnknownValue;
1696}
1697
1698/// getSCEVAtScope - Compute the value of the specified expression within the
1699/// indicated loop (which may be null to indicate in no loop). If the
1700/// expression cannot be evaluated, return UnknownValue.
1701SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1702 // FIXME: this should be turned into a virtual method on SCEV!
1703
1704 if (isa<SCEVConstant>(V) || isa<SCEVUnknown>(V)) return V;
1705 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1706 // Avoid performing the look-up in the common case where the specified
1707 // expression has no loop-variant portions.
1708 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1709 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1710 if (OpAtScope != Comm->getOperand(i)) {
1711 if (OpAtScope == UnknownValue) return UnknownValue;
1712 // Okay, at least one of these operands is loop variant but might be
1713 // foldable. Build a new instance of the folded commutative expression.
1714 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i-1);
1715 NewOps.push_back(OpAtScope);
1716
1717 for (++i; i != e; ++i) {
1718 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1719 if (OpAtScope == UnknownValue) return UnknownValue;
1720 NewOps.push_back(OpAtScope);
1721 }
1722 if (isa<SCEVAddExpr>(Comm))
1723 return SCEVAddExpr::get(NewOps);
1724 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1725 return SCEVMulExpr::get(NewOps);
1726 }
1727 }
1728 // If we got here, all operands are loop invariant.
1729 return Comm;
1730 }
1731
1732 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1733 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1734 if (LHS == UnknownValue) return LHS;
1735 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1736 if (RHS == UnknownValue) return RHS;
1737 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1738 return UDiv; // must be loop invariant
1739 return SCEVUDivExpr::get(LHS, RHS);
1740 }
1741
1742 // If this is a loop recurrence for a loop that does not contain L, then we
1743 // are dealing with the final value computed by the loop.
1744 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1745 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1746 // To evaluate this recurrence, we need to know how many times the AddRec
1747 // loop iterates. Compute this now.
1748 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1749 if (IterationCount == UnknownValue) return UnknownValue;
1750 IterationCount = getTruncateOrZeroExtend(IterationCount,
1751 AddRec->getType());
1752
1753 // If the value is affine, simplify the expression evaluation to just
1754 // Start + Step*IterationCount.
1755 if (AddRec->isAffine())
1756 return SCEVAddExpr::get(AddRec->getStart(),
1757 SCEVMulExpr::get(IterationCount,
1758 AddRec->getOperand(1)));
1759
1760 // Otherwise, evaluate it the hard way.
1761 return AddRec->evaluateAtIteration(IterationCount);
1762 }
1763 return UnknownValue;
1764 }
1765
1766 //assert(0 && "Unknown SCEV type!");
1767 return UnknownValue;
1768}
1769
1770
1771/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1772/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1773/// might be the same) or two SCEVCouldNotCompute objects.
1774///
1775static std::pair<SCEVHandle,SCEVHandle>
1776SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1777 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1778 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1779 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1780 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1781
1782 // We currently can only solve this if the coefficients are constants.
1783 if (!L || !M || !N) {
1784 SCEV *CNC = new SCEVCouldNotCompute();
1785 return std::make_pair(CNC, CNC);
1786 }
1787
1788 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
1789
1790 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
1791 Constant *C = L->getValue();
1792 // The B coefficient is M-N/2
1793 Constant *B = ConstantExpr::getSub(M->getValue(),
1794 ConstantExpr::getDiv(N->getValue(),
1795 Two));
1796 // The A coefficient is N/2
1797 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
1798
1799 // Compute the B^2-4ac term.
1800 Constant *SqrtTerm =
1801 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
1802 ConstantExpr::getMul(A, C));
1803 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
1804
1805 // Compute floor(sqrt(B^2-4ac))
1806 ConstantUInt *SqrtVal =
1807 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
1808 SqrtTerm->getType()->getUnsignedVersion()));
1809 uint64_t SqrtValV = SqrtVal->getValue();
Chris Lattnerd4f78f22004-04-05 19:05:15 +00001810 uint64_t SqrtValV2 = (uint64_t)sqrt(SqrtValV);
Chris Lattnerd934c702004-04-02 20:23:17 +00001811 // The square root might not be precise for arbitrary 64-bit integer
1812 // values. Do some sanity checks to ensure it's correct.
1813 if (SqrtValV2*SqrtValV2 > SqrtValV ||
1814 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
1815 SCEV *CNC = new SCEVCouldNotCompute();
1816 return std::make_pair(CNC, CNC);
1817 }
1818
1819 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
1820 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
1821
1822 Constant *NegB = ConstantExpr::getNeg(B);
1823 Constant *TwoA = ConstantExpr::getMul(A, Two);
1824
1825 // The divisions must be performed as signed divisions.
1826 const Type *SignedTy = NegB->getType()->getSignedVersion();
1827 NegB = ConstantExpr::getCast(NegB, SignedTy);
1828 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
1829 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
1830
1831 Constant *Solution1 =
1832 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
1833 Constant *Solution2 =
1834 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
1835 return std::make_pair(SCEVUnknown::get(Solution1),
1836 SCEVUnknown::get(Solution2));
1837}
1838
1839/// HowFarToZero - Return the number of times a backedge comparing the specified
1840/// value to zero will execute. If not computable, return UnknownValue
1841SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
1842 // If the value is a constant
1843 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1844 // If the value is already zero, the branch will execute zero times.
1845 if (C->getValue()->isNullValue()) return C;
1846 return UnknownValue; // Otherwise it will loop infinitely.
1847 }
1848
1849 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
1850 if (!AddRec || AddRec->getLoop() != L)
1851 return UnknownValue;
1852
1853 if (AddRec->isAffine()) {
1854 // If this is an affine expression the execution count of this branch is
1855 // equal to:
1856 //
1857 // (0 - Start/Step) iff Start % Step == 0
1858 //
1859 // Get the initial value for the loop.
1860 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
1861 SCEVHandle Step = AddRec->getOperand(1);
1862
1863 Step = getSCEVAtScope(Step, L->getParentLoop());
1864
1865 // Figure out if Start % Step == 0.
1866 // FIXME: We should add DivExpr and RemExpr operations to our AST.
1867 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
1868 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
1869 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
1870 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
1871 return Start; // 0 - Start/-1 == Start
1872
1873 // Check to see if Start is divisible by SC with no remainder.
1874 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
1875 ConstantInt *StartCC = StartC->getValue();
1876 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
1877 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
1878 if (Rem->isNullValue()) {
1879 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
1880 return SCEVUnknown::get(Result);
1881 }
1882 }
1883 }
1884 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
1885 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
1886 // the quadratic equation to solve it.
1887 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
1888 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
1889 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
1890 if (R1) {
Chris Lattner09169212004-04-02 20:26:46 +00001891#if 0
Chris Lattnerd934c702004-04-02 20:23:17 +00001892 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
1893 << " sol#2: " << *R2 << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00001894#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00001895 // Pick the smallest positive root value.
1896 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
1897 if (ConstantBool *CB =
1898 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
1899 R2->getValue()))) {
1900 if (CB != ConstantBool::True)
1901 std::swap(R1, R2); // R1 is the minimum root now.
1902
1903 // We can only use this value if the chrec ends up with an exact zero
1904 // value at this index. When solving for "X*X != 5", for example, we
1905 // should not accept a root of 2.
1906 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
1907 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
1908 if (EvalVal->getValue()->isNullValue())
1909 return R1; // We found a quadratic root!
1910 }
1911 }
1912 }
1913
1914 return UnknownValue;
1915}
1916
1917/// HowFarToNonZero - Return the number of times a backedge checking the
1918/// specified value for nonzero will execute. If not computable, return
1919/// UnknownValue
1920SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
1921 // Loops that look like: while (X == 0) are very strange indeed. We don't
1922 // handle them yet except for the trivial case. This could be expanded in the
1923 // future as needed.
1924
1925 // If the value is a constant, check to see if it is known to be non-zero
1926 // already. If so, the backedge will execute zero times.
1927 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1928 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
1929 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
1930 if (NonZero == ConstantBool::True)
1931 return getSCEV(Zero);
1932 return UnknownValue; // Otherwise it will loop infinitely.
1933 }
1934
1935 // We could implement others, but I really doubt anyone writes loops like
1936 // this, and if they did, they would already be constant folded.
1937 return UnknownValue;
1938}
1939
1940static ConstantInt *
1941EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1942 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1943 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1944 assert(isa<SCEVConstant>(Val) &&
1945 "Evaluation of SCEV at constant didn't fold correctly?");
1946 return cast<SCEVConstant>(Val)->getValue();
1947}
1948
1949
1950/// getNumIterationsInRange - Return the number of iterations of this loop that
1951/// produce values in the specified constant range. Another way of looking at
1952/// this is that it returns the first iteration number where the value is not in
1953/// the condition, thus computing the exit count. If the iteration count can't
1954/// be computed, an instance of SCEVCouldNotCompute is returned.
1955SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
1956 if (Range.isFullSet()) // Infinite loop.
1957 return new SCEVCouldNotCompute();
1958
1959 // If the start is a non-zero constant, shift the range to simplify things.
1960 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
1961 if (!SC->getValue()->isNullValue()) {
1962 std::vector<SCEVHandle> Operands(op_begin(), op_end());
1963 Operands[0] = getIntegerSCEV(0, SC->getType());
1964 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
1965 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
1966 return ShiftedAddRec->getNumIterationsInRange(
1967 Range.subtract(SC->getValue()));
1968 // This is strange and shouldn't happen.
1969 return new SCEVCouldNotCompute();
1970 }
1971
1972 // The only time we can solve this is when we have all constant indices.
1973 // Otherwise, we cannot determine the overflow conditions.
1974 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1975 if (!isa<SCEVConstant>(getOperand(i)))
1976 return new SCEVCouldNotCompute();
1977
1978
1979 // Okay at this point we know that all elements of the chrec are constants and
1980 // that the start element is zero.
1981
1982 // First check to see if the range contains zero. If not, the first
1983 // iteration exits.
1984 ConstantInt *Zero = ConstantInt::get(getType(), 0);
1985 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
1986
1987 if (isAffine()) {
1988 // If this is an affine expression then we have this situation:
1989 // Solve {0,+,A} in Range === Ax in Range
1990
1991 // Since we know that zero is in the range, we know that the upper value of
1992 // the range must be the first possible exit value. Also note that we
1993 // already checked for a full range.
1994 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
1995 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
1996 ConstantInt *One = ConstantInt::get(getType(), 1);
1997
1998 // The exit value should be (Upper+A-1)/A.
1999 Constant *ExitValue = Upper;
2000 if (A != One) {
2001 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2002 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2003 }
2004 assert(isa<ConstantInt>(ExitValue) &&
2005 "Constant folding of integers not implemented?");
2006
2007 // Evaluate at the exit value. If we really did fall out of the valid
2008 // range, then we computed our trip count, otherwise wrap around or other
2009 // things must have happened.
2010 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2011 if (Range.contains(Val))
2012 return new SCEVCouldNotCompute(); // Something strange happened
2013
2014 // Ensure that the previous value is in the range. This is a sanity check.
2015 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2016 ConstantExpr::getSub(ExitValue, One))) &&
2017 "Linear scev computation is off in a bad way!");
2018 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2019 } else if (isQuadratic()) {
2020 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2021 // quadratic equation to solve it. To do this, we must frame our problem in
2022 // terms of figuring out when zero is crossed, instead of when
2023 // Range.getUpper() is crossed.
2024 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2025 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2026 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2027
2028 // Next, solve the constructed addrec
2029 std::pair<SCEVHandle,SCEVHandle> Roots =
2030 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2031 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2032 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2033 if (R1) {
2034 // Pick the smallest positive root value.
2035 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2036 if (ConstantBool *CB =
2037 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2038 R2->getValue()))) {
2039 if (CB != ConstantBool::True)
2040 std::swap(R1, R2); // R1 is the minimum root now.
2041
2042 // Make sure the root is not off by one. The returned iteration should
2043 // not be in the range, but the previous one should be. When solving
2044 // for "X*X < 5", for example, we should not return a root of 2.
2045 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2046 R1->getValue());
2047 if (Range.contains(R1Val)) {
2048 // The next iteration must be out of the range...
2049 Constant *NextVal =
2050 ConstantExpr::getAdd(R1->getValue(),
2051 ConstantInt::get(R1->getType(), 1));
2052
2053 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2054 if (!Range.contains(R1Val))
2055 return SCEVUnknown::get(NextVal);
2056 return new SCEVCouldNotCompute(); // Something strange happened
2057 }
2058
2059 // If R1 was not in the range, then it is a good return value. Make
2060 // sure that R1-1 WAS in the range though, just in case.
2061 Constant *NextVal =
2062 ConstantExpr::getSub(R1->getValue(),
2063 ConstantInt::get(R1->getType(), 1));
2064 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2065 if (Range.contains(R1Val))
2066 return R1;
2067 return new SCEVCouldNotCompute(); // Something strange happened
2068 }
2069 }
2070 }
2071
2072 // Fallback, if this is a general polynomial, figure out the progression
2073 // through brute force: evaluate until we find an iteration that fails the
2074 // test. This is likely to be slow, but getting an accurate trip count is
2075 // incredibly important, we will be able to simplify the exit test a lot, and
2076 // we are almost guaranteed to get a trip count in this case.
2077 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2078 ConstantInt *One = ConstantInt::get(getType(), 1);
2079 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2080 do {
2081 ++NumBruteForceEvaluations;
2082 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2083 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2084 return new SCEVCouldNotCompute();
2085
2086 // Check to see if we found the value!
2087 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2088 return SCEVConstant::get(TestVal);
2089
2090 // Increment to test the next index.
2091 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2092 } while (TestVal != EndVal);
2093
2094 return new SCEVCouldNotCompute();
2095}
2096
2097
2098
2099//===----------------------------------------------------------------------===//
2100// ScalarEvolution Class Implementation
2101//===----------------------------------------------------------------------===//
2102
2103bool ScalarEvolution::runOnFunction(Function &F) {
2104 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2105 return false;
2106}
2107
2108void ScalarEvolution::releaseMemory() {
2109 delete (ScalarEvolutionsImpl*)Impl;
2110 Impl = 0;
2111}
2112
2113void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2114 AU.setPreservesAll();
2115 AU.addRequiredID(LoopSimplifyID);
2116 AU.addRequiredTransitive<LoopInfo>();
2117}
2118
2119SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2120 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2121}
2122
2123SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2124 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2125}
2126
2127bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2128 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2129}
2130
2131SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2132 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2133}
2134
2135void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2136 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2137}
2138
2139
2140/// shouldSubstituteIndVar - Return true if we should perform induction variable
2141/// substitution for this variable. This is a hack because we don't have a
2142/// strength reduction pass yet. When we do we will promote all vars, because
2143/// we can strength reduce them later as desired.
2144bool ScalarEvolution::shouldSubstituteIndVar(const SCEV *S) const {
2145 // Don't substitute high degree polynomials.
2146 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
2147 if (AddRec->getNumOperands() > 3) return false;
2148 return true;
2149}
2150
2151
2152static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2153 const Loop *L) {
2154 // Print all inner loops first
2155 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2156 PrintLoopInfo(OS, SE, *I);
2157
2158 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2159 if (L->getExitBlocks().size() != 1)
2160 std::cerr << "<multiple exits> ";
2161
2162 if (SE->hasLoopInvariantIterationCount(L)) {
2163 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2164 } else {
2165 std::cerr << "Unpredictable iteration count. ";
2166 }
2167
2168 std::cerr << "\n";
2169}
2170
2171void ScalarEvolution::print(std::ostream &OS) const {
2172 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2173 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2174
2175 OS << "Classifying expressions for: " << F.getName() << "\n";
2176 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2177 if ((*I)->getType()->isInteger()) {
2178 OS << **I;
2179 OS << " --> ";
2180 SCEVHandle SV = getSCEV(*I);
2181 SV->print(OS);
2182 OS << "\t\t";
2183
2184 if ((*I)->getType()->isIntegral()) {
2185 ConstantRange Bounds = SV->getValueRange();
2186 if (!Bounds.isFullSet())
2187 OS << "Bounds: " << Bounds << " ";
2188 }
2189
2190 if (const Loop *L = LI.getLoopFor((*I)->getParent())) {
2191 OS << "Exits: ";
2192 SCEVHandle ExitValue = getSCEVAtScope(*I, L->getParentLoop());
2193 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2194 OS << "<<Unknown>>";
2195 } else {
2196 OS << *ExitValue;
2197 }
2198 }
2199
2200
2201 OS << "\n";
2202 }
2203
2204 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2205 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2206 PrintLoopInfo(OS, this, *I);
2207}
2208
2209//===----------------------------------------------------------------------===//
2210// ScalarEvolutionRewriter Class Implementation
2211//===----------------------------------------------------------------------===//
2212
2213Value *ScalarEvolutionRewriter::
2214GetOrInsertCanonicalInductionVariable(const Loop *L, const Type *Ty) {
2215 assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
2216 "Can only insert integer or floating point induction variables!");
2217
2218 // Check to see if we already inserted one.
2219 SCEVHandle H = SCEVAddRecExpr::get(getIntegerSCEV(0, Ty),
2220 getIntegerSCEV(1, Ty), L);
2221 return ExpandCodeFor(H, 0, Ty);
2222}
2223
2224/// ExpandCodeFor - Insert code to directly compute the specified SCEV
2225/// expression into the program. The inserted code is inserted into the
2226/// specified block.
2227Value *ScalarEvolutionRewriter::ExpandCodeFor(SCEVHandle SH,
2228 Instruction *InsertPt,
2229 const Type *Ty) {
2230 std::map<SCEVHandle, Value*>::iterator ExistVal =InsertedExpressions.find(SH);
2231 Value *V;
2232 if (ExistVal != InsertedExpressions.end()) {
2233 V = ExistVal->second;
2234 } else {
2235 // Ask the recurrence object to expand the code for itself.
2236 V = SH->expandCodeFor(*this, InsertPt);
2237 // Cache the generated result.
2238 InsertedExpressions.insert(std::make_pair(SH, V));
2239 }
2240
2241 if (Ty == 0 || V->getType() == Ty)
2242 return V;
2243 if (Constant *C = dyn_cast<Constant>(V))
2244 return ConstantExpr::getCast(C, Ty);
2245 else if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerd420fe62004-04-14 22:01:22 +00002246 // Check to see if there is already a cast. If there is, use it.
2247 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2248 UI != E; ++UI) {
2249 if ((*UI)->getType() == Ty)
2250 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
2251 BasicBlock::iterator It = I; ++It;
Chris Lattnera4e4a632004-04-15 14:17:43 +00002252 while (isa<PHINode>(It)) ++It;
Chris Lattnerd420fe62004-04-14 22:01:22 +00002253 if (It != BasicBlock::iterator(CI)) {
2254 // Splice the cast immediately after the operand in question.
2255 I->getParent()->getInstList().splice(It,
2256 CI->getParent()->getInstList(),
2257 CI);
2258 }
2259 return CI;
2260 }
2261 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002262 BasicBlock::iterator IP = I; ++IP;
Chris Lattner29153fc2004-04-05 18:46:55 +00002263 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
2264 IP = II->getNormalDest()->begin();
Chris Lattnerd934c702004-04-02 20:23:17 +00002265 while (isa<PHINode>(IP)) ++IP;
2266 return new CastInst(V, Ty, V->getName(), IP);
2267 } else {
2268 // FIXME: check to see if there is already a cast!
2269 return new CastInst(V, Ty, V->getName(), InsertPt);
2270 }
2271}