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