blob: 2a6cc50c0ba778ad9024f435718969d1572390fa [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079#include "llvm/Support/InstIterator.h"
80#include "llvm/Support/ManagedStatic.h"
81#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085#include <ostream>
86#include <algorithm>
87#include <cmath>
88using namespace llvm;
89
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman089efff2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
103 cl::init(100));
104
Dan Gohman089efff2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107char ScalarEvolution::ID = 0;
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
116SCEV::~SCEV() {}
117void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125}
126
Dan Gohman7b560c42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
135
136bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
137 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
138 return false;
139}
140
141const Type *SCEVCouldNotCompute::getType() const {
142 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
143 return 0;
144}
145
146bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
147 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
148 return false;
149}
150
151SCEVHandle SCEVCouldNotCompute::
152replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000153 const SCEVHandle &Conc,
154 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 return this;
156}
157
Dan Gohman13058cc2009-04-21 00:47:46 +0000158void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 OS << "***COULDNOTCOMPUTE***";
160}
161
162bool SCEVCouldNotCompute::classof(const SCEV *S) {
163 return S->getSCEVType() == scCouldNotCompute;
164}
165
166
167// SCEVConstants - Only allow the creation of one SCEVConstant for any
168// particular value. Don't use a SCEVHandle here, or else the object will
169// never be deleted!
170static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
171
172
173SCEVConstant::~SCEVConstant() {
174 SCEVConstants->erase(V);
175}
176
Dan Gohman89f85052007-10-22 18:31:58 +0000177SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 SCEVConstant *&R = (*SCEVConstants)[V];
179 if (R == 0) R = new SCEVConstant(V);
180 return R;
181}
182
Dan Gohman89f85052007-10-22 18:31:58 +0000183SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
184 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185}
186
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187const Type *SCEVConstant::getType() const { return V->getType(); }
188
Dan Gohman13058cc2009-04-21 00:47:46 +0000189void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 WriteAsOperand(OS, V, false);
191}
192
193// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
194// particular input. Don't use a SCEVHandle here, or else the object will
195// never be deleted!
196static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
197 SCEVTruncateExpr*> > SCEVTruncates;
198
199SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
200 : SCEV(scTruncate), Op(op), Ty(ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000201 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
202 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204}
205
206SCEVTruncateExpr::~SCEVTruncateExpr() {
207 SCEVTruncates->erase(std::make_pair(Op, Ty));
208}
209
Evan Cheng98c073b2009-02-17 00:13:06 +0000210bool SCEVTruncateExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->dominates(BB, DT);
212}
213
Dan Gohman13058cc2009-04-21 00:47:46 +0000214void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 OS << "(truncate " << *Op << " to " << *Ty << ")";
216}
217
218// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
219// particular input. Don't use a SCEVHandle here, or else the object will never
220// be deleted!
221static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
222 SCEVZeroExtendExpr*> > SCEVZeroExtends;
223
224SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
225 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000226 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
227 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229}
230
231SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
232 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
233}
234
Evan Cheng98c073b2009-02-17 00:13:06 +0000235bool SCEVZeroExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
236 return Op->dominates(BB, DT);
237}
238
Dan Gohman13058cc2009-04-21 00:47:46 +0000239void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
241}
242
243// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
244// particular input. Don't use a SCEVHandle here, or else the object will never
245// be deleted!
246static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
247 SCEVSignExtendExpr*> > SCEVSignExtends;
248
249SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
250 : SCEV(scSignExtend), Op(op), Ty(ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000251 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
252 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254}
255
256SCEVSignExtendExpr::~SCEVSignExtendExpr() {
257 SCEVSignExtends->erase(std::make_pair(Op, Ty));
258}
259
Evan Cheng98c073b2009-02-17 00:13:06 +0000260bool SCEVSignExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
261 return Op->dominates(BB, DT);
262}
263
Dan Gohman13058cc2009-04-21 00:47:46 +0000264void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 OS << "(signextend " << *Op << " to " << *Ty << ")";
266}
267
268// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
269// particular input. Don't use a SCEVHandle here, or else the object will never
270// be deleted!
271static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
272 SCEVCommutativeExpr*> > SCEVCommExprs;
273
274SCEVCommutativeExpr::~SCEVCommutativeExpr() {
275 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
276 std::vector<SCEV*>(Operands.begin(),
277 Operands.end())));
278}
279
Dan Gohman13058cc2009-04-21 00:47:46 +0000280void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
282 const char *OpStr = getOperationStr();
283 OS << "(" << *Operands[0];
284 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
285 OS << OpStr << *Operands[i];
286 OS << ")";
287}
288
289SCEVHandle SCEVCommutativeExpr::
290replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000291 const SCEVHandle &Conc,
292 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000294 SCEVHandle H =
295 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 if (H != getOperand(i)) {
297 std::vector<SCEVHandle> NewOps;
298 NewOps.reserve(getNumOperands());
299 for (unsigned j = 0; j != i; ++j)
300 NewOps.push_back(getOperand(j));
301 NewOps.push_back(H);
302 for (++i; i != e; ++i)
303 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000304 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305
306 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000307 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000309 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000310 else if (isa<SCEVSMaxExpr>(this))
311 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000312 else if (isa<SCEVUMaxExpr>(this))
313 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 else
315 assert(0 && "Unknown commutative expr!");
316 }
317 }
318 return this;
319}
320
Evan Cheng98c073b2009-02-17 00:13:06 +0000321bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
322 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
323 if (!getOperand(i)->dominates(BB, DT))
324 return false;
325 }
326 return true;
327}
328
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000330// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331// input. Don't use a SCEVHandle here, or else the object will never be
332// deleted!
333static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000334 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000336SCEVUDivExpr::~SCEVUDivExpr() {
337 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338}
339
Evan Cheng98c073b2009-02-17 00:13:06 +0000340bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
341 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
342}
343
Dan Gohman13058cc2009-04-21 00:47:46 +0000344void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000345 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346}
347
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000348const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 return LHS->getType();
350}
351
352// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
353// particular input. Don't use a SCEVHandle here, or else the object will never
354// be deleted!
355static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
356 SCEVAddRecExpr*> > SCEVAddRecExprs;
357
358SCEVAddRecExpr::~SCEVAddRecExpr() {
359 SCEVAddRecExprs->erase(std::make_pair(L,
360 std::vector<SCEV*>(Operands.begin(),
361 Operands.end())));
362}
363
Evan Cheng98c073b2009-02-17 00:13:06 +0000364bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
365 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
366 if (!getOperand(i)->dominates(BB, DT))
367 return false;
368 }
369 return true;
370}
371
372
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373SCEVHandle SCEVAddRecExpr::
374replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000375 const SCEVHandle &Conc,
376 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000378 SCEVHandle H =
379 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 if (H != getOperand(i)) {
381 std::vector<SCEVHandle> NewOps;
382 NewOps.reserve(getNumOperands());
383 for (unsigned j = 0; j != i; ++j)
384 NewOps.push_back(getOperand(j));
385 NewOps.push_back(H);
386 for (++i; i != e; ++i)
387 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000388 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389
Dan Gohman89f85052007-10-22 18:31:58 +0000390 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391 }
392 }
393 return this;
394}
395
396
397bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
398 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
399 // contain L and if the start is invariant.
400 return !QueryLoop->contains(L->getHeader()) &&
401 getOperand(0)->isLoopInvariant(QueryLoop);
402}
403
404
Dan Gohman13058cc2009-04-21 00:47:46 +0000405void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406 OS << "{" << *Operands[0];
407 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
408 OS << ",+," << *Operands[i];
409 OS << "}<" << L->getHeader()->getName() + ">";
410}
411
412// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
413// value. Don't use a SCEVHandle here, or else the object will never be
414// deleted!
415static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
416
417SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
418
419bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
420 // All non-instruction values are loop invariant. All instructions are loop
421 // invariant if they are not contained in the specified loop.
422 if (Instruction *I = dyn_cast<Instruction>(V))
423 return !L->contains(I->getParent());
424 return true;
425}
426
Evan Cheng98c073b2009-02-17 00:13:06 +0000427bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
428 if (Instruction *I = dyn_cast<Instruction>(getValue()))
429 return DT->dominates(I->getParent(), BB);
430 return true;
431}
432
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433const Type *SCEVUnknown::getType() const {
434 return V->getType();
435}
436
Dan Gohman13058cc2009-04-21 00:47:46 +0000437void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000438 if (isa<PointerType>(V->getType()))
439 OS << "(ptrtoint " << *V->getType() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 WriteAsOperand(OS, V, false);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000441 if (isa<PointerType>(V->getType()))
442 OS << " to iPTR)";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443}
444
445//===----------------------------------------------------------------------===//
446// SCEV Utilities
447//===----------------------------------------------------------------------===//
448
449namespace {
450 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
451 /// than the complexity of the RHS. This comparator is used to canonicalize
452 /// expressions.
453 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000454 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455 return LHS->getSCEVType() < RHS->getSCEVType();
456 }
457 };
458}
459
460/// GroupByComplexity - Given a list of SCEV objects, order them by their
461/// complexity, and group objects of the same complexity together by value.
462/// When this routine is finished, we know that any duplicates in the vector are
463/// consecutive and that complexity is monotonically increasing.
464///
465/// Note that we go take special precautions to ensure that we get determinstic
466/// results from this routine. In other words, we don't want the results of
467/// this to depend on where the addresses of various SCEV objects happened to
468/// land in memory.
469///
470static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
471 if (Ops.size() < 2) return; // Noop
472 if (Ops.size() == 2) {
473 // This is the common case, which also happens to be trivially simple.
474 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000475 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 std::swap(Ops[0], Ops[1]);
477 return;
478 }
479
480 // Do the rough sort by complexity.
481 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
482
483 // Now that we are sorted by complexity, group elements of the same
484 // complexity. Note that this is, at worst, N^2, but the vector is likely to
485 // be extremely short in practice. Note that we take this approach because we
486 // do not want to depend on the addresses of the objects we are grouping.
487 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
488 SCEV *S = Ops[i];
489 unsigned Complexity = S->getSCEVType();
490
491 // If there are any objects of the same complexity and same value as this
492 // one, group them.
493 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
494 if (Ops[j] == S) { // Found a duplicate.
495 // Move it to immediately after i'th element.
496 std::swap(Ops[i+1], Ops[j]);
497 ++i; // no need to rescan it.
498 if (i == e-2) return; // Done!
499 }
500 }
501 }
502}
503
504
505
506//===----------------------------------------------------------------------===//
507// Simple SCEV method implementations
508//===----------------------------------------------------------------------===//
509
Eli Friedman7489ec92008-08-04 23:49:06 +0000510/// BinomialCoefficient - Compute BC(It, K). The result has width W.
511// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000512static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000513 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000514 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000515 // Handle the simplest case efficiently.
516 if (K == 1)
517 return SE.getTruncateOrZeroExtend(It, ResultTy);
518
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000519 // We are using the following formula for BC(It, K):
520 //
521 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
522 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000523 // Suppose, W is the bitwidth of the return value. We must be prepared for
524 // overflow. Hence, we must assure that the result of our computation is
525 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
526 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000527 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000528 // However, this code doesn't use exactly that formula; the formula it uses
529 // is something like the following, where T is the number of factors of 2 in
530 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
531 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000532 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000533 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000534 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000535 // This formula is trivially equivalent to the previous formula. However,
536 // this formula can be implemented much more efficiently. The trick is that
537 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
538 // arithmetic. To do exact division in modular arithmetic, all we have
539 // to do is multiply by the inverse. Therefore, this step can be done at
540 // width W.
541 //
542 // The next issue is how to safely do the division by 2^T. The way this
543 // is done is by doing the multiplication step at a width of at least W + T
544 // bits. This way, the bottom W+T bits of the product are accurate. Then,
545 // when we perform the division by 2^T (which is equivalent to a right shift
546 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
547 // truncated out after the division by 2^T.
548 //
549 // In comparison to just directly using the first formula, this technique
550 // is much more efficient; using the first formula requires W * K bits,
551 // but this formula less than W + K bits. Also, the first formula requires
552 // a division step, whereas this formula only requires multiplies and shifts.
553 //
554 // It doesn't matter whether the subtraction step is done in the calculation
555 // width or the input iteration count's width; if the subtraction overflows,
556 // the result must be zero anyway. We prefer here to do it in the width of
557 // the induction variable because it helps a lot for certain cases; CodeGen
558 // isn't smart enough to ignore the overflow, which leads to much less
559 // efficient code if the width of the subtraction is wider than the native
560 // register width.
561 //
562 // (It's possible to not widen at all by pulling out factors of 2 before
563 // the multiplication; for example, K=2 can be calculated as
564 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
565 // extra arithmetic, so it's not an obvious win, and it gets
566 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000567
Eli Friedman7489ec92008-08-04 23:49:06 +0000568 // Protection from insane SCEVs; this bound is conservative,
569 // but it probably doesn't matter.
570 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000571 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000572
Dan Gohman01c2ee72009-04-16 03:18:22 +0000573 unsigned W = SE.getTargetData().getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000574
Eli Friedman7489ec92008-08-04 23:49:06 +0000575 // Calculate K! / 2^T and T; we divide out the factors of two before
576 // multiplying for calculating K! / 2^T to avoid overflow.
577 // Other overflow doesn't matter because we only care about the bottom
578 // W bits of the result.
579 APInt OddFactorial(W, 1);
580 unsigned T = 1;
581 for (unsigned i = 3; i <= K; ++i) {
582 APInt Mult(W, i);
583 unsigned TwoFactors = Mult.countTrailingZeros();
584 T += TwoFactors;
585 Mult = Mult.lshr(TwoFactors);
586 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000588
Eli Friedman7489ec92008-08-04 23:49:06 +0000589 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000590 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000591
592 // Calcuate 2^T, at width T+W.
593 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
594
595 // Calculate the multiplicative inverse of K! / 2^T;
596 // this multiplication factor will perform the exact division by
597 // K! / 2^T.
598 APInt Mod = APInt::getSignedMinValue(W+1);
599 APInt MultiplyFactor = OddFactorial.zext(W+1);
600 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
601 MultiplyFactor = MultiplyFactor.trunc(W);
602
603 // Calculate the product, at width T+W
604 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
605 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
606 for (unsigned i = 1; i != K; ++i) {
607 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
608 Dividend = SE.getMulExpr(Dividend,
609 SE.getTruncateOrZeroExtend(S, CalculationTy));
610 }
611
612 // Divide by 2^T
613 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
614
615 // Truncate the result, and divide by K! / 2^T.
616
617 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
618 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619}
620
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621/// evaluateAtIteration - Return the value of this chain of recurrences at
622/// the specified iteration number. We can evaluate this recurrence by
623/// multiplying each element in the chain by the binomial coefficient
624/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
625///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000626/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000628/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629///
Dan Gohman89f85052007-10-22 18:31:58 +0000630SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
631 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000634 // The computation is correct in the face of overflow provided that the
635 // multiplication is performed _after_ the evaluation of the binomial
636 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000637 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000638 if (isa<SCEVCouldNotCompute>(Coeff))
639 return Coeff;
640
641 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 }
643 return Result;
644}
645
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646//===----------------------------------------------------------------------===//
647// SCEV Expression folder implementations
648//===----------------------------------------------------------------------===//
649
Dan Gohman89f85052007-10-22 18:31:58 +0000650SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000651 assert(getTargetData().getTypeSizeInBits(Op->getType()) >
652 getTargetData().getTypeSizeInBits(Ty) &&
653 "This is not a truncating conversion!");
654
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000656 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000657 ConstantExpr::getTrunc(SC->getValue(), Ty));
658
659 // If the input value is a chrec scev made out of constants, truncate
660 // all of the constants.
661 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
662 std::vector<SCEVHandle> Operands;
663 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
664 // FIXME: This should allow truncation of other expression types!
665 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000666 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667 else
668 break;
669 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000670 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 }
672
673 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
674 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
675 return Result;
676}
677
Dan Gohman36d40922009-04-16 19:25:55 +0000678SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
679 const Type *Ty) {
680 assert(getTargetData().getTypeSizeInBits(Op->getType()) <
681 getTargetData().getTypeSizeInBits(Ty) &&
682 "This is not an extending conversion!");
683
Dan Gohman01c2ee72009-04-16 03:18:22 +0000684 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
685 const Type *IntTy = Ty;
686 if (isa<PointerType>(IntTy)) IntTy = getTargetData().getIntPtrType();
687 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
688 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
689 return getUnknown(C);
690 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691
692 // FIXME: If the input value is a chrec scev, and we can prove that the value
693 // did not overflow the old, smaller, value, we can zero extend all of the
694 // operands (often constants). This would allow analysis of something like
695 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
696
697 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
698 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
699 return Result;
700}
701
Dan Gohman89f85052007-10-22 18:31:58 +0000702SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000703 assert(getTargetData().getTypeSizeInBits(Op->getType()) <
704 getTargetData().getTypeSizeInBits(Ty) &&
705 "This is not an extending conversion!");
706
Dan Gohman01c2ee72009-04-16 03:18:22 +0000707 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
708 const Type *IntTy = Ty;
709 if (isa<PointerType>(IntTy)) IntTy = getTargetData().getIntPtrType();
710 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
711 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
712 return getUnknown(C);
713 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714
715 // FIXME: If the input value is a chrec scev, and we can prove that the value
716 // did not overflow the old, smaller, value, we can sign extend all of the
717 // operands (often constants). This would allow analysis of something like
718 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
719
720 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
721 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
722 return Result;
723}
724
725// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000726SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 assert(!Ops.empty() && "Cannot get empty add!");
728 if (Ops.size() == 1) return Ops[0];
729
730 // Sort by complexity, this groups all similar expression types together.
731 GroupByComplexity(Ops);
732
733 // If there are any constants, fold them together.
734 unsigned Idx = 0;
735 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
736 ++Idx;
737 assert(Idx < Ops.size());
738 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
739 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000740 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
741 RHSC->getValue()->getValue());
742 Ops[0] = getConstant(Fold);
743 Ops.erase(Ops.begin()+1); // Erase the folded element
744 if (Ops.size() == 1) return Ops[0];
745 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 }
747
748 // If we are left with a constant zero being added, strip it off.
749 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
750 Ops.erase(Ops.begin());
751 --Idx;
752 }
753 }
754
755 if (Ops.size() == 1) return Ops[0];
756
757 // Okay, check to see if the same value occurs in the operand list twice. If
758 // so, merge them together into an multiply expression. Since we sorted the
759 // list, these values are required to be adjacent.
760 const Type *Ty = Ops[0]->getType();
761 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
762 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
763 // Found a match, merge the two values into a multiply, and add any
764 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000765 SCEVHandle Two = getIntegerSCEV(2, Ty);
766 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 if (Ops.size() == 2)
768 return Mul;
769 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
770 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000771 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 }
773
774 // Now we know the first non-constant operand. Skip past any cast SCEVs.
775 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
776 ++Idx;
777
778 // If there are add operands they would be next.
779 if (Idx < Ops.size()) {
780 bool DeletedAdd = false;
781 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
782 // If we have an add, expand the add operands onto the end of the operands
783 // list.
784 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
785 Ops.erase(Ops.begin()+Idx);
786 DeletedAdd = true;
787 }
788
789 // If we deleted at least one add, we added operands to the end of the list,
790 // and they are not necessarily sorted. Recurse to resort and resimplify
791 // any operands we just aquired.
792 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000793 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 }
795
796 // Skip over the add expression until we get to a multiply.
797 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
798 ++Idx;
799
800 // If we are adding something to a multiply expression, make sure the
801 // something is not already an operand of the multiply. If so, merge it into
802 // the multiply.
803 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
804 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
805 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
806 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
807 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
808 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
809 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
810 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
811 if (Mul->getNumOperands() != 2) {
812 // If the multiply has more than two operands, we must get the
813 // Y*Z term.
814 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
815 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000816 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 }
Dan Gohman89f85052007-10-22 18:31:58 +0000818 SCEVHandle One = getIntegerSCEV(1, Ty);
819 SCEVHandle AddOne = getAddExpr(InnerMul, One);
820 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 if (Ops.size() == 2) return OuterMul;
822 if (AddOp < Idx) {
823 Ops.erase(Ops.begin()+AddOp);
824 Ops.erase(Ops.begin()+Idx-1);
825 } else {
826 Ops.erase(Ops.begin()+Idx);
827 Ops.erase(Ops.begin()+AddOp-1);
828 }
829 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000830 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 }
832
833 // Check this multiply against other multiplies being added together.
834 for (unsigned OtherMulIdx = Idx+1;
835 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
836 ++OtherMulIdx) {
837 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
838 // If MulOp occurs in OtherMul, we can fold the two multiplies
839 // together.
840 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
841 OMulOp != e; ++OMulOp)
842 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
843 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
844 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
845 if (Mul->getNumOperands() != 2) {
846 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
847 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000848 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
850 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
851 if (OtherMul->getNumOperands() != 2) {
852 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
853 OtherMul->op_end());
854 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000855 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 }
Dan Gohman89f85052007-10-22 18:31:58 +0000857 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
858 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859 if (Ops.size() == 2) return OuterMul;
860 Ops.erase(Ops.begin()+Idx);
861 Ops.erase(Ops.begin()+OtherMulIdx-1);
862 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000863 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 }
865 }
866 }
867 }
868
869 // If there are any add recurrences in the operands list, see if any other
870 // added values are loop invariant. If so, we can fold them into the
871 // recurrence.
872 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
873 ++Idx;
874
875 // Scan over all recurrences, trying to fold loop invariants into them.
876 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
877 // Scan all of the other operands to this add and add them to the vector if
878 // they are loop invariant w.r.t. the recurrence.
879 std::vector<SCEVHandle> LIOps;
880 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
881 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
882 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
883 LIOps.push_back(Ops[i]);
884 Ops.erase(Ops.begin()+i);
885 --i; --e;
886 }
887
888 // If we found some loop invariants, fold them into the recurrence.
889 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000890 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 LIOps.push_back(AddRec->getStart());
892
893 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000894 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000895
Dan Gohman89f85052007-10-22 18:31:58 +0000896 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 // If all of the other operands were loop invariant, we are done.
898 if (Ops.size() == 1) return NewRec;
899
900 // Otherwise, add the folded AddRec by the non-liv parts.
901 for (unsigned i = 0;; ++i)
902 if (Ops[i] == AddRec) {
903 Ops[i] = NewRec;
904 break;
905 }
Dan Gohman89f85052007-10-22 18:31:58 +0000906 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 }
908
909 // Okay, if there weren't any loop invariants to be folded, check to see if
910 // there are multiple AddRec's with the same loop induction variable being
911 // added together. If so, we can fold them.
912 for (unsigned OtherIdx = Idx+1;
913 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
914 if (OtherIdx != Idx) {
915 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
916 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
917 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
918 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
919 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
920 if (i >= NewOps.size()) {
921 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
922 OtherAddRec->op_end());
923 break;
924 }
Dan Gohman89f85052007-10-22 18:31:58 +0000925 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 }
Dan Gohman89f85052007-10-22 18:31:58 +0000927 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928
929 if (Ops.size() == 2) return NewAddRec;
930
931 Ops.erase(Ops.begin()+Idx);
932 Ops.erase(Ops.begin()+OtherIdx-1);
933 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000934 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 }
936 }
937
938 // Otherwise couldn't fold anything into this recurrence. Move onto the
939 // next one.
940 }
941
942 // Okay, it looks like we really DO need an add expr. Check to see if we
943 // already have one, otherwise create a new one.
944 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
945 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
946 SCEVOps)];
947 if (Result == 0) Result = new SCEVAddExpr(Ops);
948 return Result;
949}
950
951
Dan Gohman89f85052007-10-22 18:31:58 +0000952SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 assert(!Ops.empty() && "Cannot get empty mul!");
954
955 // Sort by complexity, this groups all similar expression types together.
956 GroupByComplexity(Ops);
957
958 // If there are any constants, fold them together.
959 unsigned Idx = 0;
960 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
961
962 // C1*(C2+V) -> C1*C2 + C1*V
963 if (Ops.size() == 2)
964 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
965 if (Add->getNumOperands() == 2 &&
966 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000967 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
968 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000969
970
971 ++Idx;
972 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
973 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000974 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
975 RHSC->getValue()->getValue());
976 Ops[0] = getConstant(Fold);
977 Ops.erase(Ops.begin()+1); // Erase the folded element
978 if (Ops.size() == 1) return Ops[0];
979 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 }
981
982 // If we are left with a constant one being multiplied, strip it off.
983 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
984 Ops.erase(Ops.begin());
985 --Idx;
986 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
987 // If we have a multiply of zero, it will always be zero.
988 return Ops[0];
989 }
990 }
991
992 // Skip over the add expression until we get to a multiply.
993 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
994 ++Idx;
995
996 if (Ops.size() == 1)
997 return Ops[0];
998
999 // If there are mul operands inline them all into this expression.
1000 if (Idx < Ops.size()) {
1001 bool DeletedMul = false;
1002 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1003 // If we have an mul, expand the mul operands onto the end of the operands
1004 // list.
1005 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1006 Ops.erase(Ops.begin()+Idx);
1007 DeletedMul = true;
1008 }
1009
1010 // If we deleted at least one mul, we added operands to the end of the list,
1011 // and they are not necessarily sorted. Recurse to resort and resimplify
1012 // any operands we just aquired.
1013 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001014 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 }
1016
1017 // If there are any add recurrences in the operands list, see if any other
1018 // added values are loop invariant. If so, we can fold them into the
1019 // recurrence.
1020 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1021 ++Idx;
1022
1023 // Scan over all recurrences, trying to fold loop invariants into them.
1024 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1025 // Scan all of the other operands to this mul and add them to the vector if
1026 // they are loop invariant w.r.t. the recurrence.
1027 std::vector<SCEVHandle> LIOps;
1028 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1029 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1030 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1031 LIOps.push_back(Ops[i]);
1032 Ops.erase(Ops.begin()+i);
1033 --i; --e;
1034 }
1035
1036 // If we found some loop invariants, fold them into the recurrence.
1037 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001038 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 std::vector<SCEVHandle> NewOps;
1040 NewOps.reserve(AddRec->getNumOperands());
1041 if (LIOps.size() == 1) {
1042 SCEV *Scale = LIOps[0];
1043 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001044 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 } else {
1046 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1047 std::vector<SCEVHandle> MulOps(LIOps);
1048 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001049 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050 }
1051 }
1052
Dan Gohman89f85052007-10-22 18:31:58 +00001053 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054
1055 // If all of the other operands were loop invariant, we are done.
1056 if (Ops.size() == 1) return NewRec;
1057
1058 // Otherwise, multiply the folded AddRec by the non-liv parts.
1059 for (unsigned i = 0;; ++i)
1060 if (Ops[i] == AddRec) {
1061 Ops[i] = NewRec;
1062 break;
1063 }
Dan Gohman89f85052007-10-22 18:31:58 +00001064 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 }
1066
1067 // Okay, if there weren't any loop invariants to be folded, check to see if
1068 // there are multiple AddRec's with the same loop induction variable being
1069 // multiplied together. If so, we can fold them.
1070 for (unsigned OtherIdx = Idx+1;
1071 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1072 if (OtherIdx != Idx) {
1073 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1074 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1075 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1076 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001077 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001079 SCEVHandle B = F->getStepRecurrence(*this);
1080 SCEVHandle D = G->getStepRecurrence(*this);
1081 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1082 getMulExpr(G, B),
1083 getMulExpr(B, D));
1084 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1085 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 if (Ops.size() == 2) return NewAddRec;
1087
1088 Ops.erase(Ops.begin()+Idx);
1089 Ops.erase(Ops.begin()+OtherIdx-1);
1090 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001091 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 }
1093 }
1094
1095 // Otherwise couldn't fold anything into this recurrence. Move onto the
1096 // next one.
1097 }
1098
1099 // Okay, it looks like we really DO need an mul expr. Check to see if we
1100 // already have one, otherwise create a new one.
1101 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1102 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1103 SCEVOps)];
1104 if (Result == 0)
1105 Result = new SCEVMulExpr(Ops);
1106 return Result;
1107}
1108
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001109SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1111 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001112 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113
1114 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1115 Constant *LHSCV = LHSC->getValue();
1116 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001117 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 }
1119 }
1120
Nick Lewycky35b56022009-01-13 09:18:58 +00001121 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1122
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001123 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1124 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 return Result;
1126}
1127
1128
1129/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1130/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001131SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 const SCEVHandle &Step, const Loop *L) {
1133 std::vector<SCEVHandle> Operands;
1134 Operands.push_back(Start);
1135 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1136 if (StepChrec->getLoop() == L) {
1137 Operands.insert(Operands.end(), StepChrec->op_begin(),
1138 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001139 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 }
1141
1142 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001143 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144}
1145
1146/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1147/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001148SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149 const Loop *L) {
1150 if (Operands.size() == 1) return Operands[0];
1151
Dan Gohman7b560c42008-06-18 16:23:07 +00001152 if (Operands.back()->isZero()) {
1153 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001154 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001155 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156
Dan Gohman42936882008-08-08 18:33:12 +00001157 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1158 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1159 const Loop* NestedLoop = NestedAR->getLoop();
1160 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1161 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1162 NestedAR->op_end());
1163 SCEVHandle NestedARHandle(NestedAR);
1164 Operands[0] = NestedAR->getStart();
1165 NestedOperands[0] = getAddRecExpr(Operands, L);
1166 return getAddRecExpr(NestedOperands, NestedLoop);
1167 }
1168 }
1169
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 SCEVAddRecExpr *&Result =
1171 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1172 Operands.end()))];
1173 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1174 return Result;
1175}
1176
Nick Lewycky711640a2007-11-25 22:41:31 +00001177SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1178 const SCEVHandle &RHS) {
1179 std::vector<SCEVHandle> Ops;
1180 Ops.push_back(LHS);
1181 Ops.push_back(RHS);
1182 return getSMaxExpr(Ops);
1183}
1184
1185SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1186 assert(!Ops.empty() && "Cannot get empty smax!");
1187 if (Ops.size() == 1) return Ops[0];
1188
1189 // Sort by complexity, this groups all similar expression types together.
1190 GroupByComplexity(Ops);
1191
1192 // If there are any constants, fold them together.
1193 unsigned Idx = 0;
1194 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1195 ++Idx;
1196 assert(Idx < Ops.size());
1197 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1198 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001199 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001200 APIntOps::smax(LHSC->getValue()->getValue(),
1201 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001202 Ops[0] = getConstant(Fold);
1203 Ops.erase(Ops.begin()+1); // Erase the folded element
1204 if (Ops.size() == 1) return Ops[0];
1205 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001206 }
1207
1208 // If we are left with a constant -inf, strip it off.
1209 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1210 Ops.erase(Ops.begin());
1211 --Idx;
1212 }
1213 }
1214
1215 if (Ops.size() == 1) return Ops[0];
1216
1217 // Find the first SMax
1218 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1219 ++Idx;
1220
1221 // Check to see if one of the operands is an SMax. If so, expand its operands
1222 // onto our operand list, and recurse to simplify.
1223 if (Idx < Ops.size()) {
1224 bool DeletedSMax = false;
1225 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1226 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1227 Ops.erase(Ops.begin()+Idx);
1228 DeletedSMax = true;
1229 }
1230
1231 if (DeletedSMax)
1232 return getSMaxExpr(Ops);
1233 }
1234
1235 // Okay, check to see if the same value occurs in the operand list twice. If
1236 // so, delete one. Since we sorted the list, these values are required to
1237 // be adjacent.
1238 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1239 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1240 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1241 --i; --e;
1242 }
1243
1244 if (Ops.size() == 1) return Ops[0];
1245
1246 assert(!Ops.empty() && "Reduced smax down to nothing!");
1247
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001248 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001249 // already have one, otherwise create a new one.
1250 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1251 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1252 SCEVOps)];
1253 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1254 return Result;
1255}
1256
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001257SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1258 const SCEVHandle &RHS) {
1259 std::vector<SCEVHandle> Ops;
1260 Ops.push_back(LHS);
1261 Ops.push_back(RHS);
1262 return getUMaxExpr(Ops);
1263}
1264
1265SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1266 assert(!Ops.empty() && "Cannot get empty umax!");
1267 if (Ops.size() == 1) return Ops[0];
1268
1269 // Sort by complexity, this groups all similar expression types together.
1270 GroupByComplexity(Ops);
1271
1272 // If there are any constants, fold them together.
1273 unsigned Idx = 0;
1274 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1275 ++Idx;
1276 assert(Idx < Ops.size());
1277 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1278 // We found two constants, fold them together!
1279 ConstantInt *Fold = ConstantInt::get(
1280 APIntOps::umax(LHSC->getValue()->getValue(),
1281 RHSC->getValue()->getValue()));
1282 Ops[0] = getConstant(Fold);
1283 Ops.erase(Ops.begin()+1); // Erase the folded element
1284 if (Ops.size() == 1) return Ops[0];
1285 LHSC = cast<SCEVConstant>(Ops[0]);
1286 }
1287
1288 // If we are left with a constant zero, strip it off.
1289 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1290 Ops.erase(Ops.begin());
1291 --Idx;
1292 }
1293 }
1294
1295 if (Ops.size() == 1) return Ops[0];
1296
1297 // Find the first UMax
1298 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1299 ++Idx;
1300
1301 // Check to see if one of the operands is a UMax. If so, expand its operands
1302 // onto our operand list, and recurse to simplify.
1303 if (Idx < Ops.size()) {
1304 bool DeletedUMax = false;
1305 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1306 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1307 Ops.erase(Ops.begin()+Idx);
1308 DeletedUMax = true;
1309 }
1310
1311 if (DeletedUMax)
1312 return getUMaxExpr(Ops);
1313 }
1314
1315 // Okay, check to see if the same value occurs in the operand list twice. If
1316 // so, delete one. Since we sorted the list, these values are required to
1317 // be adjacent.
1318 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1319 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1320 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1321 --i; --e;
1322 }
1323
1324 if (Ops.size() == 1) return Ops[0];
1325
1326 assert(!Ops.empty() && "Reduced umax down to nothing!");
1327
1328 // Okay, it looks like we really DO need a umax expr. Check to see if we
1329 // already have one, otherwise create a new one.
1330 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1331 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1332 SCEVOps)];
1333 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1334 return Result;
1335}
1336
Dan Gohman89f85052007-10-22 18:31:58 +00001337SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001339 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001340 if (isa<ConstantPointerNull>(V))
1341 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1343 if (Result == 0) Result = new SCEVUnknown(V);
1344 return Result;
1345}
1346
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347//===----------------------------------------------------------------------===//
1348// ScalarEvolutionsImpl Definition and Implementation
1349//===----------------------------------------------------------------------===//
1350//
1351/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1352/// evolution code.
1353///
1354namespace {
1355 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001356 /// SE - A reference to the public ScalarEvolution object.
1357 ScalarEvolution &SE;
1358
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 /// F - The function we are analyzing.
1360 ///
1361 Function &F;
1362
1363 /// LI - The loop information for the function we are currently analyzing.
1364 ///
1365 LoopInfo &LI;
1366
Dan Gohman01c2ee72009-04-16 03:18:22 +00001367 /// TD - The target data information for the target we are targetting.
1368 ///
1369 TargetData &TD;
1370
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1372 /// things.
1373 SCEVHandle UnknownValue;
1374
1375 /// Scalars - This is a cache of the scalars we have analyzed so far.
1376 ///
1377 std::map<Value*, SCEVHandle> Scalars;
1378
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001379 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
1380 /// this function as they are computed.
1381 std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382
1383 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1384 /// the PHI instructions that we attempt to compute constant evolutions for.
1385 /// This allows us to avoid potentially expensive recomputation of these
1386 /// properties. An instruction maps to null if we are unable to compute its
1387 /// exit value.
1388 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1389
1390 public:
Dan Gohman01c2ee72009-04-16 03:18:22 +00001391 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li,
1392 TargetData &td)
1393 : SE(se), F(f), LI(li), TD(td), UnknownValue(new SCEVCouldNotCompute()) {}
1394
Dan Gohman0ad08b02009-04-18 17:58:19 +00001395 SCEVHandle getCouldNotCompute();
1396
Dan Gohman01c2ee72009-04-16 03:18:22 +00001397 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1398 /// specified signed integer value and return a SCEV for the constant.
1399 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
1400
1401 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1402 ///
1403 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
1404
1405 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1406 ///
1407 SCEVHandle getNotSCEV(const SCEVHandle &V);
1408
1409 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1410 ///
1411 SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS);
1412
1413 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
1414 /// of the input value to the specified type. If the type must be extended,
1415 /// it is zero extended.
1416 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
1417
1418 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
1419 /// of the input value to the specified type. If the type must be extended,
1420 /// it is sign extended.
1421 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422
1423 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1424 /// expression and create a new one.
1425 SCEVHandle getSCEV(Value *V);
1426
1427 /// hasSCEV - Return true if the SCEV for this value has already been
1428 /// computed.
1429 bool hasSCEV(Value *V) const {
1430 return Scalars.count(V);
1431 }
1432
1433 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1434 /// the specified value.
1435 void setSCEV(Value *V, const SCEVHandle &H) {
1436 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1437 assert(isNew && "This entry already existed!");
Devang Patelfc736502008-11-11 19:17:41 +00001438 isNew = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 }
1440
1441
1442 /// getSCEVAtScope - Compute the value of the specified expression within
1443 /// the indicated loop (which may be null to indicate in no loop). If the
1444 /// expression cannot be evaluated, return UnknownValue itself.
1445 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1446
1447
Dan Gohmancacd2012009-02-12 22:19:27 +00001448 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1449 /// a conditional between LHS and RHS.
1450 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1451 SCEV *LHS, SCEV *RHS);
1452
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001453 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
1454 /// has an analyzable loop-invariant backedge-taken count.
1455 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001457 /// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001458 /// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001459 /// ScalarEvolution's ability to compute a trip count, or if the loop
1460 /// is deleted.
1461 void forgetLoopBackedgeTakenCount(const Loop *L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001462
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001463 /// getBackedgeTakenCount - If the specified loop has a predictable
1464 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1465 /// object. The backedge-taken count is the number of times the loop header
1466 /// will be branched to from within the loop. This is one less than the
1467 /// trip count of the loop, since it doesn't count the first iteration,
1468 /// when the header is branched to from outside the loop.
1469 ///
1470 /// Note that it is not valid to call this method on a loop without a
1471 /// loop-invariant backedge-taken count (see
1472 /// hasLoopInvariantBackedgeTakenCount).
1473 ///
1474 SCEVHandle getBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475
1476 /// deleteValueFromRecords - This method should be called by the
1477 /// client before it removes a value from the program, to make sure
1478 /// that no dangling references are left around.
1479 void deleteValueFromRecords(Value *V);
1480
Dan Gohman01c2ee72009-04-16 03:18:22 +00001481 /// getTargetData - Return the TargetData.
1482 const TargetData &getTargetData() const;
1483
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 private:
1485 /// createSCEV - We know that there is no SCEV for the specified value.
1486 /// Analyze the expression.
1487 SCEVHandle createSCEV(Value *V);
1488
1489 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1490 /// SCEVs.
1491 SCEVHandle createNodeForPHI(PHINode *PN);
1492
1493 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1494 /// for the specified instruction and replaces any references to the
1495 /// symbolic value SymName with the specified value. This is used during
1496 /// PHI resolution.
1497 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1498 const SCEVHandle &SymName,
1499 const SCEVHandle &NewVal);
1500
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001501 /// ComputeBackedgeTakenCount - Compute the number of times the specified
1502 /// loop will iterate.
1503 SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001505 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
1506 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
1507 SCEVHandle
1508 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
1509 Constant *RHS,
1510 const Loop *L,
1511 ICmpInst::Predicate p);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001513 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
1514 /// a constant number of times (the condition evolves only from constants),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515 /// try to evaluate a few iterations of the loop until we get the exit
1516 /// condition gets a value of ExitWhen (true or false). If we cannot
1517 /// evaluate the trip count of the loop, return UnknownValue.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001518 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
1519 bool ExitWhen);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520
1521 /// HowFarToZero - Return the number of times a backedge comparing the
1522 /// specified value to zero will execute. If not computable, return
1523 /// UnknownValue.
1524 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1525
1526 /// HowFarToNonZero - Return the number of times a backedge checking the
1527 /// specified value for nonzero will execute. If not computable, return
1528 /// UnknownValue.
1529 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1530
1531 /// HowManyLessThans - Return the number of times a backedge containing the
1532 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001533 /// UnknownValue. isSigned specifies whether the less-than is signed.
1534 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewycky35b56022009-01-13 09:18:58 +00001535 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001536
Dan Gohman1cddf972008-09-15 22:18:04 +00001537 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1538 /// (which may not be an immediate predecessor) which has exactly one
1539 /// successor from which BB is reachable, or null if no such block is
1540 /// found.
1541 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1542
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1544 /// in the header of its containing loop, we know the loop executes a
1545 /// constant number of times, and the PHI node is just a recurrence
1546 /// involving constants, fold it.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001547 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548 const Loop *L);
1549 };
1550}
1551
1552//===----------------------------------------------------------------------===//
1553// Basic SCEV Analysis and PHI Idiom Recognition Code
1554//
1555
1556/// deleteValueFromRecords - 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.
1559void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1560 SmallVector<Value *, 16> Worklist;
1561
1562 if (Scalars.erase(V)) {
1563 if (PHINode *PN = dyn_cast<PHINode>(V))
1564 ConstantEvolutionLoopExitValue.erase(PN);
1565 Worklist.push_back(V);
1566 }
1567
1568 while (!Worklist.empty()) {
1569 Value *VV = Worklist.back();
1570 Worklist.pop_back();
1571
1572 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1573 UI != UE; ++UI) {
1574 Instruction *Inst = cast<Instruction>(*UI);
1575 if (Scalars.erase(Inst)) {
1576 if (PHINode *PN = dyn_cast<PHINode>(VV))
1577 ConstantEvolutionLoopExitValue.erase(PN);
1578 Worklist.push_back(Inst);
1579 }
1580 }
1581 }
1582}
1583
Dan Gohman01c2ee72009-04-16 03:18:22 +00001584const TargetData &ScalarEvolutionsImpl::getTargetData() const {
1585 return TD;
1586}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001587
Dan Gohman0ad08b02009-04-18 17:58:19 +00001588SCEVHandle ScalarEvolutionsImpl::getCouldNotCompute() {
1589 return UnknownValue;
1590}
1591
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1593/// expression and create a new one.
1594SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1595 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1596
1597 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1598 if (I != Scalars.end()) return I->second;
1599 SCEVHandle S = createSCEV(V);
1600 Scalars.insert(std::make_pair(V, S));
1601 return S;
1602}
1603
Dan Gohman01c2ee72009-04-16 03:18:22 +00001604/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1605/// specified signed integer value and return a SCEV for the constant.
1606SCEVHandle ScalarEvolutionsImpl::getIntegerSCEV(int Val, const Type *Ty) {
1607 if (isa<PointerType>(Ty))
1608 Ty = TD.getIntPtrType();
1609 Constant *C;
1610 if (Val == 0)
1611 C = Constant::getNullValue(Ty);
1612 else if (Ty->isFloatingPoint())
1613 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1614 APFloat::IEEEdouble, Val));
1615 else
1616 C = ConstantInt::get(Ty, Val);
1617 return SE.getUnknown(C);
1618}
1619
1620/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1621///
1622SCEVHandle ScalarEvolutionsImpl::getNegativeSCEV(const SCEVHandle &V) {
1623 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1624 return SE.getUnknown(ConstantExpr::getNeg(VC->getValue()));
1625
1626 const Type *Ty = V->getType();
1627 if (isa<PointerType>(Ty))
1628 Ty = TD.getIntPtrType();
1629 return SE.getMulExpr(V, SE.getConstant(ConstantInt::getAllOnesValue(Ty)));
1630}
1631
1632/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1633SCEVHandle ScalarEvolutionsImpl::getNotSCEV(const SCEVHandle &V) {
1634 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1635 return SE.getUnknown(ConstantExpr::getNot(VC->getValue()));
1636
1637 const Type *Ty = V->getType();
1638 if (isa<PointerType>(Ty))
1639 Ty = TD.getIntPtrType();
1640 SCEVHandle AllOnes = SE.getConstant(ConstantInt::getAllOnesValue(Ty));
1641 return getMinusSCEV(AllOnes, V);
1642}
1643
1644/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1645///
1646SCEVHandle ScalarEvolutionsImpl::getMinusSCEV(const SCEVHandle &LHS,
1647 const SCEVHandle &RHS) {
1648 // X - Y --> X + -Y
1649 return SE.getAddExpr(LHS, SE.getNegativeSCEV(RHS));
1650}
1651
1652/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1653/// input value to the specified type. If the type must be extended, it is zero
1654/// extended.
1655SCEVHandle
1656ScalarEvolutionsImpl::getTruncateOrZeroExtend(const SCEVHandle &V,
1657 const Type *Ty) {
1658 const Type *SrcTy = V->getType();
1659 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
1660 (Ty->isInteger() || isa<PointerType>(Ty)) &&
1661 "Cannot truncate or zero extend with non-integer arguments!");
1662 if (TD.getTypeSizeInBits(SrcTy) == TD.getTypeSizeInBits(Ty))
1663 return V; // No conversion
1664 if (TD.getTypeSizeInBits(SrcTy) > TD.getTypeSizeInBits(Ty))
1665 return SE.getTruncateExpr(V, Ty);
1666 return SE.getZeroExtendExpr(V, Ty);
1667}
1668
1669/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1670/// input value to the specified type. If the type must be extended, it is sign
1671/// extended.
1672SCEVHandle
1673ScalarEvolutionsImpl::getTruncateOrSignExtend(const SCEVHandle &V,
1674 const Type *Ty) {
1675 const Type *SrcTy = V->getType();
1676 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
1677 (Ty->isInteger() || isa<PointerType>(Ty)) &&
1678 "Cannot truncate or zero extend with non-integer arguments!");
1679 if (TD.getTypeSizeInBits(SrcTy) == TD.getTypeSizeInBits(Ty))
1680 return V; // No conversion
1681 if (TD.getTypeSizeInBits(SrcTy) > TD.getTypeSizeInBits(Ty))
1682 return SE.getTruncateExpr(V, Ty);
1683 return SE.getSignExtendExpr(V, Ty);
1684}
1685
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1687/// the specified instruction and replaces any references to the symbolic value
1688/// SymName with the specified value. This is used during PHI resolution.
1689void ScalarEvolutionsImpl::
1690ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1691 const SCEVHandle &NewVal) {
1692 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1693 if (SI == Scalars.end()) return;
1694
1695 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001696 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697 if (NV == SI->second) return; // No change.
1698
1699 SI->second = NV; // Update the scalars map!
1700
1701 // Any instruction values that use this instruction might also need to be
1702 // updated!
1703 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1704 UI != E; ++UI)
1705 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1706}
1707
1708/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1709/// a loop header, making it a potential recurrence, or it doesn't.
1710///
1711SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1712 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1713 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1714 if (L->getHeader() == PN->getParent()) {
1715 // If it lives in the loop header, it has two incoming values, one
1716 // from outside the loop, and one from inside.
1717 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1718 unsigned BackEdge = IncomingEdge^1;
1719
1720 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001721 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722 assert(Scalars.find(PN) == Scalars.end() &&
1723 "PHI node already processed?");
1724 Scalars.insert(std::make_pair(PN, SymbolicName));
1725
1726 // Using this symbolic name for the PHI, analyze the value coming around
1727 // the back-edge.
1728 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1729
1730 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1731 // has a special value for the first iteration of the loop.
1732
1733 // If the value coming around the backedge is an add with the symbolic
1734 // value we just inserted, then we found a simple induction variable!
1735 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1736 // If there is a single occurrence of the symbolic value, replace it
1737 // with a recurrence.
1738 unsigned FoundIndex = Add->getNumOperands();
1739 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1740 if (Add->getOperand(i) == SymbolicName)
1741 if (FoundIndex == e) {
1742 FoundIndex = i;
1743 break;
1744 }
1745
1746 if (FoundIndex != Add->getNumOperands()) {
1747 // Create an add with everything but the specified operand.
1748 std::vector<SCEVHandle> Ops;
1749 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1750 if (i != FoundIndex)
1751 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001752 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001753
1754 // This is not a valid addrec if the step amount is varying each
1755 // loop iteration, but is not itself an addrec in this loop.
1756 if (Accum->isLoopInvariant(L) ||
1757 (isa<SCEVAddRecExpr>(Accum) &&
1758 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1759 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001760 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761
1762 // Okay, for the entire analysis of this edge we assumed the PHI
1763 // to be symbolic. We now need to go back and update all of the
1764 // entries for the scalars that use the PHI (except for the PHI
1765 // itself) to use the new analyzed value instead of the "symbolic"
1766 // value.
1767 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1768 return PHISCEV;
1769 }
1770 }
1771 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1772 // Otherwise, this could be a loop like this:
1773 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1774 // In this case, j = {1,+,1} and BEValue is j.
1775 // Because the other in-value of i (0) fits the evolution of BEValue
1776 // i really is an addrec evolution.
1777 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1778 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1779
1780 // If StartVal = j.start - j.stride, we can use StartVal as the
1781 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001782 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1783 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001785 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001786
1787 // Okay, for the entire analysis of this edge we assumed the PHI
1788 // to be symbolic. We now need to go back and update all of the
1789 // entries for the scalars that use the PHI (except for the PHI
1790 // itself) to use the new analyzed value instead of the "symbolic"
1791 // value.
1792 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1793 return PHISCEV;
1794 }
1795 }
1796 }
1797
1798 return SymbolicName;
1799 }
1800
1801 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001802 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001803}
1804
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001805/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1806/// guaranteed to end in (at every loop iteration). It is, at the same time,
1807/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1808/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001809static uint32_t GetMinTrailingZeros(SCEVHandle S, const TargetData &TD) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001810 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001811 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001813 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001814 return std::min(GetMinTrailingZeros(T->getOperand(), TD),
1815 (uint32_t)TD.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001816
1817 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001818 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), TD);
1819 return OpRes == TD.getTypeSizeInBits(E->getOperand()->getType()) ?
1820 TD.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001821 }
1822
1823 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001824 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), TD);
1825 return OpRes == TD.getTypeSizeInBits(E->getOperand()->getType()) ?
1826 TD.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001827 }
1828
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001829 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001830 // The result is the min of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001831 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), TD);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001832 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001833 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), TD));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001834 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835 }
1836
1837 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001838 // The result is the sum of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001839 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
1840 uint32_t BitWidth = TD.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001841 for (unsigned i = 1, e = M->getNumOperands();
1842 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001843 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), TD),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001844 BitWidth);
1845 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001846 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001847
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001849 // The result is the min of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001850 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), TD);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001851 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001852 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), TD));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001853 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001855
Nick Lewycky711640a2007-11-25 22:41:31 +00001856 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1857 // The result is the min of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001858 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
Nick Lewycky711640a2007-11-25 22:41:31 +00001859 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001860 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), TD));
Nick Lewycky711640a2007-11-25 22:41:31 +00001861 return MinOpRes;
1862 }
1863
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001864 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1865 // The result is the min of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001866 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001867 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001868 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), TD));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001869 return MinOpRes;
1870 }
1871
Nick Lewycky35b56022009-01-13 09:18:58 +00001872 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001873 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874}
1875
1876/// createSCEV - We know that there is no SCEV for the specified value.
1877/// Analyze the expression.
1878///
1879SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001880 if (!isa<IntegerType>(V->getType()) &&
1881 !isa<PointerType>(V->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00001882 return SE.getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001883
Dan Gohman3996f472008-06-22 19:56:46 +00001884 unsigned Opcode = Instruction::UserOp1;
1885 if (Instruction *I = dyn_cast<Instruction>(V))
1886 Opcode = I->getOpcode();
1887 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1888 Opcode = CE->getOpcode();
1889 else
1890 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001891
Dan Gohman3996f472008-06-22 19:56:46 +00001892 User *U = cast<User>(V);
1893 switch (Opcode) {
1894 case Instruction::Add:
1895 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1896 getSCEV(U->getOperand(1)));
1897 case Instruction::Mul:
1898 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1899 getSCEV(U->getOperand(1)));
1900 case Instruction::UDiv:
1901 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1902 getSCEV(U->getOperand(1)));
1903 case Instruction::Sub:
1904 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1905 getSCEV(U->getOperand(1)));
1906 case Instruction::Or:
1907 // If the RHS of the Or is a constant, we may have something like:
1908 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1909 // optimizations will transparently handle this case.
1910 //
1911 // In order for this transformation to be safe, the LHS must be of the
1912 // form X*(2^n) and the Or constant must be less than 2^n.
1913 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1914 SCEVHandle LHS = getSCEV(U->getOperand(0));
1915 const APInt &CIVal = CI->getValue();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001916 if (GetMinTrailingZeros(LHS, TD) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001917 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1918 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919 }
Dan Gohman3996f472008-06-22 19:56:46 +00001920 break;
1921 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001922 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001923 // If the RHS of the xor is a signbit, then this is just an add.
1924 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001925 if (CI->getValue().isSignBit())
1926 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1927 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001928
1929 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001930 else if (CI->isAllOnesValue())
1931 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1932 }
1933 break;
1934
1935 case Instruction::Shl:
1936 // Turn shift left of a constant amount into a multiply.
1937 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1938 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1939 Constant *X = ConstantInt::get(
1940 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1941 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1942 }
1943 break;
1944
Nick Lewycky7fd27892008-07-07 06:15:49 +00001945 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001946 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001947 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1948 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1949 Constant *X = ConstantInt::get(
1950 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1951 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1952 }
1953 break;
1954
Dan Gohman3996f472008-06-22 19:56:46 +00001955 case Instruction::Trunc:
1956 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1957
1958 case Instruction::ZExt:
1959 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1960
1961 case Instruction::SExt:
1962 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1963
1964 case Instruction::BitCast:
1965 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001966 if ((U->getType()->isInteger() ||
1967 isa<PointerType>(U->getType())) &&
1968 (U->getOperand(0)->getType()->isInteger() ||
1969 isa<PointerType>(U->getOperand(0)->getType())))
Dan Gohman3996f472008-06-22 19:56:46 +00001970 return getSCEV(U->getOperand(0));
1971 break;
1972
Dan Gohman01c2ee72009-04-16 03:18:22 +00001973 case Instruction::IntToPtr:
1974 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1975 TD.getIntPtrType());
1976
1977 case Instruction::PtrToInt:
1978 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1979 U->getType());
1980
1981 case Instruction::GetElementPtr: {
1982 const Type *IntPtrTy = TD.getIntPtrType();
1983 Value *Base = U->getOperand(0);
1984 SCEVHandle TotalOffset = SE.getIntegerSCEV(0, IntPtrTy);
1985 gep_type_iterator GTI = gep_type_begin(U);
1986 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1987 E = U->op_end();
1988 I != E; ++I) {
1989 Value *Index = *I;
1990 // Compute the (potentially symbolic) offset in bytes for this index.
1991 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1992 // For a struct, add the member offset.
1993 const StructLayout &SL = *TD.getStructLayout(STy);
1994 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1995 uint64_t Offset = SL.getElementOffset(FieldNo);
1996 TotalOffset = SE.getAddExpr(TotalOffset,
1997 SE.getIntegerSCEV(Offset, IntPtrTy));
1998 } else {
1999 // For an array, add the element offset, explicitly scaled.
2000 SCEVHandle LocalOffset = getSCEV(Index);
2001 if (!isa<PointerType>(LocalOffset->getType()))
2002 // Getelementptr indicies are signed.
2003 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2004 IntPtrTy);
2005 LocalOffset =
2006 SE.getMulExpr(LocalOffset,
2007 SE.getIntegerSCEV(TD.getTypePaddedSize(*GTI),
2008 IntPtrTy));
2009 TotalOffset = SE.getAddExpr(TotalOffset, LocalOffset);
2010 }
2011 }
2012 return SE.getAddExpr(getSCEV(Base), TotalOffset);
2013 }
2014
Dan Gohman3996f472008-06-22 19:56:46 +00002015 case Instruction::PHI:
2016 return createNodeForPHI(cast<PHINode>(U));
2017
2018 case Instruction::Select:
2019 // This could be a smax or umax that was lowered earlier.
2020 // Try to recover it.
2021 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2022 Value *LHS = ICI->getOperand(0);
2023 Value *RHS = ICI->getOperand(1);
2024 switch (ICI->getPredicate()) {
2025 case ICmpInst::ICMP_SLT:
2026 case ICmpInst::ICMP_SLE:
2027 std::swap(LHS, RHS);
2028 // fall through
2029 case ICmpInst::ICMP_SGT:
2030 case ICmpInst::ICMP_SGE:
2031 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2032 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2033 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002034 // ~smax(~x, ~y) == smin(x, y).
2035 return SE.getNotSCEV(SE.getSMaxExpr(
2036 SE.getNotSCEV(getSCEV(LHS)),
2037 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002038 break;
2039 case ICmpInst::ICMP_ULT:
2040 case ICmpInst::ICMP_ULE:
2041 std::swap(LHS, RHS);
2042 // fall through
2043 case ICmpInst::ICMP_UGT:
2044 case ICmpInst::ICMP_UGE:
2045 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2046 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2047 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2048 // ~umax(~x, ~y) == umin(x, y)
2049 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
2050 SE.getNotSCEV(getSCEV(RHS))));
2051 break;
2052 default:
2053 break;
2054 }
2055 }
2056
2057 default: // We cannot analyze this expression.
2058 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002059 }
2060
Dan Gohman89f85052007-10-22 18:31:58 +00002061 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002062}
2063
2064
2065
2066//===----------------------------------------------------------------------===//
2067// Iteration Count Computation Code
2068//
2069
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002070/// getBackedgeTakenCount - If the specified loop has a predictable
2071/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2072/// object. The backedge-taken count is the number of times the loop header
2073/// will be branched to from within the loop. This is one less than the
2074/// trip count of the loop, since it doesn't count the first iteration,
2075/// when the header is branched to from outside the loop.
2076///
2077/// Note that it is not valid to call this method on a loop without a
2078/// loop-invariant backedge-taken count (see
2079/// hasLoopInvariantBackedgeTakenCount).
2080///
2081SCEVHandle ScalarEvolutionsImpl::getBackedgeTakenCount(const Loop *L) {
2082 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
2083 if (I == BackedgeTakenCounts.end()) {
2084 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
2085 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002086 if (ItCount != UnknownValue) {
2087 assert(ItCount->isLoopInvariant(L) &&
2088 "Computed trip count isn't loop invariant for loop!");
2089 ++NumTripCountsComputed;
2090 } else if (isa<PHINode>(L->getHeader()->begin())) {
2091 // Only count loops that have phi nodes as not being computable.
2092 ++NumTripCountsNotComputed;
2093 }
2094 }
2095 return I->second;
2096}
2097
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002098/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002099/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002100/// ScalarEvolution's ability to compute a trip count, or if the loop
2101/// is deleted.
2102void ScalarEvolutionsImpl::forgetLoopBackedgeTakenCount(const Loop *L) {
2103 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002104}
2105
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002106/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2107/// of the specified loop will execute.
2108SCEVHandle ScalarEvolutionsImpl::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002109 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002110 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002111 L->getExitBlocks(ExitBlocks);
2112 if (ExitBlocks.size() != 1) return UnknownValue;
2113
2114 // Okay, there is one exit block. Try to find the condition that causes the
2115 // loop to be exited.
2116 BasicBlock *ExitBlock = ExitBlocks[0];
2117
2118 BasicBlock *ExitingBlock = 0;
2119 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2120 PI != E; ++PI)
2121 if (L->contains(*PI)) {
2122 if (ExitingBlock == 0)
2123 ExitingBlock = *PI;
2124 else
2125 return UnknownValue; // More than one block exiting!
2126 }
2127 assert(ExitingBlock && "No exits from loop, something is broken!");
2128
2129 // Okay, we've computed the exiting block. See what condition causes us to
2130 // exit.
2131 //
2132 // FIXME: we should be able to handle switch instructions (with a single exit)
2133 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2134 if (ExitBr == 0) return UnknownValue;
2135 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2136
2137 // At this point, we know we have a conditional branch that determines whether
2138 // the loop is exited. However, we don't know if the branch is executed each
2139 // time through the loop. If not, then the execution count of the branch will
2140 // not be equal to the trip count of the loop.
2141 //
2142 // Currently we check for this by checking to see if the Exit branch goes to
2143 // the loop header. If so, we know it will always execute the same number of
2144 // times as the loop. We also handle the case where the exit block *is* the
2145 // loop header. This is common for un-rotated loops. More extensive analysis
2146 // could be done to handle more cases here.
2147 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2148 ExitBr->getSuccessor(1) != L->getHeader() &&
2149 ExitBr->getParent() != L->getHeader())
2150 return UnknownValue;
2151
2152 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2153
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002154 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 // Note that ICmpInst deals with pointer comparisons too so we must check
2156 // the type of the operand.
2157 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002158 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159 ExitBr->getSuccessor(0) == ExitBlock);
2160
2161 // If the condition was exit on true, convert the condition to exit on false
2162 ICmpInst::Predicate Cond;
2163 if (ExitBr->getSuccessor(1) == ExitBlock)
2164 Cond = ExitCond->getPredicate();
2165 else
2166 Cond = ExitCond->getInversePredicate();
2167
2168 // Handle common loops like: for (X = "string"; *X; ++X)
2169 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2170 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2171 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002172 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002173 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2174 }
2175
2176 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2177 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2178
2179 // Try to evaluate any dependencies out of the loop.
2180 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2181 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2182 Tmp = getSCEVAtScope(RHS, L);
2183 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2184
2185 // At this point, we would like to compute how many iterations of the
2186 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002187 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2188 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189 std::swap(LHS, RHS);
2190 Cond = ICmpInst::getSwappedPredicate(Cond);
2191 }
2192
2193 // FIXME: think about handling pointer comparisons! i.e.:
2194 // while (P != P+100) ++P;
2195
2196 // If we have a comparison of a chrec against a constant, try to use value
2197 // ranges to answer this query.
2198 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2199 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2200 if (AddRec->getLoop() == L) {
2201 // Form the comparison range using the constant of the correct type so
2202 // that the ConstantRange class knows to do a signed or unsigned
2203 // comparison.
2204 ConstantInt *CompVal = RHSC->getValue();
2205 const Type *RealTy = ExitCond->getOperand(0)->getType();
2206 CompVal = dyn_cast<ConstantInt>(
2207 ConstantExpr::getBitCast(CompVal, RealTy));
2208 if (CompVal) {
2209 // Form the constant range.
2210 ConstantRange CompRange(
2211 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2212
Dan Gohman89f85052007-10-22 18:31:58 +00002213 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002214 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2215 }
2216 }
2217
2218 switch (Cond) {
2219 case ICmpInst::ICMP_NE: { // while (X != Y)
2220 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00002221 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002222 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2223 break;
2224 }
2225 case ICmpInst::ICMP_EQ: {
2226 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00002227 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002228 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2229 break;
2230 }
2231 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002232 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002233 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2234 break;
2235 }
2236 case ICmpInst::ICMP_SGT: {
Eli Friedman0dcd4ed2008-07-30 00:04:08 +00002237 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002238 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002239 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2240 break;
2241 }
2242 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002243 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002244 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2245 break;
2246 }
2247 case ICmpInst::ICMP_UGT: {
Dale Johannesend721b952008-04-20 16:58:57 +00002248 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002249 SE.getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002250 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2251 break;
2252 }
2253 default:
2254#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002255 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002256 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002257 errs() << "[unsigned] ";
2258 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002259 << Instruction::getOpcodeName(Instruction::ICmp)
2260 << " " << *RHS << "\n";
2261#endif
2262 break;
2263 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002264 return
2265 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2266 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002267}
2268
2269static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002270EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2271 ScalarEvolution &SE) {
2272 SCEVHandle InVal = SE.getConstant(C);
2273 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 assert(isa<SCEVConstant>(Val) &&
2275 "Evaluation of SCEV at constant didn't fold correctly?");
2276 return cast<SCEVConstant>(Val)->getValue();
2277}
2278
2279/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2280/// and a GEP expression (missing the pointer index) indexing into it, return
2281/// the addressed element of the initializer or null if the index expression is
2282/// invalid.
2283static Constant *
2284GetAddressedElementFromGlobal(GlobalVariable *GV,
2285 const std::vector<ConstantInt*> &Indices) {
2286 Constant *Init = GV->getInitializer();
2287 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2288 uint64_t Idx = Indices[i]->getZExtValue();
2289 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2290 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2291 Init = cast<Constant>(CS->getOperand(Idx));
2292 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2293 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2294 Init = cast<Constant>(CA->getOperand(Idx));
2295 } else if (isa<ConstantAggregateZero>(Init)) {
2296 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2297 assert(Idx < STy->getNumElements() && "Bad struct index!");
2298 Init = Constant::getNullValue(STy->getElementType(Idx));
2299 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2300 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2301 Init = Constant::getNullValue(ATy->getElementType());
2302 } else {
2303 assert(0 && "Unknown constant aggregate type!");
2304 }
2305 return 0;
2306 } else {
2307 return 0; // Unknown initializer type
2308 }
2309 }
2310 return Init;
2311}
2312
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002313/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2314/// 'icmp op load X, cst', try to see if we can compute the backedge
2315/// execution count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316SCEVHandle ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002317ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2318 const Loop *L,
2319 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002320 if (LI->isVolatile()) return UnknownValue;
2321
2322 // Check to see if the loaded pointer is a getelementptr of a global.
2323 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2324 if (!GEP) return UnknownValue;
2325
2326 // Make sure that it is really a constant global we are gepping, with an
2327 // initializer, and make sure the first IDX is really 0.
2328 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2329 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2330 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2331 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2332 return UnknownValue;
2333
2334 // Okay, we allow one non-constant index into the GEP instruction.
2335 Value *VarIdx = 0;
2336 std::vector<ConstantInt*> Indexes;
2337 unsigned VarIdxNum = 0;
2338 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2339 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2340 Indexes.push_back(CI);
2341 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2342 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2343 VarIdx = GEP->getOperand(i);
2344 VarIdxNum = i-2;
2345 Indexes.push_back(0);
2346 }
2347
2348 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2349 // Check to see if X is a loop variant variable value now.
2350 SCEVHandle Idx = getSCEV(VarIdx);
2351 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2352 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2353
2354 // We can only recognize very limited forms of loop index expressions, in
2355 // particular, only affine AddRec's like {C1,+,C2}.
2356 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2357 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2358 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2359 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2360 return UnknownValue;
2361
2362 unsigned MaxSteps = MaxBruteForceIterations;
2363 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2364 ConstantInt *ItCst =
2365 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00002366 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002367
2368 // Form the GEP offset.
2369 Indexes[VarIdxNum] = Val;
2370
2371 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2372 if (Result == 0) break; // Cannot compute!
2373
2374 // Evaluate the condition for this iteration.
2375 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2376 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2377 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2378#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002379 errs() << "\n***\n*** Computed loop count " << *ItCst
2380 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2381 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002382#endif
2383 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00002384 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002385 }
2386 }
2387 return UnknownValue;
2388}
2389
2390
2391/// CanConstantFold - Return true if we can constant fold an instruction of the
2392/// specified type, assuming that all operands were constants.
2393static bool CanConstantFold(const Instruction *I) {
2394 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2395 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2396 return true;
2397
2398 if (const CallInst *CI = dyn_cast<CallInst>(I))
2399 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002400 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002401 return false;
2402}
2403
2404/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2405/// in the loop that V is derived from. We allow arbitrary operations along the
2406/// way, but the operands of an operation must either be constants or a value
2407/// derived from a constant PHI. If this expression does not fit with these
2408/// constraints, return null.
2409static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2410 // If this is not an instruction, or if this is an instruction outside of the
2411 // loop, it can't be derived from a loop PHI.
2412 Instruction *I = dyn_cast<Instruction>(V);
2413 if (I == 0 || !L->contains(I->getParent())) return 0;
2414
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002415 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002416 if (L->getHeader() == I->getParent())
2417 return PN;
2418 else
2419 // We don't currently keep track of the control flow needed to evaluate
2420 // PHIs, so we cannot handle PHIs inside of loops.
2421 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002422 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423
2424 // If we won't be able to constant fold this expression even if the operands
2425 // are constants, return early.
2426 if (!CanConstantFold(I)) return 0;
2427
2428 // Otherwise, we can evaluate this instruction if all of its operands are
2429 // constant or derived from a PHI node themselves.
2430 PHINode *PHI = 0;
2431 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2432 if (!(isa<Constant>(I->getOperand(Op)) ||
2433 isa<GlobalValue>(I->getOperand(Op)))) {
2434 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2435 if (P == 0) return 0; // Not evolving from PHI
2436 if (PHI == 0)
2437 PHI = P;
2438 else if (PHI != P)
2439 return 0; // Evolving from multiple different PHIs.
2440 }
2441
2442 // This is a expression evolving from a constant PHI!
2443 return PHI;
2444}
2445
2446/// EvaluateExpression - Given an expression that passes the
2447/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2448/// in the loop has the value PHIVal. If we can't fold this expression for some
2449/// reason, return null.
2450static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2451 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002452 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002453 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002454 Instruction *I = cast<Instruction>(V);
2455
2456 std::vector<Constant*> Operands;
2457 Operands.resize(I->getNumOperands());
2458
2459 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2460 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2461 if (Operands[i] == 0) return 0;
2462 }
2463
Chris Lattnerd6e56912007-12-10 22:53:04 +00002464 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2465 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2466 &Operands[0], Operands.size());
2467 else
2468 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2469 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002470}
2471
2472/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2473/// in the header of its containing loop, we know the loop executes a
2474/// constant number of times, and the PHI node is just a recurrence
2475/// involving constants, fold it.
2476Constant *ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002477getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 std::map<PHINode*, Constant*>::iterator I =
2479 ConstantEvolutionLoopExitValue.find(PN);
2480 if (I != ConstantEvolutionLoopExitValue.end())
2481 return I->second;
2482
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002483 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002484 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2485
2486 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2487
2488 // Since the loop is canonicalized, the PHI node must have two entries. One
2489 // entry must be a constant (coming in from outside of the loop), and the
2490 // second must be derived from the same PHI.
2491 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2492 Constant *StartCST =
2493 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2494 if (StartCST == 0)
2495 return RetVal = 0; // Must be a constant.
2496
2497 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2498 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2499 if (PN2 != PN)
2500 return RetVal = 0; // Not derived from same PHI.
2501
2502 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002503 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2505
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002506 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002507 unsigned IterationNum = 0;
2508 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2509 if (IterationNum == NumIterations)
2510 return RetVal = PHIVal; // Got exit value!
2511
2512 // Compute the value of the PHI node for the next iteration.
2513 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2514 if (NextPHI == PHIVal)
2515 return RetVal = NextPHI; // Stopped evolving!
2516 if (NextPHI == 0)
2517 return 0; // Couldn't evaluate!
2518 PHIVal = NextPHI;
2519 }
2520}
2521
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002522/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002523/// constant number of times (the condition evolves only from constants),
2524/// try to evaluate a few iterations of the loop until we get the exit
2525/// condition gets a value of ExitWhen (true or false). If we cannot
2526/// evaluate the trip count of the loop, return UnknownValue.
2527SCEVHandle ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002528ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002529 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2530 if (PN == 0) return UnknownValue;
2531
2532 // Since the loop is canonicalized, the PHI node must have two entries. One
2533 // entry must be a constant (coming in from outside of the loop), and the
2534 // second must be derived from the same PHI.
2535 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2536 Constant *StartCST =
2537 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2538 if (StartCST == 0) return UnknownValue; // Must be a constant.
2539
2540 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2541 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2542 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2543
2544 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2545 // the loop symbolically to determine when the condition gets a value of
2546 // "ExitWhen".
2547 unsigned IterationNum = 0;
2548 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2549 for (Constant *PHIVal = StartCST;
2550 IterationNum != MaxIterations; ++IterationNum) {
2551 ConstantInt *CondVal =
2552 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2553
2554 // Couldn't symbolically evaluate.
2555 if (!CondVal) return UnknownValue;
2556
2557 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2558 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2559 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002560 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002561 }
2562
2563 // Compute the value of the PHI node for the next iteration.
2564 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2565 if (NextPHI == 0 || NextPHI == PHIVal)
2566 return UnknownValue; // Couldn't evaluate or not making progress...
2567 PHIVal = NextPHI;
2568 }
2569
2570 // Too many iterations were needed to evaluate.
2571 return UnknownValue;
2572}
2573
2574/// getSCEVAtScope - Compute the value of the specified expression within the
2575/// indicated loop (which may be null to indicate in no loop). If the
2576/// expression cannot be evaluated, return UnknownValue.
2577SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2578 // FIXME: this should be turned into a virtual method on SCEV!
2579
2580 if (isa<SCEVConstant>(V)) return V;
2581
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002582 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002583 // exit value from the loop without using SCEVs.
2584 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2585 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2586 const Loop *LI = this->LI[I->getParent()];
2587 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2588 if (PHINode *PN = dyn_cast<PHINode>(I))
2589 if (PN->getParent() == LI->getHeader()) {
2590 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002591 // to see if the loop that contains it has a known backedge-taken
2592 // count. If so, we may be able to force computation of the exit
2593 // value.
2594 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2595 if (SCEVConstant *BTCC =
2596 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002597 // Okay, we know how many times the containing loop executes. If
2598 // this is a constant evolving PHI node, get the final value at
2599 // the specified iteration number.
2600 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002601 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002603 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002604 }
2605 }
2606
2607 // Okay, this is an expression that we cannot symbolically evaluate
2608 // into a SCEV. Check to see if it's possible to symbolically evaluate
2609 // the arguments into constants, and if so, try to constant propagate the
2610 // result. This is particularly useful for computing loop exit values.
2611 if (CanConstantFold(I)) {
2612 std::vector<Constant*> Operands;
2613 Operands.reserve(I->getNumOperands());
2614 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2615 Value *Op = I->getOperand(i);
2616 if (Constant *C = dyn_cast<Constant>(Op)) {
2617 Operands.push_back(C);
2618 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002619 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002620 // non-integer and non-pointer, don't even try to analyze them
2621 // with scev techniques.
2622 if (!isa<IntegerType>(Op->getType()) &&
2623 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002624 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002625
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002626 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2627 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2628 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2629 Op->getType(),
2630 false));
2631 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2632 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2633 Operands.push_back(ConstantExpr::getIntegerCast(C,
2634 Op->getType(),
2635 false));
2636 else
2637 return V;
2638 } else {
2639 return V;
2640 }
2641 }
2642 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002643
2644 Constant *C;
2645 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2646 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2647 &Operands[0], Operands.size());
2648 else
2649 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2650 &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002651 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002652 }
2653 }
2654
2655 // This is some other type of SCEVUnknown, just return it.
2656 return V;
2657 }
2658
2659 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2660 // Avoid performing the look-up in the common case where the specified
2661 // expression has no loop-variant portions.
2662 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2663 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2664 if (OpAtScope != Comm->getOperand(i)) {
2665 if (OpAtScope == UnknownValue) return UnknownValue;
2666 // Okay, at least one of these operands is loop variant but might be
2667 // foldable. Build a new instance of the folded commutative expression.
2668 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2669 NewOps.push_back(OpAtScope);
2670
2671 for (++i; i != e; ++i) {
2672 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2673 if (OpAtScope == UnknownValue) return UnknownValue;
2674 NewOps.push_back(OpAtScope);
2675 }
2676 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002677 return SE.getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002678 if (isa<SCEVMulExpr>(Comm))
2679 return SE.getMulExpr(NewOps);
2680 if (isa<SCEVSMaxExpr>(Comm))
2681 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002682 if (isa<SCEVUMaxExpr>(Comm))
2683 return SE.getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002684 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002685 }
2686 }
2687 // If we got here, all operands are loop invariant.
2688 return Comm;
2689 }
2690
Nick Lewycky35b56022009-01-13 09:18:58 +00002691 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2692 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002693 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002694 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002695 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002696 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2697 return Div; // must be loop invariant
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002698 return SE.getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002699 }
2700
2701 // If this is a loop recurrence for a loop that does not contain L, then we
2702 // are dealing with the final value computed by the loop.
2703 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2704 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2705 // To evaluate this recurrence, we need to know how many times the AddRec
2706 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002707 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2708 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002709
Eli Friedman7489ec92008-08-04 23:49:06 +00002710 // Then, evaluate the AddRec.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002711 return AddRec->evaluateAtIteration(BackedgeTakenCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002712 }
2713 return UnknownValue;
2714 }
2715
2716 //assert(0 && "Unknown SCEV type!");
2717 return UnknownValue;
2718}
2719
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002720/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2721/// following equation:
2722///
2723/// A * X = B (mod N)
2724///
2725/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2726/// A and B isn't important.
2727///
2728/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2729static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2730 ScalarEvolution &SE) {
2731 uint32_t BW = A.getBitWidth();
2732 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2733 assert(A != 0 && "A must be non-zero.");
2734
2735 // 1. D = gcd(A, N)
2736 //
2737 // The gcd of A and N may have only one prime factor: 2. The number of
2738 // trailing zeros in A is its multiplicity
2739 uint32_t Mult2 = A.countTrailingZeros();
2740 // D = 2^Mult2
2741
2742 // 2. Check if B is divisible by D.
2743 //
2744 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2745 // is not less than multiplicity of this prime factor for D.
2746 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002747 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002748
2749 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2750 // modulo (N / D).
2751 //
2752 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2753 // bit width during computations.
2754 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2755 APInt Mod(BW + 1, 0);
2756 Mod.set(BW - Mult2); // Mod = N / D
2757 APInt I = AD.multiplicativeInverse(Mod);
2758
2759 // 4. Compute the minimum unsigned root of the equation:
2760 // I * (B / D) mod (N / D)
2761 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2762
2763 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2764 // bits.
2765 return SE.getConstant(Result.trunc(BW));
2766}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002767
2768/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2769/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2770/// might be the same) or two SCEVCouldNotCompute objects.
2771///
2772static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002773SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002774 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2775 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2776 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2777 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2778
2779 // We currently can only solve this if the coefficients are constants.
2780 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002781 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 return std::make_pair(CNC, CNC);
2783 }
2784
2785 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2786 const APInt &L = LC->getValue()->getValue();
2787 const APInt &M = MC->getValue()->getValue();
2788 const APInt &N = NC->getValue()->getValue();
2789 APInt Two(BitWidth, 2);
2790 APInt Four(BitWidth, 4);
2791
2792 {
2793 using namespace APIntOps;
2794 const APInt& C = L;
2795 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2796 // The B coefficient is M-N/2
2797 APInt B(M);
2798 B -= sdiv(N,Two);
2799
2800 // The A coefficient is N/2
2801 APInt A(N.sdiv(Two));
2802
2803 // Compute the B^2-4ac term.
2804 APInt SqrtTerm(B);
2805 SqrtTerm *= B;
2806 SqrtTerm -= Four * (A * C);
2807
2808 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2809 // integer value or else APInt::sqrt() will assert.
2810 APInt SqrtVal(SqrtTerm.sqrt());
2811
2812 // Compute the two solutions for the quadratic formula.
2813 // The divisions must be performed as signed divisions.
2814 APInt NegB(-B);
2815 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002816 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002817 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002818 return std::make_pair(CNC, CNC);
2819 }
2820
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002821 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2822 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2823
Dan Gohman89f85052007-10-22 18:31:58 +00002824 return std::make_pair(SE.getConstant(Solution1),
2825 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002826 } // end APIntOps namespace
2827}
2828
2829/// HowFarToZero - Return the number of times a backedge comparing the specified
2830/// value to zero will execute. If not computable, return UnknownValue
2831SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2832 // If the value is a constant
2833 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2834 // If the value is already zero, the branch will execute zero times.
2835 if (C->getValue()->isZero()) return C;
2836 return UnknownValue; // Otherwise it will loop infinitely.
2837 }
2838
2839 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2840 if (!AddRec || AddRec->getLoop() != L)
2841 return UnknownValue;
2842
2843 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002844 // If this is an affine expression, the execution count of this branch is
2845 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002846 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002847 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002848 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002849 // equivalent to:
2850 //
2851 // Step*N = -Start (mod 2^BW)
2852 //
2853 // where BW is the common bit width of Start and Step.
2854
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002855 // Get the initial value for the loop.
2856 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2857 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002859 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002860
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002861 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002862 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002864 // First, handle unitary steps.
2865 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2866 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2867 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2868 return Start; // N = Start (as unsigned)
2869
2870 // Then, try to solve the above equation provided that Start is constant.
2871 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2872 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2873 -StartC->getValue()->getValue(),SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002874 }
2875 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2876 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2877 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002878 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2880 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2881 if (R1) {
2882#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002883 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2884 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002885#endif
2886 // Pick the smallest positive root value.
2887 if (ConstantInt *CB =
2888 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2889 R1->getValue(), R2->getValue()))) {
2890 if (CB->getZExtValue() == false)
2891 std::swap(R1, R2); // R1 is the minimum root now.
2892
2893 // We can only use this value if the chrec ends up with an exact zero
2894 // value at this index. When solving for "X*X != 5", for example, we
2895 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002896 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohman7b560c42008-06-18 16:23:07 +00002897 if (Val->isZero())
2898 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002899 }
2900 }
2901 }
2902
2903 return UnknownValue;
2904}
2905
2906/// HowFarToNonZero - Return the number of times a backedge checking the
2907/// specified value for nonzero will execute. If not computable, return
2908/// UnknownValue
2909SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2910 // Loops that look like: while (X == 0) are very strange indeed. We don't
2911 // handle them yet except for the trivial case. This could be expanded in the
2912 // future as needed.
2913
2914 // If the value is a constant, check to see if it is known to be non-zero
2915 // already. If so, the backedge will execute zero times.
2916 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002917 if (!C->getValue()->isNullValue())
2918 return SE.getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002919 return UnknownValue; // Otherwise it will loop infinitely.
2920 }
2921
2922 // We could implement others, but I really doubt anyone writes loops like
2923 // this, and if they did, they would already be constant folded.
2924 return UnknownValue;
2925}
2926
Dan Gohman1cddf972008-09-15 22:18:04 +00002927/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2928/// (which may not be an immediate predecessor) which has exactly one
2929/// successor from which BB is reachable, or null if no such block is
2930/// found.
2931///
2932BasicBlock *
2933ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2934 // If the block has a unique predecessor, the predecessor must have
2935 // no other successors from which BB is reachable.
2936 if (BasicBlock *Pred = BB->getSinglePredecessor())
2937 return Pred;
2938
2939 // A loop's header is defined to be a block that dominates the loop.
2940 // If the loop has a preheader, it must be a block that has exactly
2941 // one successor that can reach BB. This is slightly more strict
2942 // than necessary, but works if critical edges are split.
2943 if (Loop *L = LI.getLoopFor(BB))
2944 return L->getLoopPreheader();
2945
2946 return 0;
2947}
2948
Dan Gohmancacd2012009-02-12 22:19:27 +00002949/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002950/// a conditional between LHS and RHS.
Dan Gohmancacd2012009-02-12 22:19:27 +00002951bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2952 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002953 SCEV *LHS, SCEV *RHS) {
2954 BasicBlock *Preheader = L->getLoopPreheader();
2955 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002956
Dan Gohmanab678fb2008-08-12 20:17:31 +00002957 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002958 // there are predecessors that can be found that have unique successors
2959 // leading to the original header.
2960 for (; Preheader;
2961 PreheaderDest = Preheader,
2962 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002963
2964 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002965 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002966 if (!LoopEntryPredicate ||
2967 LoopEntryPredicate->isUnconditional())
2968 continue;
2969
2970 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2971 if (!ICI) continue;
2972
2973 // Now that we found a conditional branch that dominates the loop, check to
2974 // see if it is the comparison we are looking for.
2975 Value *PreCondLHS = ICI->getOperand(0);
2976 Value *PreCondRHS = ICI->getOperand(1);
2977 ICmpInst::Predicate Cond;
2978 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2979 Cond = ICI->getPredicate();
2980 else
2981 Cond = ICI->getInversePredicate();
2982
Dan Gohmancacd2012009-02-12 22:19:27 +00002983 if (Cond == Pred)
2984 ; // An exact match.
2985 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2986 ; // The actual condition is beyond sufficient.
2987 else
2988 // Check a few special cases.
2989 switch (Cond) {
2990 case ICmpInst::ICMP_UGT:
2991 if (Pred == ICmpInst::ICMP_ULT) {
2992 std::swap(PreCondLHS, PreCondRHS);
2993 Cond = ICmpInst::ICMP_ULT;
2994 break;
2995 }
2996 continue;
2997 case ICmpInst::ICMP_SGT:
2998 if (Pred == ICmpInst::ICMP_SLT) {
2999 std::swap(PreCondLHS, PreCondRHS);
3000 Cond = ICmpInst::ICMP_SLT;
3001 break;
3002 }
3003 continue;
3004 case ICmpInst::ICMP_NE:
3005 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3006 // so check for this case by checking if the NE is comparing against
3007 // a minimum or maximum constant.
3008 if (!ICmpInst::isTrueWhenEqual(Pred))
3009 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3010 const APInt &A = CI->getValue();
3011 switch (Pred) {
3012 case ICmpInst::ICMP_SLT:
3013 if (A.isMaxSignedValue()) break;
3014 continue;
3015 case ICmpInst::ICMP_SGT:
3016 if (A.isMinSignedValue()) break;
3017 continue;
3018 case ICmpInst::ICMP_ULT:
3019 if (A.isMaxValue()) break;
3020 continue;
3021 case ICmpInst::ICMP_UGT:
3022 if (A.isMinValue()) break;
3023 continue;
3024 default:
3025 continue;
3026 }
3027 Cond = ICmpInst::ICMP_NE;
3028 // NE is symmetric but the original comparison may not be. Swap
3029 // the operands if necessary so that they match below.
3030 if (isa<SCEVConstant>(LHS))
3031 std::swap(PreCondLHS, PreCondRHS);
3032 break;
3033 }
3034 continue;
3035 default:
3036 // We weren't able to reconcile the condition.
3037 continue;
3038 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003039
3040 if (!PreCondLHS->getType()->isInteger()) continue;
3041
3042 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3043 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3044 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3045 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
3046 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
3047 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003048 }
3049
Dan Gohmanab678fb2008-08-12 20:17:31 +00003050 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003051}
3052
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003053/// HowManyLessThans - Return the number of times a backedge containing the
3054/// specified less-than comparison will execute. If not computable, return
3055/// UnknownValue.
3056SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky35b56022009-01-13 09:18:58 +00003057HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003058 // Only handle: "ADDREC < LoopInvariant".
3059 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3060
3061 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3062 if (!AddRec || AddRec->getLoop() != L)
3063 return UnknownValue;
3064
3065 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003066 // FORNOW: We only support unit strides.
3067 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
3068 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003069 return UnknownValue;
3070
Nick Lewycky35b56022009-01-13 09:18:58 +00003071 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3072 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3073 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003074 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003076 // First, we get the value of the LHS in the first iteration: n
3077 SCEVHandle Start = AddRec->getOperand(0);
3078
Dan Gohmancacd2012009-02-12 22:19:27 +00003079 if (isLoopGuardedByCond(L,
3080 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Nick Lewycky35b56022009-01-13 09:18:58 +00003081 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
3082 // Since we know that the condition is true in order to enter the loop,
3083 // we know that it will run exactly m-n times.
3084 return SE.getMinusSCEV(RHS, Start);
3085 } else {
3086 // Then, we get the value of the LHS in the first iteration in which the
3087 // above condition doesn't hold. This equals to max(m,n).
3088 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
3089 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003090
Nick Lewycky35b56022009-01-13 09:18:58 +00003091 // Finally, we subtract these two values to get the number of times the
3092 // backedge is executed: max(m,n)-n.
3093 return SE.getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00003094 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095 }
3096
3097 return UnknownValue;
3098}
3099
3100/// getNumIterationsInRange - Return the number of iterations of this loop that
3101/// produce values in the specified constant range. Another way of looking at
3102/// this is that it returns the first iteration number where the value is not in
3103/// the condition, thus computing the exit count. If the iteration count can't
3104/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003105SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3106 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003108 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109
3110 // If the start is a non-zero constant, shift the range to simplify things.
3111 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3112 if (!SC->getValue()->isZero()) {
3113 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003114 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3115 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003116 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3117 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003118 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003119 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003120 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121 }
3122
3123 // The only time we can solve this is when we have all constant indices.
3124 // Otherwise, we cannot determine the overflow conditions.
3125 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3126 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003127 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128
3129
3130 // Okay at this point we know that all elements of the chrec are constants and
3131 // that the start element is zero.
3132
3133 // First check to see if the range contains zero. If not, the first
3134 // iteration exits.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003135 unsigned BitWidth = SE.getTargetData().getTypeSizeInBits(getType());
3136 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003137 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138
3139 if (isAffine()) {
3140 // If this is an affine expression then we have this situation:
3141 // Solve {0,+,A} in Range === Ax in Range
3142
3143 // We know that zero is in the range. If A is positive then we know that
3144 // the upper value of the range must be the first possible exit value.
3145 // If A is negative then the lower of the range is the last possible loop
3146 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003147 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003148 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3149 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3150
3151 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003152 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003153 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3154
3155 // Evaluate at the exit value. If we really did fall out of the valid
3156 // range, then we computed our trip count, otherwise wrap around or other
3157 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003158 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003160 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161
3162 // Ensure that the previous value is in the range. This is a sanity check.
3163 assert(Range.contains(
3164 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003165 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003166 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003167 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 } else if (isQuadratic()) {
3169 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3170 // quadratic equation to solve it. To do this, we must frame our problem in
3171 // terms of figuring out when zero is crossed, instead of when
3172 // Range.getUpper() is crossed.
3173 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003174 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3175 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176
3177 // Next, solve the constructed addrec
3178 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003179 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003180 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3181 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3182 if (R1) {
3183 // Pick the smallest positive root value.
3184 if (ConstantInt *CB =
3185 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3186 R1->getValue(), R2->getValue()))) {
3187 if (CB->getZExtValue() == false)
3188 std::swap(R1, R2); // R1 is the minimum root now.
3189
3190 // Make sure the root is not off by one. The returned iteration should
3191 // not be in the range, but the previous one should be. When solving
3192 // for "X*X < 5", for example, we should not return a root of 2.
3193 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003194 R1->getValue(),
3195 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003196 if (Range.contains(R1Val->getValue())) {
3197 // The next iteration must be out of the range...
3198 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3199
Dan Gohman89f85052007-10-22 18:31:58 +00003200 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003201 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003202 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003203 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 }
3205
3206 // If R1 was not in the range, then it is a good return value. Make
3207 // sure that R1-1 WAS in the range though, just in case.
3208 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003209 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003210 if (Range.contains(R1Val->getValue()))
3211 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003212 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213 }
3214 }
3215 }
3216
Dan Gohman0ad08b02009-04-18 17:58:19 +00003217 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218}
3219
3220
3221
3222//===----------------------------------------------------------------------===//
3223// ScalarEvolution Class Implementation
3224//===----------------------------------------------------------------------===//
3225
3226bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00003227 Impl = new ScalarEvolutionsImpl(*this, F,
3228 getAnalysis<LoopInfo>(),
3229 getAnalysis<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003230 return false;
3231}
3232
3233void ScalarEvolution::releaseMemory() {
3234 delete (ScalarEvolutionsImpl*)Impl;
3235 Impl = 0;
3236}
3237
3238void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3239 AU.setPreservesAll();
3240 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003241 AU.addRequiredTransitive<TargetData>();
3242}
3243
3244const TargetData &ScalarEvolution::getTargetData() const {
3245 return ((ScalarEvolutionsImpl*)Impl)->getTargetData();
3246}
3247
Dan Gohman0ad08b02009-04-18 17:58:19 +00003248SCEVHandle ScalarEvolution::getCouldNotCompute() {
3249 return ((ScalarEvolutionsImpl*)Impl)->getCouldNotCompute();
3250}
3251
Dan Gohman01c2ee72009-04-16 03:18:22 +00003252SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
3253 return ((ScalarEvolutionsImpl*)Impl)->getIntegerSCEV(Val, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254}
3255
3256SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3257 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3258}
3259
3260/// hasSCEV - Return true if the SCEV for this value has already been
3261/// computed.
3262bool ScalarEvolution::hasSCEV(Value *V) const {
3263 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3264}
3265
3266
3267/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3268/// the specified value.
3269void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3270 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3271}
3272
Dan Gohman01c2ee72009-04-16 03:18:22 +00003273/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3274///
3275SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
3276 return ((ScalarEvolutionsImpl*)Impl)->getNegativeSCEV(V);
3277}
3278
3279/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3280///
3281SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
3282 return ((ScalarEvolutionsImpl*)Impl)->getNotSCEV(V);
3283}
3284
3285/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
3286///
3287SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
3288 const SCEVHandle &RHS) {
3289 return ((ScalarEvolutionsImpl*)Impl)->getMinusSCEV(LHS, RHS);
3290}
3291
3292/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
3293/// of the input value to the specified type. If the type must be
3294/// extended, it is zero extended.
3295SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
3296 const Type *Ty) {
3297 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrZeroExtend(V, Ty);
3298}
3299
3300/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
3301/// of the input value to the specified type. If the type must be
3302/// extended, it is sign extended.
3303SCEVHandle ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
3304 const Type *Ty) {
3305 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrSignExtend(V, Ty);
3306}
3307
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308
Dan Gohmancacd2012009-02-12 22:19:27 +00003309bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3310 ICmpInst::Predicate Pred,
3311 SCEV *LHS, SCEV *RHS) {
3312 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3313 LHS, RHS);
3314}
3315
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003316SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) const {
3317 return ((ScalarEvolutionsImpl*)Impl)->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003318}
3319
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003320bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) const {
3321 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003322}
3323
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003324void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3325 return ((ScalarEvolutionsImpl*)Impl)->forgetLoopBackedgeTakenCount(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003326}
3327
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003328SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3329 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3330}
3331
3332void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3333 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3334}
3335
Dan Gohman13058cc2009-04-21 00:47:46 +00003336static void PrintLoopInfo(raw_ostream &OS, const ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003337 const Loop *L) {
3338 // Print all inner loops first
3339 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3340 PrintLoopInfo(OS, SE, *I);
3341
Nick Lewyckye5da1912008-01-02 02:49:20 +00003342 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003343
Devang Patel02451fa2007-08-21 00:31:24 +00003344 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003345 L->getExitBlocks(ExitBlocks);
3346 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003347 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003348
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003349 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3350 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003351 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003352 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003353 }
3354
Nick Lewyckye5da1912008-01-02 02:49:20 +00003355 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356}
3357
Dan Gohman13058cc2009-04-21 00:47:46 +00003358void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003359 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3360 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3361
3362 OS << "Classifying expressions for: " << F.getName() << "\n";
3363 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3364 if (I->getType()->isInteger()) {
3365 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003366 OS << " --> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003367 SCEVHandle SV = getSCEV(&*I);
3368 SV->print(OS);
3369 OS << "\t\t";
3370
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003371 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3372 OS << "Exits: ";
3373 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3374 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3375 OS << "<<Unknown>>";
3376 } else {
3377 OS << *ExitValue;
3378 }
3379 }
3380
3381
3382 OS << "\n";
3383 }
3384
3385 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3386 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3387 PrintLoopInfo(OS, this, *I);
3388}
Dan Gohman13058cc2009-04-21 00:47:46 +00003389
3390void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3391 raw_os_ostream OS(o);
3392 print(OS, M);
3393}