blob: e429697b1cd84db74fcc532c4fdf0a3c6e574986 [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 Gohmanb98c1a32009-04-21 01:07:12 +0000573 unsigned W = SE.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 Gohmanb98c1a32009-04-21 01:07:12 +0000651 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000652 "This is not a truncating conversion!");
653
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000655 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 ConstantExpr::getTrunc(SC->getValue(), Ty));
657
658 // If the input value is a chrec scev made out of constants, truncate
659 // all of the constants.
660 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
661 std::vector<SCEVHandle> Operands;
662 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
663 // FIXME: This should allow truncation of other expression types!
664 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000665 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666 else
667 break;
668 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000669 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 }
671
672 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
673 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
674 return Result;
675}
676
Dan Gohman36d40922009-04-16 19:25:55 +0000677SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
678 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000679 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000680 "This is not an extending conversion!");
681
Dan Gohman01c2ee72009-04-16 03:18:22 +0000682 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000683 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000684 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
685 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
686 return getUnknown(C);
687 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688
689 // FIXME: If the input value is a chrec scev, and we can prove that the value
690 // did not overflow the old, smaller, value, we can zero extend all of the
691 // operands (often constants). This would allow analysis of something like
692 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
693
694 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
695 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
696 return Result;
697}
698
Dan Gohman89f85052007-10-22 18:31:58 +0000699SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000700 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000701 "This is not an extending conversion!");
702
Dan Gohman01c2ee72009-04-16 03:18:22 +0000703 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000704 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000705 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
706 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
707 return getUnknown(C);
708 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709
710 // FIXME: If the input value is a chrec scev, and we can prove that the value
711 // did not overflow the old, smaller, value, we can sign extend all of the
712 // operands (often constants). This would allow analysis of something like
713 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
714
715 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
716 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
717 return Result;
718}
719
720// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000721SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000722 assert(!Ops.empty() && "Cannot get empty add!");
723 if (Ops.size() == 1) return Ops[0];
724
725 // Sort by complexity, this groups all similar expression types together.
726 GroupByComplexity(Ops);
727
728 // If there are any constants, fold them together.
729 unsigned Idx = 0;
730 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
731 ++Idx;
732 assert(Idx < Ops.size());
733 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
734 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000735 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
736 RHSC->getValue()->getValue());
737 Ops[0] = getConstant(Fold);
738 Ops.erase(Ops.begin()+1); // Erase the folded element
739 if (Ops.size() == 1) return Ops[0];
740 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 }
742
743 // If we are left with a constant zero being added, strip it off.
744 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
745 Ops.erase(Ops.begin());
746 --Idx;
747 }
748 }
749
750 if (Ops.size() == 1) return Ops[0];
751
752 // Okay, check to see if the same value occurs in the operand list twice. If
753 // so, merge them together into an multiply expression. Since we sorted the
754 // list, these values are required to be adjacent.
755 const Type *Ty = Ops[0]->getType();
756 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
757 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
758 // Found a match, merge the two values into a multiply, and add any
759 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000760 SCEVHandle Two = getIntegerSCEV(2, Ty);
761 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762 if (Ops.size() == 2)
763 return Mul;
764 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
765 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000766 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 }
768
769 // Now we know the first non-constant operand. Skip past any cast SCEVs.
770 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
771 ++Idx;
772
773 // If there are add operands they would be next.
774 if (Idx < Ops.size()) {
775 bool DeletedAdd = false;
776 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
777 // If we have an add, expand the add operands onto the end of the operands
778 // list.
779 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
780 Ops.erase(Ops.begin()+Idx);
781 DeletedAdd = true;
782 }
783
784 // If we deleted at least one add, we added operands to the end of the list,
785 // and they are not necessarily sorted. Recurse to resort and resimplify
786 // any operands we just aquired.
787 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000788 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789 }
790
791 // Skip over the add expression until we get to a multiply.
792 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
793 ++Idx;
794
795 // If we are adding something to a multiply expression, make sure the
796 // something is not already an operand of the multiply. If so, merge it into
797 // the multiply.
798 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
799 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
800 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
801 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
802 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
803 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
804 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
805 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
806 if (Mul->getNumOperands() != 2) {
807 // If the multiply has more than two operands, we must get the
808 // Y*Z term.
809 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
810 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000811 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 }
Dan Gohman89f85052007-10-22 18:31:58 +0000813 SCEVHandle One = getIntegerSCEV(1, Ty);
814 SCEVHandle AddOne = getAddExpr(InnerMul, One);
815 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 if (Ops.size() == 2) return OuterMul;
817 if (AddOp < Idx) {
818 Ops.erase(Ops.begin()+AddOp);
819 Ops.erase(Ops.begin()+Idx-1);
820 } else {
821 Ops.erase(Ops.begin()+Idx);
822 Ops.erase(Ops.begin()+AddOp-1);
823 }
824 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000825 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826 }
827
828 // Check this multiply against other multiplies being added together.
829 for (unsigned OtherMulIdx = Idx+1;
830 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
831 ++OtherMulIdx) {
832 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
833 // If MulOp occurs in OtherMul, we can fold the two multiplies
834 // together.
835 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
836 OMulOp != e; ++OMulOp)
837 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
838 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
839 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
840 if (Mul->getNumOperands() != 2) {
841 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
842 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000843 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 }
845 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
846 if (OtherMul->getNumOperands() != 2) {
847 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
848 OtherMul->op_end());
849 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000850 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 }
Dan Gohman89f85052007-10-22 18:31:58 +0000852 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
853 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 if (Ops.size() == 2) return OuterMul;
855 Ops.erase(Ops.begin()+Idx);
856 Ops.erase(Ops.begin()+OtherMulIdx-1);
857 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000858 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859 }
860 }
861 }
862 }
863
864 // If there are any add recurrences in the operands list, see if any other
865 // added values are loop invariant. If so, we can fold them into the
866 // recurrence.
867 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
868 ++Idx;
869
870 // Scan over all recurrences, trying to fold loop invariants into them.
871 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
872 // Scan all of the other operands to this add and add them to the vector if
873 // they are loop invariant w.r.t. the recurrence.
874 std::vector<SCEVHandle> LIOps;
875 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
876 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
877 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
878 LIOps.push_back(Ops[i]);
879 Ops.erase(Ops.begin()+i);
880 --i; --e;
881 }
882
883 // If we found some loop invariants, fold them into the recurrence.
884 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000885 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000886 LIOps.push_back(AddRec->getStart());
887
888 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000889 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890
Dan Gohman89f85052007-10-22 18:31:58 +0000891 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 // If all of the other operands were loop invariant, we are done.
893 if (Ops.size() == 1) return NewRec;
894
895 // Otherwise, add the folded AddRec by the non-liv parts.
896 for (unsigned i = 0;; ++i)
897 if (Ops[i] == AddRec) {
898 Ops[i] = NewRec;
899 break;
900 }
Dan Gohman89f85052007-10-22 18:31:58 +0000901 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 }
903
904 // Okay, if there weren't any loop invariants to be folded, check to see if
905 // there are multiple AddRec's with the same loop induction variable being
906 // added together. If so, we can fold them.
907 for (unsigned OtherIdx = Idx+1;
908 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
909 if (OtherIdx != Idx) {
910 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
911 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
912 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
913 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
914 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
915 if (i >= NewOps.size()) {
916 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
917 OtherAddRec->op_end());
918 break;
919 }
Dan Gohman89f85052007-10-22 18:31:58 +0000920 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 }
Dan Gohman89f85052007-10-22 18:31:58 +0000922 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923
924 if (Ops.size() == 2) return NewAddRec;
925
926 Ops.erase(Ops.begin()+Idx);
927 Ops.erase(Ops.begin()+OtherIdx-1);
928 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000929 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 }
931 }
932
933 // Otherwise couldn't fold anything into this recurrence. Move onto the
934 // next one.
935 }
936
937 // Okay, it looks like we really DO need an add expr. Check to see if we
938 // already have one, otherwise create a new one.
939 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
940 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
941 SCEVOps)];
942 if (Result == 0) Result = new SCEVAddExpr(Ops);
943 return Result;
944}
945
946
Dan Gohman89f85052007-10-22 18:31:58 +0000947SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 assert(!Ops.empty() && "Cannot get empty mul!");
949
950 // Sort by complexity, this groups all similar expression types together.
951 GroupByComplexity(Ops);
952
953 // If there are any constants, fold them together.
954 unsigned Idx = 0;
955 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
956
957 // C1*(C2+V) -> C1*C2 + C1*V
958 if (Ops.size() == 2)
959 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
960 if (Add->getNumOperands() == 2 &&
961 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000962 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
963 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964
965
966 ++Idx;
967 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
968 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000969 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
970 RHSC->getValue()->getValue());
971 Ops[0] = getConstant(Fold);
972 Ops.erase(Ops.begin()+1); // Erase the folded element
973 if (Ops.size() == 1) return Ops[0];
974 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975 }
976
977 // If we are left with a constant one being multiplied, strip it off.
978 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
979 Ops.erase(Ops.begin());
980 --Idx;
981 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
982 // If we have a multiply of zero, it will always be zero.
983 return Ops[0];
984 }
985 }
986
987 // Skip over the add expression until we get to a multiply.
988 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
989 ++Idx;
990
991 if (Ops.size() == 1)
992 return Ops[0];
993
994 // If there are mul operands inline them all into this expression.
995 if (Idx < Ops.size()) {
996 bool DeletedMul = false;
997 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
998 // If we have an mul, expand the mul operands onto the end of the operands
999 // list.
1000 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1001 Ops.erase(Ops.begin()+Idx);
1002 DeletedMul = true;
1003 }
1004
1005 // If we deleted at least one mul, we added operands to the end of the list,
1006 // and they are not necessarily sorted. Recurse to resort and resimplify
1007 // any operands we just aquired.
1008 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001009 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 }
1011
1012 // If there are any add recurrences in the operands list, see if any other
1013 // added values are loop invariant. If so, we can fold them into the
1014 // recurrence.
1015 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1016 ++Idx;
1017
1018 // Scan over all recurrences, trying to fold loop invariants into them.
1019 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1020 // Scan all of the other operands to this mul and add them to the vector if
1021 // they are loop invariant w.r.t. the recurrence.
1022 std::vector<SCEVHandle> LIOps;
1023 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1024 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1025 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1026 LIOps.push_back(Ops[i]);
1027 Ops.erase(Ops.begin()+i);
1028 --i; --e;
1029 }
1030
1031 // If we found some loop invariants, fold them into the recurrence.
1032 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001033 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 std::vector<SCEVHandle> NewOps;
1035 NewOps.reserve(AddRec->getNumOperands());
1036 if (LIOps.size() == 1) {
1037 SCEV *Scale = LIOps[0];
1038 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001039 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 } else {
1041 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1042 std::vector<SCEVHandle> MulOps(LIOps);
1043 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001044 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 }
1046 }
1047
Dan Gohman89f85052007-10-22 18:31:58 +00001048 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049
1050 // If all of the other operands were loop invariant, we are done.
1051 if (Ops.size() == 1) return NewRec;
1052
1053 // Otherwise, multiply the folded AddRec by the non-liv parts.
1054 for (unsigned i = 0;; ++i)
1055 if (Ops[i] == AddRec) {
1056 Ops[i] = NewRec;
1057 break;
1058 }
Dan Gohman89f85052007-10-22 18:31:58 +00001059 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060 }
1061
1062 // Okay, if there weren't any loop invariants to be folded, check to see if
1063 // there are multiple AddRec's with the same loop induction variable being
1064 // multiplied together. If so, we can fold them.
1065 for (unsigned OtherIdx = Idx+1;
1066 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1067 if (OtherIdx != Idx) {
1068 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1069 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1070 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1071 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001072 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001074 SCEVHandle B = F->getStepRecurrence(*this);
1075 SCEVHandle D = G->getStepRecurrence(*this);
1076 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1077 getMulExpr(G, B),
1078 getMulExpr(B, D));
1079 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1080 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 if (Ops.size() == 2) return NewAddRec;
1082
1083 Ops.erase(Ops.begin()+Idx);
1084 Ops.erase(Ops.begin()+OtherIdx-1);
1085 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001086 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 }
1088 }
1089
1090 // Otherwise couldn't fold anything into this recurrence. Move onto the
1091 // next one.
1092 }
1093
1094 // Okay, it looks like we really DO need an mul expr. Check to see if we
1095 // already have one, otherwise create a new one.
1096 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1097 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1098 SCEVOps)];
1099 if (Result == 0)
1100 Result = new SCEVMulExpr(Ops);
1101 return Result;
1102}
1103
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001104SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1106 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001107 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108
1109 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1110 Constant *LHSCV = LHSC->getValue();
1111 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001112 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 }
1114 }
1115
Nick Lewycky35b56022009-01-13 09:18:58 +00001116 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1117
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001118 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1119 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 return Result;
1121}
1122
1123
1124/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1125/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001126SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 const SCEVHandle &Step, const Loop *L) {
1128 std::vector<SCEVHandle> Operands;
1129 Operands.push_back(Start);
1130 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1131 if (StepChrec->getLoop() == L) {
1132 Operands.insert(Operands.end(), StepChrec->op_begin(),
1133 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001134 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 }
1136
1137 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001138 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139}
1140
1141/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1142/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001143SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 const Loop *L) {
1145 if (Operands.size() == 1) return Operands[0];
1146
Dan Gohman7b560c42008-06-18 16:23:07 +00001147 if (Operands.back()->isZero()) {
1148 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001149 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001150 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151
Dan Gohman42936882008-08-08 18:33:12 +00001152 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1153 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1154 const Loop* NestedLoop = NestedAR->getLoop();
1155 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1156 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1157 NestedAR->op_end());
1158 SCEVHandle NestedARHandle(NestedAR);
1159 Operands[0] = NestedAR->getStart();
1160 NestedOperands[0] = getAddRecExpr(Operands, L);
1161 return getAddRecExpr(NestedOperands, NestedLoop);
1162 }
1163 }
1164
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 SCEVAddRecExpr *&Result =
1166 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1167 Operands.end()))];
1168 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1169 return Result;
1170}
1171
Nick Lewycky711640a2007-11-25 22:41:31 +00001172SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1173 const SCEVHandle &RHS) {
1174 std::vector<SCEVHandle> Ops;
1175 Ops.push_back(LHS);
1176 Ops.push_back(RHS);
1177 return getSMaxExpr(Ops);
1178}
1179
1180SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1181 assert(!Ops.empty() && "Cannot get empty smax!");
1182 if (Ops.size() == 1) return Ops[0];
1183
1184 // Sort by complexity, this groups all similar expression types together.
1185 GroupByComplexity(Ops);
1186
1187 // If there are any constants, fold them together.
1188 unsigned Idx = 0;
1189 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1190 ++Idx;
1191 assert(Idx < Ops.size());
1192 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1193 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001194 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001195 APIntOps::smax(LHSC->getValue()->getValue(),
1196 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001197 Ops[0] = getConstant(Fold);
1198 Ops.erase(Ops.begin()+1); // Erase the folded element
1199 if (Ops.size() == 1) return Ops[0];
1200 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001201 }
1202
1203 // If we are left with a constant -inf, strip it off.
1204 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1205 Ops.erase(Ops.begin());
1206 --Idx;
1207 }
1208 }
1209
1210 if (Ops.size() == 1) return Ops[0];
1211
1212 // Find the first SMax
1213 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1214 ++Idx;
1215
1216 // Check to see if one of the operands is an SMax. If so, expand its operands
1217 // onto our operand list, and recurse to simplify.
1218 if (Idx < Ops.size()) {
1219 bool DeletedSMax = false;
1220 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1221 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1222 Ops.erase(Ops.begin()+Idx);
1223 DeletedSMax = true;
1224 }
1225
1226 if (DeletedSMax)
1227 return getSMaxExpr(Ops);
1228 }
1229
1230 // Okay, check to see if the same value occurs in the operand list twice. If
1231 // so, delete one. Since we sorted the list, these values are required to
1232 // be adjacent.
1233 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1234 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1235 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1236 --i; --e;
1237 }
1238
1239 if (Ops.size() == 1) return Ops[0];
1240
1241 assert(!Ops.empty() && "Reduced smax down to nothing!");
1242
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001243 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001244 // already have one, otherwise create a new one.
1245 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1246 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1247 SCEVOps)];
1248 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1249 return Result;
1250}
1251
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001252SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1253 const SCEVHandle &RHS) {
1254 std::vector<SCEVHandle> Ops;
1255 Ops.push_back(LHS);
1256 Ops.push_back(RHS);
1257 return getUMaxExpr(Ops);
1258}
1259
1260SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1261 assert(!Ops.empty() && "Cannot get empty umax!");
1262 if (Ops.size() == 1) return Ops[0];
1263
1264 // Sort by complexity, this groups all similar expression types together.
1265 GroupByComplexity(Ops);
1266
1267 // If there are any constants, fold them together.
1268 unsigned Idx = 0;
1269 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1270 ++Idx;
1271 assert(Idx < Ops.size());
1272 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1273 // We found two constants, fold them together!
1274 ConstantInt *Fold = ConstantInt::get(
1275 APIntOps::umax(LHSC->getValue()->getValue(),
1276 RHSC->getValue()->getValue()));
1277 Ops[0] = getConstant(Fold);
1278 Ops.erase(Ops.begin()+1); // Erase the folded element
1279 if (Ops.size() == 1) return Ops[0];
1280 LHSC = cast<SCEVConstant>(Ops[0]);
1281 }
1282
1283 // If we are left with a constant zero, strip it off.
1284 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1285 Ops.erase(Ops.begin());
1286 --Idx;
1287 }
1288 }
1289
1290 if (Ops.size() == 1) return Ops[0];
1291
1292 // Find the first UMax
1293 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1294 ++Idx;
1295
1296 // Check to see if one of the operands is a UMax. If so, expand its operands
1297 // onto our operand list, and recurse to simplify.
1298 if (Idx < Ops.size()) {
1299 bool DeletedUMax = false;
1300 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1301 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1302 Ops.erase(Ops.begin()+Idx);
1303 DeletedUMax = true;
1304 }
1305
1306 if (DeletedUMax)
1307 return getUMaxExpr(Ops);
1308 }
1309
1310 // Okay, check to see if the same value occurs in the operand list twice. If
1311 // so, delete one. Since we sorted the list, these values are required to
1312 // be adjacent.
1313 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1314 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1315 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1316 --i; --e;
1317 }
1318
1319 if (Ops.size() == 1) return Ops[0];
1320
1321 assert(!Ops.empty() && "Reduced umax down to nothing!");
1322
1323 // Okay, it looks like we really DO need a umax expr. Check to see if we
1324 // already have one, otherwise create a new one.
1325 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1326 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1327 SCEVOps)];
1328 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1329 return Result;
1330}
1331
Dan Gohman89f85052007-10-22 18:31:58 +00001332SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001334 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001335 if (isa<ConstantPointerNull>(V))
1336 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1338 if (Result == 0) Result = new SCEVUnknown(V);
1339 return Result;
1340}
1341
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342//===----------------------------------------------------------------------===//
1343// ScalarEvolutionsImpl Definition and Implementation
1344//===----------------------------------------------------------------------===//
1345//
1346/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1347/// evolution code.
1348///
1349namespace {
1350 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001351 /// SE - A reference to the public ScalarEvolution object.
1352 ScalarEvolution &SE;
1353
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354 /// F - The function we are analyzing.
1355 ///
1356 Function &F;
1357
1358 /// LI - The loop information for the function we are currently analyzing.
1359 ///
1360 LoopInfo &LI;
1361
Dan Gohman01c2ee72009-04-16 03:18:22 +00001362 /// TD - The target data information for the target we are targetting.
1363 ///
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001364 TargetData *TD;
Dan Gohman01c2ee72009-04-16 03:18:22 +00001365
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001366 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1367 /// things.
1368 SCEVHandle UnknownValue;
1369
1370 /// Scalars - This is a cache of the scalars we have analyzed so far.
1371 ///
1372 std::map<Value*, SCEVHandle> Scalars;
1373
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001374 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
1375 /// this function as they are computed.
1376 std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001377
1378 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1379 /// the PHI instructions that we attempt to compute constant evolutions for.
1380 /// This allows us to avoid potentially expensive recomputation of these
1381 /// properties. An instruction maps to null if we are unable to compute its
1382 /// exit value.
1383 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1384
1385 public:
Dan Gohman01c2ee72009-04-16 03:18:22 +00001386 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li,
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001387 TargetData *td)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001388 : SE(se), F(f), LI(li), TD(td), UnknownValue(new SCEVCouldNotCompute()) {}
1389
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001390 /// isSCEVable - Test if values of the given type are analyzable within
1391 /// the SCEV framework. This primarily includes integer types, and it
1392 /// can optionally include pointer types if the ScalarEvolution class
1393 /// has access to target-specific information.
1394 bool isSCEVable(const Type *Ty) const;
1395
1396 /// getTypeSizeInBits - Return the size in bits of the specified type,
1397 /// for which isSCEVable must return true.
1398 uint64_t getTypeSizeInBits(const Type *Ty) const;
1399
1400 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1401 /// the given type and which represents how SCEV will treat the given
1402 /// type, for which isSCEVable must return true. For pointer types,
1403 /// this is the pointer-sized integer type.
1404 const Type *getEffectiveSCEVType(const Type *Ty) const;
1405
Dan Gohman0ad08b02009-04-18 17:58:19 +00001406 SCEVHandle getCouldNotCompute();
1407
Dan Gohman01c2ee72009-04-16 03:18:22 +00001408 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1409 /// specified signed integer value and return a SCEV for the constant.
1410 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
1411
1412 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1413 ///
1414 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
1415
1416 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1417 ///
1418 SCEVHandle getNotSCEV(const SCEVHandle &V);
1419
1420 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1421 ///
1422 SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS);
1423
1424 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
1425 /// of the input value to the specified type. If the type must be extended,
1426 /// it is zero extended.
1427 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
1428
1429 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
1430 /// of the input value to the specified type. If the type must be extended,
1431 /// it is sign extended.
1432 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433
1434 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1435 /// expression and create a new one.
1436 SCEVHandle getSCEV(Value *V);
1437
1438 /// hasSCEV - Return true if the SCEV for this value has already been
1439 /// computed.
1440 bool hasSCEV(Value *V) const {
1441 return Scalars.count(V);
1442 }
1443
1444 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1445 /// the specified value.
1446 void setSCEV(Value *V, const SCEVHandle &H) {
1447 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1448 assert(isNew && "This entry already existed!");
Devang Patelfc736502008-11-11 19:17:41 +00001449 isNew = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 }
1451
1452
1453 /// getSCEVAtScope - Compute the value of the specified expression within
1454 /// the indicated loop (which may be null to indicate in no loop). If the
1455 /// expression cannot be evaluated, return UnknownValue itself.
1456 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1457
1458
Dan Gohmancacd2012009-02-12 22:19:27 +00001459 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1460 /// a conditional between LHS and RHS.
1461 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1462 SCEV *LHS, SCEV *RHS);
1463
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001464 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
1465 /// has an analyzable loop-invariant backedge-taken count.
1466 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001468 /// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001469 /// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001470 /// ScalarEvolution's ability to compute a trip count, or if the loop
1471 /// is deleted.
1472 void forgetLoopBackedgeTakenCount(const Loop *L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001473
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001474 /// getBackedgeTakenCount - If the specified loop has a predictable
1475 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1476 /// object. The backedge-taken count is the number of times the loop header
1477 /// will be branched to from within the loop. This is one less than the
1478 /// trip count of the loop, since it doesn't count the first iteration,
1479 /// when the header is branched to from outside the loop.
1480 ///
1481 /// Note that it is not valid to call this method on a loop without a
1482 /// loop-invariant backedge-taken count (see
1483 /// hasLoopInvariantBackedgeTakenCount).
1484 ///
1485 SCEVHandle getBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001486
1487 /// deleteValueFromRecords - This method should be called by the
1488 /// client before it removes a value from the program, to make sure
1489 /// that no dangling references are left around.
1490 void deleteValueFromRecords(Value *V);
1491
1492 private:
1493 /// createSCEV - We know that there is no SCEV for the specified value.
1494 /// Analyze the expression.
1495 SCEVHandle createSCEV(Value *V);
1496
1497 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1498 /// SCEVs.
1499 SCEVHandle createNodeForPHI(PHINode *PN);
1500
1501 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1502 /// for the specified instruction and replaces any references to the
1503 /// symbolic value SymName with the specified value. This is used during
1504 /// PHI resolution.
1505 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1506 const SCEVHandle &SymName,
1507 const SCEVHandle &NewVal);
1508
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001509 /// ComputeBackedgeTakenCount - Compute the number of times the specified
1510 /// loop will iterate.
1511 SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001513 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
1514 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
1515 SCEVHandle
1516 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
1517 Constant *RHS,
1518 const Loop *L,
1519 ICmpInst::Predicate p);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001521 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
1522 /// a constant number of times (the condition evolves only from constants),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523 /// try to evaluate a few iterations of the loop until we get the exit
1524 /// condition gets a value of ExitWhen (true or false). If we cannot
1525 /// evaluate the trip count of the loop, return UnknownValue.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001526 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
1527 bool ExitWhen);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528
1529 /// HowFarToZero - Return the number of times a backedge comparing the
1530 /// specified value to zero will execute. If not computable, return
1531 /// UnknownValue.
1532 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1533
1534 /// HowFarToNonZero - Return the number of times a backedge checking the
1535 /// specified value for nonzero will execute. If not computable, return
1536 /// UnknownValue.
1537 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1538
1539 /// HowManyLessThans - Return the number of times a backedge containing the
1540 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001541 /// UnknownValue. isSigned specifies whether the less-than is signed.
1542 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewycky35b56022009-01-13 09:18:58 +00001543 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001544
Dan Gohman1cddf972008-09-15 22:18:04 +00001545 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1546 /// (which may not be an immediate predecessor) which has exactly one
1547 /// successor from which BB is reachable, or null if no such block is
1548 /// found.
1549 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1550
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1552 /// in the header of its containing loop, we know the loop executes a
1553 /// constant number of times, and the PHI node is just a recurrence
1554 /// involving constants, fold it.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001555 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556 const Loop *L);
1557 };
1558}
1559
1560//===----------------------------------------------------------------------===//
1561// Basic SCEV Analysis and PHI Idiom Recognition Code
1562//
1563
1564/// deleteValueFromRecords - This method should be called by the
1565/// client before it removes an instruction from the program, to make sure
1566/// that no dangling references are left around.
1567void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1568 SmallVector<Value *, 16> Worklist;
1569
1570 if (Scalars.erase(V)) {
1571 if (PHINode *PN = dyn_cast<PHINode>(V))
1572 ConstantEvolutionLoopExitValue.erase(PN);
1573 Worklist.push_back(V);
1574 }
1575
1576 while (!Worklist.empty()) {
1577 Value *VV = Worklist.back();
1578 Worklist.pop_back();
1579
1580 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1581 UI != UE; ++UI) {
1582 Instruction *Inst = cast<Instruction>(*UI);
1583 if (Scalars.erase(Inst)) {
1584 if (PHINode *PN = dyn_cast<PHINode>(VV))
1585 ConstantEvolutionLoopExitValue.erase(PN);
1586 Worklist.push_back(Inst);
1587 }
1588 }
1589 }
1590}
1591
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001592/// isSCEVable - Test if values of the given type are analyzable within
1593/// the SCEV framework. This primarily includes integer types, and it
1594/// can optionally include pointer types if the ScalarEvolution class
1595/// has access to target-specific information.
1596bool ScalarEvolutionsImpl::isSCEVable(const Type *Ty) const {
1597 // Integers are always SCEVable.
1598 if (Ty->isInteger())
1599 return true;
1600
1601 // Pointers are SCEVable if TargetData information is available
1602 // to provide pointer size information.
1603 if (isa<PointerType>(Ty))
1604 return TD != NULL;
1605
1606 // Otherwise it's not SCEVable.
1607 return false;
1608}
1609
1610/// getTypeSizeInBits - Return the size in bits of the specified type,
1611/// for which isSCEVable must return true.
1612uint64_t ScalarEvolutionsImpl::getTypeSizeInBits(const Type *Ty) const {
1613 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1614
1615 // If we have a TargetData, use it!
1616 if (TD)
1617 return TD->getTypeSizeInBits(Ty);
1618
1619 // Otherwise, we support only integer types.
1620 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1621 return Ty->getPrimitiveSizeInBits();
1622}
1623
1624/// getEffectiveSCEVType - Return a type with the same bitwidth as
1625/// the given type and which represents how SCEV will treat the given
1626/// type, for which isSCEVable must return true. For pointer types,
1627/// this is the pointer-sized integer type.
1628const Type *ScalarEvolutionsImpl::getEffectiveSCEVType(const Type *Ty) const {
1629 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1630
1631 if (Ty->isInteger())
1632 return Ty;
1633
1634 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1635 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001636}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637
Dan Gohman0ad08b02009-04-18 17:58:19 +00001638SCEVHandle ScalarEvolutionsImpl::getCouldNotCompute() {
1639 return UnknownValue;
1640}
1641
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1643/// expression and create a new one.
1644SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001645 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646
1647 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1648 if (I != Scalars.end()) return I->second;
1649 SCEVHandle S = createSCEV(V);
1650 Scalars.insert(std::make_pair(V, S));
1651 return S;
1652}
1653
Dan Gohman01c2ee72009-04-16 03:18:22 +00001654/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1655/// specified signed integer value and return a SCEV for the constant.
1656SCEVHandle ScalarEvolutionsImpl::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001657 Ty = SE.getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001658 Constant *C;
1659 if (Val == 0)
1660 C = Constant::getNullValue(Ty);
1661 else if (Ty->isFloatingPoint())
1662 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1663 APFloat::IEEEdouble, Val));
1664 else
1665 C = ConstantInt::get(Ty, Val);
1666 return SE.getUnknown(C);
1667}
1668
1669/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1670///
1671SCEVHandle ScalarEvolutionsImpl::getNegativeSCEV(const SCEVHandle &V) {
1672 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1673 return SE.getUnknown(ConstantExpr::getNeg(VC->getValue()));
1674
1675 const Type *Ty = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001676 Ty = SE.getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001677 return SE.getMulExpr(V, SE.getConstant(ConstantInt::getAllOnesValue(Ty)));
1678}
1679
1680/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1681SCEVHandle ScalarEvolutionsImpl::getNotSCEV(const SCEVHandle &V) {
1682 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1683 return SE.getUnknown(ConstantExpr::getNot(VC->getValue()));
1684
1685 const Type *Ty = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001686 Ty = SE.getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001687 SCEVHandle AllOnes = SE.getConstant(ConstantInt::getAllOnesValue(Ty));
1688 return getMinusSCEV(AllOnes, V);
1689}
1690
1691/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1692///
1693SCEVHandle ScalarEvolutionsImpl::getMinusSCEV(const SCEVHandle &LHS,
1694 const SCEVHandle &RHS) {
1695 // X - Y --> X + -Y
1696 return SE.getAddExpr(LHS, SE.getNegativeSCEV(RHS));
1697}
1698
1699/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1700/// input value to the specified type. If the type must be extended, it is zero
1701/// extended.
1702SCEVHandle
1703ScalarEvolutionsImpl::getTruncateOrZeroExtend(const SCEVHandle &V,
1704 const Type *Ty) {
1705 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001706 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1707 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001708 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001709 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001710 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001711 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001712 return SE.getTruncateExpr(V, Ty);
1713 return SE.getZeroExtendExpr(V, Ty);
1714}
1715
1716/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1717/// input value to the specified type. If the type must be extended, it is sign
1718/// extended.
1719SCEVHandle
1720ScalarEvolutionsImpl::getTruncateOrSignExtend(const SCEVHandle &V,
1721 const Type *Ty) {
1722 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001723 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1724 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001725 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001726 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001727 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001728 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001729 return SE.getTruncateExpr(V, Ty);
1730 return SE.getSignExtendExpr(V, Ty);
1731}
1732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1734/// the specified instruction and replaces any references to the symbolic value
1735/// SymName with the specified value. This is used during PHI resolution.
1736void ScalarEvolutionsImpl::
1737ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1738 const SCEVHandle &NewVal) {
1739 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1740 if (SI == Scalars.end()) return;
1741
1742 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001743 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 if (NV == SI->second) return; // No change.
1745
1746 SI->second = NV; // Update the scalars map!
1747
1748 // Any instruction values that use this instruction might also need to be
1749 // updated!
1750 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1751 UI != E; ++UI)
1752 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1753}
1754
1755/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1756/// a loop header, making it a potential recurrence, or it doesn't.
1757///
1758SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1759 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1760 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1761 if (L->getHeader() == PN->getParent()) {
1762 // If it lives in the loop header, it has two incoming values, one
1763 // from outside the loop, and one from inside.
1764 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1765 unsigned BackEdge = IncomingEdge^1;
1766
1767 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001768 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769 assert(Scalars.find(PN) == Scalars.end() &&
1770 "PHI node already processed?");
1771 Scalars.insert(std::make_pair(PN, SymbolicName));
1772
1773 // Using this symbolic name for the PHI, analyze the value coming around
1774 // the back-edge.
1775 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1776
1777 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1778 // has a special value for the first iteration of the loop.
1779
1780 // If the value coming around the backedge is an add with the symbolic
1781 // value we just inserted, then we found a simple induction variable!
1782 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1783 // If there is a single occurrence of the symbolic value, replace it
1784 // with a recurrence.
1785 unsigned FoundIndex = Add->getNumOperands();
1786 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1787 if (Add->getOperand(i) == SymbolicName)
1788 if (FoundIndex == e) {
1789 FoundIndex = i;
1790 break;
1791 }
1792
1793 if (FoundIndex != Add->getNumOperands()) {
1794 // Create an add with everything but the specified operand.
1795 std::vector<SCEVHandle> Ops;
1796 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1797 if (i != FoundIndex)
1798 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001799 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800
1801 // This is not a valid addrec if the step amount is varying each
1802 // loop iteration, but is not itself an addrec in this loop.
1803 if (Accum->isLoopInvariant(L) ||
1804 (isa<SCEVAddRecExpr>(Accum) &&
1805 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1806 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001807 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001808
1809 // Okay, for the entire analysis of this edge we assumed the PHI
1810 // to be symbolic. We now need to go back and update all of the
1811 // entries for the scalars that use the PHI (except for the PHI
1812 // itself) to use the new analyzed value instead of the "symbolic"
1813 // value.
1814 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1815 return PHISCEV;
1816 }
1817 }
1818 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1819 // Otherwise, this could be a loop like this:
1820 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1821 // In this case, j = {1,+,1} and BEValue is j.
1822 // Because the other in-value of i (0) fits the evolution of BEValue
1823 // i really is an addrec evolution.
1824 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1825 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1826
1827 // If StartVal = j.start - j.stride, we can use StartVal as the
1828 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001829 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1830 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001832 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001833
1834 // Okay, for the entire analysis of this edge we assumed the PHI
1835 // to be symbolic. We now need to go back and update all of the
1836 // entries for the scalars that use the PHI (except for the PHI
1837 // itself) to use the new analyzed value instead of the "symbolic"
1838 // value.
1839 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1840 return PHISCEV;
1841 }
1842 }
1843 }
1844
1845 return SymbolicName;
1846 }
1847
1848 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001849 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001850}
1851
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001852/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1853/// guaranteed to end in (at every loop iteration). It is, at the same time,
1854/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1855/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001856static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001857 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001858 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001859
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001860 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001861 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1862 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001863
1864 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001865 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1866 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1867 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001868 }
1869
1870 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001871 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1872 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1873 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001874 }
1875
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001876 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001877 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001878 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001879 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001880 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001881 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 }
1883
1884 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001885 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001886 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1887 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001888 for (unsigned i = 1, e = M->getNumOperands();
1889 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001890 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001891 BitWidth);
1892 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001894
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001895 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001896 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001897 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001898 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001899 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001900 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001902
Nick Lewycky711640a2007-11-25 22:41:31 +00001903 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1904 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001905 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001906 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001907 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001908 return MinOpRes;
1909 }
1910
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001911 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1912 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001913 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001914 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001915 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001916 return MinOpRes;
1917 }
1918
Nick Lewycky35b56022009-01-13 09:18:58 +00001919 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001920 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001921}
1922
1923/// createSCEV - We know that there is no SCEV for the specified value.
1924/// Analyze the expression.
1925///
1926SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001927 if (!isSCEVable(V->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00001928 return SE.getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001929
Dan Gohman3996f472008-06-22 19:56:46 +00001930 unsigned Opcode = Instruction::UserOp1;
1931 if (Instruction *I = dyn_cast<Instruction>(V))
1932 Opcode = I->getOpcode();
1933 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1934 Opcode = CE->getOpcode();
1935 else
1936 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001937
Dan Gohman3996f472008-06-22 19:56:46 +00001938 User *U = cast<User>(V);
1939 switch (Opcode) {
1940 case Instruction::Add:
1941 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1942 getSCEV(U->getOperand(1)));
1943 case Instruction::Mul:
1944 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1945 getSCEV(U->getOperand(1)));
1946 case Instruction::UDiv:
1947 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1948 getSCEV(U->getOperand(1)));
1949 case Instruction::Sub:
1950 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1951 getSCEV(U->getOperand(1)));
1952 case Instruction::Or:
1953 // If the RHS of the Or is a constant, we may have something like:
1954 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1955 // optimizations will transparently handle this case.
1956 //
1957 // In order for this transformation to be safe, the LHS must be of the
1958 // form X*(2^n) and the Or constant must be less than 2^n.
1959 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1960 SCEVHandle LHS = getSCEV(U->getOperand(0));
1961 const APInt &CIVal = CI->getValue();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001962 if (GetMinTrailingZeros(LHS, SE) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001963 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1964 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001965 }
Dan Gohman3996f472008-06-22 19:56:46 +00001966 break;
1967 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001968 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001969 // If the RHS of the xor is a signbit, then this is just an add.
1970 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001971 if (CI->getValue().isSignBit())
1972 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1973 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001974
1975 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001976 else if (CI->isAllOnesValue())
1977 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1978 }
1979 break;
1980
1981 case Instruction::Shl:
1982 // Turn shift left of a constant amount into a multiply.
1983 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1984 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1985 Constant *X = ConstantInt::get(
1986 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1987 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1988 }
1989 break;
1990
Nick Lewycky7fd27892008-07-07 06:15:49 +00001991 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001992 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001993 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1994 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1995 Constant *X = ConstantInt::get(
1996 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1997 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1998 }
1999 break;
2000
Dan Gohman3996f472008-06-22 19:56:46 +00002001 case Instruction::Trunc:
2002 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2003
2004 case Instruction::ZExt:
2005 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2006
2007 case Instruction::SExt:
2008 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2009
2010 case Instruction::BitCast:
2011 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002012 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002013 return getSCEV(U->getOperand(0));
2014 break;
2015
Dan Gohman01c2ee72009-04-16 03:18:22 +00002016 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002017 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002018 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002019 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002020
2021 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002022 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002023 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2024 U->getType());
2025
2026 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002027 if (!TD) break; // Without TD we can't analyze pointers.
2028 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002029 Value *Base = U->getOperand(0);
2030 SCEVHandle TotalOffset = SE.getIntegerSCEV(0, IntPtrTy);
2031 gep_type_iterator GTI = gep_type_begin(U);
2032 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
2033 E = U->op_end();
2034 I != E; ++I) {
2035 Value *Index = *I;
2036 // Compute the (potentially symbolic) offset in bytes for this index.
2037 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2038 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002039 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002040 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2041 uint64_t Offset = SL.getElementOffset(FieldNo);
2042 TotalOffset = SE.getAddExpr(TotalOffset,
2043 SE.getIntegerSCEV(Offset, IntPtrTy));
2044 } else {
2045 // For an array, add the element offset, explicitly scaled.
2046 SCEVHandle LocalOffset = getSCEV(Index);
2047 if (!isa<PointerType>(LocalOffset->getType()))
2048 // Getelementptr indicies are signed.
2049 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2050 IntPtrTy);
2051 LocalOffset =
2052 SE.getMulExpr(LocalOffset,
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002053 SE.getIntegerSCEV(TD->getTypePaddedSize(*GTI),
Dan Gohman01c2ee72009-04-16 03:18:22 +00002054 IntPtrTy));
2055 TotalOffset = SE.getAddExpr(TotalOffset, LocalOffset);
2056 }
2057 }
2058 return SE.getAddExpr(getSCEV(Base), TotalOffset);
2059 }
2060
Dan Gohman3996f472008-06-22 19:56:46 +00002061 case Instruction::PHI:
2062 return createNodeForPHI(cast<PHINode>(U));
2063
2064 case Instruction::Select:
2065 // This could be a smax or umax that was lowered earlier.
2066 // Try to recover it.
2067 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2068 Value *LHS = ICI->getOperand(0);
2069 Value *RHS = ICI->getOperand(1);
2070 switch (ICI->getPredicate()) {
2071 case ICmpInst::ICMP_SLT:
2072 case ICmpInst::ICMP_SLE:
2073 std::swap(LHS, RHS);
2074 // fall through
2075 case ICmpInst::ICMP_SGT:
2076 case ICmpInst::ICMP_SGE:
2077 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2078 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2079 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002080 // ~smax(~x, ~y) == smin(x, y).
2081 return SE.getNotSCEV(SE.getSMaxExpr(
2082 SE.getNotSCEV(getSCEV(LHS)),
2083 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002084 break;
2085 case ICmpInst::ICMP_ULT:
2086 case ICmpInst::ICMP_ULE:
2087 std::swap(LHS, RHS);
2088 // fall through
2089 case ICmpInst::ICMP_UGT:
2090 case ICmpInst::ICMP_UGE:
2091 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2092 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2093 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2094 // ~umax(~x, ~y) == umin(x, y)
2095 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
2096 SE.getNotSCEV(getSCEV(RHS))));
2097 break;
2098 default:
2099 break;
2100 }
2101 }
2102
2103 default: // We cannot analyze this expression.
2104 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002105 }
2106
Dan Gohman89f85052007-10-22 18:31:58 +00002107 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002108}
2109
2110
2111
2112//===----------------------------------------------------------------------===//
2113// Iteration Count Computation Code
2114//
2115
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002116/// getBackedgeTakenCount - If the specified loop has a predictable
2117/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2118/// object. The backedge-taken count is the number of times the loop header
2119/// will be branched to from within the loop. This is one less than the
2120/// trip count of the loop, since it doesn't count the first iteration,
2121/// when the header is branched to from outside the loop.
2122///
2123/// Note that it is not valid to call this method on a loop without a
2124/// loop-invariant backedge-taken count (see
2125/// hasLoopInvariantBackedgeTakenCount).
2126///
2127SCEVHandle ScalarEvolutionsImpl::getBackedgeTakenCount(const Loop *L) {
2128 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
2129 if (I == BackedgeTakenCounts.end()) {
2130 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
2131 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002132 if (ItCount != UnknownValue) {
2133 assert(ItCount->isLoopInvariant(L) &&
2134 "Computed trip count isn't loop invariant for loop!");
2135 ++NumTripCountsComputed;
2136 } else if (isa<PHINode>(L->getHeader()->begin())) {
2137 // Only count loops that have phi nodes as not being computable.
2138 ++NumTripCountsNotComputed;
2139 }
2140 }
2141 return I->second;
2142}
2143
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002144/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002145/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002146/// ScalarEvolution's ability to compute a trip count, or if the loop
2147/// is deleted.
2148void ScalarEvolutionsImpl::forgetLoopBackedgeTakenCount(const Loop *L) {
2149 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002150}
2151
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002152/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2153/// of the specified loop will execute.
2154SCEVHandle ScalarEvolutionsImpl::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002156 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002157 L->getExitBlocks(ExitBlocks);
2158 if (ExitBlocks.size() != 1) return UnknownValue;
2159
2160 // Okay, there is one exit block. Try to find the condition that causes the
2161 // loop to be exited.
2162 BasicBlock *ExitBlock = ExitBlocks[0];
2163
2164 BasicBlock *ExitingBlock = 0;
2165 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2166 PI != E; ++PI)
2167 if (L->contains(*PI)) {
2168 if (ExitingBlock == 0)
2169 ExitingBlock = *PI;
2170 else
2171 return UnknownValue; // More than one block exiting!
2172 }
2173 assert(ExitingBlock && "No exits from loop, something is broken!");
2174
2175 // Okay, we've computed the exiting block. See what condition causes us to
2176 // exit.
2177 //
2178 // FIXME: we should be able to handle switch instructions (with a single exit)
2179 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2180 if (ExitBr == 0) return UnknownValue;
2181 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2182
2183 // At this point, we know we have a conditional branch that determines whether
2184 // the loop is exited. However, we don't know if the branch is executed each
2185 // time through the loop. If not, then the execution count of the branch will
2186 // not be equal to the trip count of the loop.
2187 //
2188 // Currently we check for this by checking to see if the Exit branch goes to
2189 // the loop header. If so, we know it will always execute the same number of
2190 // times as the loop. We also handle the case where the exit block *is* the
2191 // loop header. This is common for un-rotated loops. More extensive analysis
2192 // could be done to handle more cases here.
2193 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2194 ExitBr->getSuccessor(1) != L->getHeader() &&
2195 ExitBr->getParent() != L->getHeader())
2196 return UnknownValue;
2197
2198 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2199
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002200 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002201 // Note that ICmpInst deals with pointer comparisons too so we must check
2202 // the type of the operand.
2203 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002204 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002205 ExitBr->getSuccessor(0) == ExitBlock);
2206
2207 // If the condition was exit on true, convert the condition to exit on false
2208 ICmpInst::Predicate Cond;
2209 if (ExitBr->getSuccessor(1) == ExitBlock)
2210 Cond = ExitCond->getPredicate();
2211 else
2212 Cond = ExitCond->getInversePredicate();
2213
2214 // Handle common loops like: for (X = "string"; *X; ++X)
2215 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2216 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2217 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002218 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002219 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2220 }
2221
2222 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2223 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2224
2225 // Try to evaluate any dependencies out of the loop.
2226 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2227 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2228 Tmp = getSCEVAtScope(RHS, L);
2229 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2230
2231 // At this point, we would like to compute how many iterations of the
2232 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002233 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2234 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 std::swap(LHS, RHS);
2236 Cond = ICmpInst::getSwappedPredicate(Cond);
2237 }
2238
2239 // FIXME: think about handling pointer comparisons! i.e.:
2240 // while (P != P+100) ++P;
2241
2242 // If we have a comparison of a chrec against a constant, try to use value
2243 // ranges to answer this query.
2244 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2245 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2246 if (AddRec->getLoop() == L) {
2247 // Form the comparison range using the constant of the correct type so
2248 // that the ConstantRange class knows to do a signed or unsigned
2249 // comparison.
2250 ConstantInt *CompVal = RHSC->getValue();
2251 const Type *RealTy = ExitCond->getOperand(0)->getType();
2252 CompVal = dyn_cast<ConstantInt>(
2253 ConstantExpr::getBitCast(CompVal, RealTy));
2254 if (CompVal) {
2255 // Form the constant range.
2256 ConstantRange CompRange(
2257 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2258
Dan Gohman89f85052007-10-22 18:31:58 +00002259 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2261 }
2262 }
2263
2264 switch (Cond) {
2265 case ICmpInst::ICMP_NE: { // while (X != Y)
2266 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00002267 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002268 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2269 break;
2270 }
2271 case ICmpInst::ICMP_EQ: {
2272 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00002273 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2275 break;
2276 }
2277 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002278 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2280 break;
2281 }
2282 case ICmpInst::ICMP_SGT: {
Eli Friedman0dcd4ed2008-07-30 00:04:08 +00002283 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002284 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002285 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2286 break;
2287 }
2288 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002289 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002290 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2291 break;
2292 }
2293 case ICmpInst::ICMP_UGT: {
Dale Johannesend721b952008-04-20 16:58:57 +00002294 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002295 SE.getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002296 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2297 break;
2298 }
2299 default:
2300#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002301 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002303 errs() << "[unsigned] ";
2304 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 << Instruction::getOpcodeName(Instruction::ICmp)
2306 << " " << *RHS << "\n";
2307#endif
2308 break;
2309 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002310 return
2311 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2312 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313}
2314
2315static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002316EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2317 ScalarEvolution &SE) {
2318 SCEVHandle InVal = SE.getConstant(C);
2319 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002320 assert(isa<SCEVConstant>(Val) &&
2321 "Evaluation of SCEV at constant didn't fold correctly?");
2322 return cast<SCEVConstant>(Val)->getValue();
2323}
2324
2325/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2326/// and a GEP expression (missing the pointer index) indexing into it, return
2327/// the addressed element of the initializer or null if the index expression is
2328/// invalid.
2329static Constant *
2330GetAddressedElementFromGlobal(GlobalVariable *GV,
2331 const std::vector<ConstantInt*> &Indices) {
2332 Constant *Init = GV->getInitializer();
2333 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2334 uint64_t Idx = Indices[i]->getZExtValue();
2335 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2336 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2337 Init = cast<Constant>(CS->getOperand(Idx));
2338 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2339 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2340 Init = cast<Constant>(CA->getOperand(Idx));
2341 } else if (isa<ConstantAggregateZero>(Init)) {
2342 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2343 assert(Idx < STy->getNumElements() && "Bad struct index!");
2344 Init = Constant::getNullValue(STy->getElementType(Idx));
2345 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2346 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2347 Init = Constant::getNullValue(ATy->getElementType());
2348 } else {
2349 assert(0 && "Unknown constant aggregate type!");
2350 }
2351 return 0;
2352 } else {
2353 return 0; // Unknown initializer type
2354 }
2355 }
2356 return Init;
2357}
2358
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002359/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2360/// 'icmp op load X, cst', try to see if we can compute the backedge
2361/// execution count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002362SCEVHandle ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002363ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2364 const Loop *L,
2365 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002366 if (LI->isVolatile()) return UnknownValue;
2367
2368 // Check to see if the loaded pointer is a getelementptr of a global.
2369 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2370 if (!GEP) return UnknownValue;
2371
2372 // Make sure that it is really a constant global we are gepping, with an
2373 // initializer, and make sure the first IDX is really 0.
2374 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2375 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2376 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2377 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2378 return UnknownValue;
2379
2380 // Okay, we allow one non-constant index into the GEP instruction.
2381 Value *VarIdx = 0;
2382 std::vector<ConstantInt*> Indexes;
2383 unsigned VarIdxNum = 0;
2384 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2385 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2386 Indexes.push_back(CI);
2387 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2388 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2389 VarIdx = GEP->getOperand(i);
2390 VarIdxNum = i-2;
2391 Indexes.push_back(0);
2392 }
2393
2394 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2395 // Check to see if X is a loop variant variable value now.
2396 SCEVHandle Idx = getSCEV(VarIdx);
2397 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2398 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2399
2400 // We can only recognize very limited forms of loop index expressions, in
2401 // particular, only affine AddRec's like {C1,+,C2}.
2402 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2403 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2404 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2405 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2406 return UnknownValue;
2407
2408 unsigned MaxSteps = MaxBruteForceIterations;
2409 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2410 ConstantInt *ItCst =
2411 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00002412 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002413
2414 // Form the GEP offset.
2415 Indexes[VarIdxNum] = Val;
2416
2417 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2418 if (Result == 0) break; // Cannot compute!
2419
2420 // Evaluate the condition for this iteration.
2421 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2422 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2423 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2424#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002425 errs() << "\n***\n*** Computed loop count " << *ItCst
2426 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2427 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002428#endif
2429 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00002430 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002431 }
2432 }
2433 return UnknownValue;
2434}
2435
2436
2437/// CanConstantFold - Return true if we can constant fold an instruction of the
2438/// specified type, assuming that all operands were constants.
2439static bool CanConstantFold(const Instruction *I) {
2440 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2441 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2442 return true;
2443
2444 if (const CallInst *CI = dyn_cast<CallInst>(I))
2445 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002446 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002447 return false;
2448}
2449
2450/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2451/// in the loop that V is derived from. We allow arbitrary operations along the
2452/// way, but the operands of an operation must either be constants or a value
2453/// derived from a constant PHI. If this expression does not fit with these
2454/// constraints, return null.
2455static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2456 // If this is not an instruction, or if this is an instruction outside of the
2457 // loop, it can't be derived from a loop PHI.
2458 Instruction *I = dyn_cast<Instruction>(V);
2459 if (I == 0 || !L->contains(I->getParent())) return 0;
2460
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002461 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002462 if (L->getHeader() == I->getParent())
2463 return PN;
2464 else
2465 // We don't currently keep track of the control flow needed to evaluate
2466 // PHIs, so we cannot handle PHIs inside of loops.
2467 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002468 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002469
2470 // If we won't be able to constant fold this expression even if the operands
2471 // are constants, return early.
2472 if (!CanConstantFold(I)) return 0;
2473
2474 // Otherwise, we can evaluate this instruction if all of its operands are
2475 // constant or derived from a PHI node themselves.
2476 PHINode *PHI = 0;
2477 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2478 if (!(isa<Constant>(I->getOperand(Op)) ||
2479 isa<GlobalValue>(I->getOperand(Op)))) {
2480 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2481 if (P == 0) return 0; // Not evolving from PHI
2482 if (PHI == 0)
2483 PHI = P;
2484 else if (PHI != P)
2485 return 0; // Evolving from multiple different PHIs.
2486 }
2487
2488 // This is a expression evolving from a constant PHI!
2489 return PHI;
2490}
2491
2492/// EvaluateExpression - Given an expression that passes the
2493/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2494/// in the loop has the value PHIVal. If we can't fold this expression for some
2495/// reason, return null.
2496static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2497 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002498 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002499 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002500 Instruction *I = cast<Instruction>(V);
2501
2502 std::vector<Constant*> Operands;
2503 Operands.resize(I->getNumOperands());
2504
2505 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2506 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2507 if (Operands[i] == 0) return 0;
2508 }
2509
Chris Lattnerd6e56912007-12-10 22:53:04 +00002510 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2511 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2512 &Operands[0], Operands.size());
2513 else
2514 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2515 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002516}
2517
2518/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2519/// in the header of its containing loop, we know the loop executes a
2520/// constant number of times, and the PHI node is just a recurrence
2521/// involving constants, fold it.
2522Constant *ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002523getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002524 std::map<PHINode*, Constant*>::iterator I =
2525 ConstantEvolutionLoopExitValue.find(PN);
2526 if (I != ConstantEvolutionLoopExitValue.end())
2527 return I->second;
2528
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002529 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2531
2532 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2533
2534 // Since the loop is canonicalized, the PHI node must have two entries. One
2535 // entry must be a constant (coming in from outside of the loop), and the
2536 // second must be derived from the same PHI.
2537 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2538 Constant *StartCST =
2539 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2540 if (StartCST == 0)
2541 return RetVal = 0; // Must be a constant.
2542
2543 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2544 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2545 if (PN2 != PN)
2546 return RetVal = 0; // Not derived from same PHI.
2547
2548 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002549 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2551
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002552 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553 unsigned IterationNum = 0;
2554 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2555 if (IterationNum == NumIterations)
2556 return RetVal = PHIVal; // Got exit value!
2557
2558 // Compute the value of the PHI node for the next iteration.
2559 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2560 if (NextPHI == PHIVal)
2561 return RetVal = NextPHI; // Stopped evolving!
2562 if (NextPHI == 0)
2563 return 0; // Couldn't evaluate!
2564 PHIVal = NextPHI;
2565 }
2566}
2567
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002568/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569/// constant number of times (the condition evolves only from constants),
2570/// try to evaluate a few iterations of the loop until we get the exit
2571/// condition gets a value of ExitWhen (true or false). If we cannot
2572/// evaluate the trip count of the loop, return UnknownValue.
2573SCEVHandle ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002574ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002575 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2576 if (PN == 0) return UnknownValue;
2577
2578 // Since the loop is canonicalized, the PHI node must have two entries. One
2579 // entry must be a constant (coming in from outside of the loop), and the
2580 // second must be derived from the same PHI.
2581 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2582 Constant *StartCST =
2583 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2584 if (StartCST == 0) return UnknownValue; // Must be a constant.
2585
2586 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2587 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2588 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2589
2590 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2591 // the loop symbolically to determine when the condition gets a value of
2592 // "ExitWhen".
2593 unsigned IterationNum = 0;
2594 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2595 for (Constant *PHIVal = StartCST;
2596 IterationNum != MaxIterations; ++IterationNum) {
2597 ConstantInt *CondVal =
2598 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2599
2600 // Couldn't symbolically evaluate.
2601 if (!CondVal) return UnknownValue;
2602
2603 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2604 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2605 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002606 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002607 }
2608
2609 // Compute the value of the PHI node for the next iteration.
2610 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2611 if (NextPHI == 0 || NextPHI == PHIVal)
2612 return UnknownValue; // Couldn't evaluate or not making progress...
2613 PHIVal = NextPHI;
2614 }
2615
2616 // Too many iterations were needed to evaluate.
2617 return UnknownValue;
2618}
2619
2620/// getSCEVAtScope - Compute the value of the specified expression within the
2621/// indicated loop (which may be null to indicate in no loop). If the
2622/// expression cannot be evaluated, return UnknownValue.
2623SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2624 // FIXME: this should be turned into a virtual method on SCEV!
2625
2626 if (isa<SCEVConstant>(V)) return V;
2627
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002628 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002629 // exit value from the loop without using SCEVs.
2630 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2631 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2632 const Loop *LI = this->LI[I->getParent()];
2633 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2634 if (PHINode *PN = dyn_cast<PHINode>(I))
2635 if (PN->getParent() == LI->getHeader()) {
2636 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002637 // to see if the loop that contains it has a known backedge-taken
2638 // count. If so, we may be able to force computation of the exit
2639 // value.
2640 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2641 if (SCEVConstant *BTCC =
2642 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002643 // Okay, we know how many times the containing loop executes. If
2644 // this is a constant evolving PHI node, get the final value at
2645 // the specified iteration number.
2646 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002647 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002648 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002649 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002650 }
2651 }
2652
2653 // Okay, this is an expression that we cannot symbolically evaluate
2654 // into a SCEV. Check to see if it's possible to symbolically evaluate
2655 // the arguments into constants, and if so, try to constant propagate the
2656 // result. This is particularly useful for computing loop exit values.
2657 if (CanConstantFold(I)) {
2658 std::vector<Constant*> Operands;
2659 Operands.reserve(I->getNumOperands());
2660 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2661 Value *Op = I->getOperand(i);
2662 if (Constant *C = dyn_cast<Constant>(Op)) {
2663 Operands.push_back(C);
2664 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002665 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002666 // non-integer and non-pointer, don't even try to analyze them
2667 // with scev techniques.
2668 if (!isa<IntegerType>(Op->getType()) &&
2669 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002670 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002671
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002672 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2673 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2674 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2675 Op->getType(),
2676 false));
2677 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2678 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2679 Operands.push_back(ConstantExpr::getIntegerCast(C,
2680 Op->getType(),
2681 false));
2682 else
2683 return V;
2684 } else {
2685 return V;
2686 }
2687 }
2688 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002689
2690 Constant *C;
2691 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2692 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2693 &Operands[0], Operands.size());
2694 else
2695 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2696 &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002697 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002698 }
2699 }
2700
2701 // This is some other type of SCEVUnknown, just return it.
2702 return V;
2703 }
2704
2705 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2706 // Avoid performing the look-up in the common case where the specified
2707 // expression has no loop-variant portions.
2708 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2709 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2710 if (OpAtScope != Comm->getOperand(i)) {
2711 if (OpAtScope == UnknownValue) return UnknownValue;
2712 // Okay, at least one of these operands is loop variant but might be
2713 // foldable. Build a new instance of the folded commutative expression.
2714 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2715 NewOps.push_back(OpAtScope);
2716
2717 for (++i; i != e; ++i) {
2718 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2719 if (OpAtScope == UnknownValue) return UnknownValue;
2720 NewOps.push_back(OpAtScope);
2721 }
2722 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002723 return SE.getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002724 if (isa<SCEVMulExpr>(Comm))
2725 return SE.getMulExpr(NewOps);
2726 if (isa<SCEVSMaxExpr>(Comm))
2727 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002728 if (isa<SCEVUMaxExpr>(Comm))
2729 return SE.getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002730 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731 }
2732 }
2733 // If we got here, all operands are loop invariant.
2734 return Comm;
2735 }
2736
Nick Lewycky35b56022009-01-13 09:18:58 +00002737 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2738 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002740 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002741 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002742 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2743 return Div; // must be loop invariant
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002744 return SE.getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 }
2746
2747 // If this is a loop recurrence for a loop that does not contain L, then we
2748 // are dealing with the final value computed by the loop.
2749 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2750 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2751 // To evaluate this recurrence, we need to know how many times the AddRec
2752 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002753 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2754 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755
Eli Friedman7489ec92008-08-04 23:49:06 +00002756 // Then, evaluate the AddRec.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002757 return AddRec->evaluateAtIteration(BackedgeTakenCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 }
2759 return UnknownValue;
2760 }
2761
2762 //assert(0 && "Unknown SCEV type!");
2763 return UnknownValue;
2764}
2765
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002766/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2767/// following equation:
2768///
2769/// A * X = B (mod N)
2770///
2771/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2772/// A and B isn't important.
2773///
2774/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2775static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2776 ScalarEvolution &SE) {
2777 uint32_t BW = A.getBitWidth();
2778 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2779 assert(A != 0 && "A must be non-zero.");
2780
2781 // 1. D = gcd(A, N)
2782 //
2783 // The gcd of A and N may have only one prime factor: 2. The number of
2784 // trailing zeros in A is its multiplicity
2785 uint32_t Mult2 = A.countTrailingZeros();
2786 // D = 2^Mult2
2787
2788 // 2. Check if B is divisible by D.
2789 //
2790 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2791 // is not less than multiplicity of this prime factor for D.
2792 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002793 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002794
2795 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2796 // modulo (N / D).
2797 //
2798 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2799 // bit width during computations.
2800 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2801 APInt Mod(BW + 1, 0);
2802 Mod.set(BW - Mult2); // Mod = N / D
2803 APInt I = AD.multiplicativeInverse(Mod);
2804
2805 // 4. Compute the minimum unsigned root of the equation:
2806 // I * (B / D) mod (N / D)
2807 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2808
2809 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2810 // bits.
2811 return SE.getConstant(Result.trunc(BW));
2812}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813
2814/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2815/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2816/// might be the same) or two SCEVCouldNotCompute objects.
2817///
2818static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002819SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002820 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2821 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2822 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2823 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2824
2825 // We currently can only solve this if the coefficients are constants.
2826 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002827 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002828 return std::make_pair(CNC, CNC);
2829 }
2830
2831 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2832 const APInt &L = LC->getValue()->getValue();
2833 const APInt &M = MC->getValue()->getValue();
2834 const APInt &N = NC->getValue()->getValue();
2835 APInt Two(BitWidth, 2);
2836 APInt Four(BitWidth, 4);
2837
2838 {
2839 using namespace APIntOps;
2840 const APInt& C = L;
2841 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2842 // The B coefficient is M-N/2
2843 APInt B(M);
2844 B -= sdiv(N,Two);
2845
2846 // The A coefficient is N/2
2847 APInt A(N.sdiv(Two));
2848
2849 // Compute the B^2-4ac term.
2850 APInt SqrtTerm(B);
2851 SqrtTerm *= B;
2852 SqrtTerm -= Four * (A * C);
2853
2854 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2855 // integer value or else APInt::sqrt() will assert.
2856 APInt SqrtVal(SqrtTerm.sqrt());
2857
2858 // Compute the two solutions for the quadratic formula.
2859 // The divisions must be performed as signed divisions.
2860 APInt NegB(-B);
2861 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002862 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002863 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002864 return std::make_pair(CNC, CNC);
2865 }
2866
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2868 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2869
Dan Gohman89f85052007-10-22 18:31:58 +00002870 return std::make_pair(SE.getConstant(Solution1),
2871 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002872 } // end APIntOps namespace
2873}
2874
2875/// HowFarToZero - Return the number of times a backedge comparing the specified
2876/// value to zero will execute. If not computable, return UnknownValue
2877SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2878 // If the value is a constant
2879 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2880 // If the value is already zero, the branch will execute zero times.
2881 if (C->getValue()->isZero()) return C;
2882 return UnknownValue; // Otherwise it will loop infinitely.
2883 }
2884
2885 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2886 if (!AddRec || AddRec->getLoop() != L)
2887 return UnknownValue;
2888
2889 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002890 // If this is an affine expression, the execution count of this branch is
2891 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002892 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002893 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002894 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002895 // equivalent to:
2896 //
2897 // Step*N = -Start (mod 2^BW)
2898 //
2899 // where BW is the common bit width of Start and Step.
2900
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002901 // Get the initial value for the loop.
2902 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2903 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002904
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002905 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002906
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002907 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002908 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002909
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002910 // First, handle unitary steps.
2911 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2912 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2913 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2914 return Start; // N = Start (as unsigned)
2915
2916 // Then, try to solve the above equation provided that Start is constant.
2917 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2918 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2919 -StartC->getValue()->getValue(),SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002920 }
2921 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2922 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2923 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002924 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002925 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2926 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2927 if (R1) {
2928#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002929 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2930 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002931#endif
2932 // Pick the smallest positive root value.
2933 if (ConstantInt *CB =
2934 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2935 R1->getValue(), R2->getValue()))) {
2936 if (CB->getZExtValue() == false)
2937 std::swap(R1, R2); // R1 is the minimum root now.
2938
2939 // We can only use this value if the chrec ends up with an exact zero
2940 // value at this index. When solving for "X*X != 5", for example, we
2941 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002942 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohman7b560c42008-06-18 16:23:07 +00002943 if (Val->isZero())
2944 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002945 }
2946 }
2947 }
2948
2949 return UnknownValue;
2950}
2951
2952/// HowFarToNonZero - Return the number of times a backedge checking the
2953/// specified value for nonzero will execute. If not computable, return
2954/// UnknownValue
2955SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2956 // Loops that look like: while (X == 0) are very strange indeed. We don't
2957 // handle them yet except for the trivial case. This could be expanded in the
2958 // future as needed.
2959
2960 // If the value is a constant, check to see if it is known to be non-zero
2961 // already. If so, the backedge will execute zero times.
2962 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002963 if (!C->getValue()->isNullValue())
2964 return SE.getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002965 return UnknownValue; // Otherwise it will loop infinitely.
2966 }
2967
2968 // We could implement others, but I really doubt anyone writes loops like
2969 // this, and if they did, they would already be constant folded.
2970 return UnknownValue;
2971}
2972
Dan Gohman1cddf972008-09-15 22:18:04 +00002973/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2974/// (which may not be an immediate predecessor) which has exactly one
2975/// successor from which BB is reachable, or null if no such block is
2976/// found.
2977///
2978BasicBlock *
2979ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2980 // If the block has a unique predecessor, the predecessor must have
2981 // no other successors from which BB is reachable.
2982 if (BasicBlock *Pred = BB->getSinglePredecessor())
2983 return Pred;
2984
2985 // A loop's header is defined to be a block that dominates the loop.
2986 // If the loop has a preheader, it must be a block that has exactly
2987 // one successor that can reach BB. This is slightly more strict
2988 // than necessary, but works if critical edges are split.
2989 if (Loop *L = LI.getLoopFor(BB))
2990 return L->getLoopPreheader();
2991
2992 return 0;
2993}
2994
Dan Gohmancacd2012009-02-12 22:19:27 +00002995/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002996/// a conditional between LHS and RHS.
Dan Gohmancacd2012009-02-12 22:19:27 +00002997bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2998 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002999 SCEV *LHS, SCEV *RHS) {
3000 BasicBlock *Preheader = L->getLoopPreheader();
3001 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003002
Dan Gohmanab678fb2008-08-12 20:17:31 +00003003 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003004 // there are predecessors that can be found that have unique successors
3005 // leading to the original header.
3006 for (; Preheader;
3007 PreheaderDest = Preheader,
3008 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003009
3010 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003011 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003012 if (!LoopEntryPredicate ||
3013 LoopEntryPredicate->isUnconditional())
3014 continue;
3015
3016 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3017 if (!ICI) continue;
3018
3019 // Now that we found a conditional branch that dominates the loop, check to
3020 // see if it is the comparison we are looking for.
3021 Value *PreCondLHS = ICI->getOperand(0);
3022 Value *PreCondRHS = ICI->getOperand(1);
3023 ICmpInst::Predicate Cond;
3024 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3025 Cond = ICI->getPredicate();
3026 else
3027 Cond = ICI->getInversePredicate();
3028
Dan Gohmancacd2012009-02-12 22:19:27 +00003029 if (Cond == Pred)
3030 ; // An exact match.
3031 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3032 ; // The actual condition is beyond sufficient.
3033 else
3034 // Check a few special cases.
3035 switch (Cond) {
3036 case ICmpInst::ICMP_UGT:
3037 if (Pred == ICmpInst::ICMP_ULT) {
3038 std::swap(PreCondLHS, PreCondRHS);
3039 Cond = ICmpInst::ICMP_ULT;
3040 break;
3041 }
3042 continue;
3043 case ICmpInst::ICMP_SGT:
3044 if (Pred == ICmpInst::ICMP_SLT) {
3045 std::swap(PreCondLHS, PreCondRHS);
3046 Cond = ICmpInst::ICMP_SLT;
3047 break;
3048 }
3049 continue;
3050 case ICmpInst::ICMP_NE:
3051 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3052 // so check for this case by checking if the NE is comparing against
3053 // a minimum or maximum constant.
3054 if (!ICmpInst::isTrueWhenEqual(Pred))
3055 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3056 const APInt &A = CI->getValue();
3057 switch (Pred) {
3058 case ICmpInst::ICMP_SLT:
3059 if (A.isMaxSignedValue()) break;
3060 continue;
3061 case ICmpInst::ICMP_SGT:
3062 if (A.isMinSignedValue()) break;
3063 continue;
3064 case ICmpInst::ICMP_ULT:
3065 if (A.isMaxValue()) break;
3066 continue;
3067 case ICmpInst::ICMP_UGT:
3068 if (A.isMinValue()) break;
3069 continue;
3070 default:
3071 continue;
3072 }
3073 Cond = ICmpInst::ICMP_NE;
3074 // NE is symmetric but the original comparison may not be. Swap
3075 // the operands if necessary so that they match below.
3076 if (isa<SCEVConstant>(LHS))
3077 std::swap(PreCondLHS, PreCondRHS);
3078 break;
3079 }
3080 continue;
3081 default:
3082 // We weren't able to reconcile the condition.
3083 continue;
3084 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003085
3086 if (!PreCondLHS->getType()->isInteger()) continue;
3087
3088 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3089 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3090 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3091 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
3092 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
3093 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003094 }
3095
Dan Gohmanab678fb2008-08-12 20:17:31 +00003096 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003097}
3098
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003099/// HowManyLessThans - Return the number of times a backedge containing the
3100/// specified less-than comparison will execute. If not computable, return
3101/// UnknownValue.
3102SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky35b56022009-01-13 09:18:58 +00003103HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003104 // Only handle: "ADDREC < LoopInvariant".
3105 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3106
3107 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3108 if (!AddRec || AddRec->getLoop() != L)
3109 return UnknownValue;
3110
3111 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003112 // FORNOW: We only support unit strides.
3113 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
3114 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115 return UnknownValue;
3116
Nick Lewycky35b56022009-01-13 09:18:58 +00003117 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3118 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3119 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003120 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003122 // First, we get the value of the LHS in the first iteration: n
3123 SCEVHandle Start = AddRec->getOperand(0);
3124
Dan Gohmancacd2012009-02-12 22:19:27 +00003125 if (isLoopGuardedByCond(L,
3126 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Nick Lewycky35b56022009-01-13 09:18:58 +00003127 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
3128 // Since we know that the condition is true in order to enter the loop,
3129 // we know that it will run exactly m-n times.
3130 return SE.getMinusSCEV(RHS, Start);
3131 } else {
3132 // Then, we get the value of the LHS in the first iteration in which the
3133 // above condition doesn't hold. This equals to max(m,n).
3134 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
3135 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003136
Nick Lewycky35b56022009-01-13 09:18:58 +00003137 // Finally, we subtract these two values to get the number of times the
3138 // backedge is executed: max(m,n)-n.
3139 return SE.getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00003140 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003141 }
3142
3143 return UnknownValue;
3144}
3145
3146/// getNumIterationsInRange - Return the number of iterations of this loop that
3147/// produce values in the specified constant range. Another way of looking at
3148/// this is that it returns the first iteration number where the value is not in
3149/// the condition, thus computing the exit count. If the iteration count can't
3150/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003151SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3152 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003153 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003154 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155
3156 // If the start is a non-zero constant, shift the range to simplify things.
3157 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3158 if (!SC->getValue()->isZero()) {
3159 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003160 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3161 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3163 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003164 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003165 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003166 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003167 }
3168
3169 // The only time we can solve this is when we have all constant indices.
3170 // Otherwise, we cannot determine the overflow conditions.
3171 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3172 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003173 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003174
3175
3176 // Okay at this point we know that all elements of the chrec are constants and
3177 // that the start element is zero.
3178
3179 // First check to see if the range contains zero. If not, the first
3180 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003181 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003182 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003183 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184
3185 if (isAffine()) {
3186 // If this is an affine expression then we have this situation:
3187 // Solve {0,+,A} in Range === Ax in Range
3188
3189 // We know that zero is in the range. If A is positive then we know that
3190 // the upper value of the range must be the first possible exit value.
3191 // If A is negative then the lower of the range is the last possible loop
3192 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003193 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003194 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3195 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3196
3197 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003198 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003199 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3200
3201 // Evaluate at the exit value. If we really did fall out of the valid
3202 // range, then we computed our trip count, otherwise wrap around or other
3203 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003204 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003205 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003206 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207
3208 // Ensure that the previous value is in the range. This is a sanity check.
3209 assert(Range.contains(
3210 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003211 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003212 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003213 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 } else if (isQuadratic()) {
3215 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3216 // quadratic equation to solve it. To do this, we must frame our problem in
3217 // terms of figuring out when zero is crossed, instead of when
3218 // Range.getUpper() is crossed.
3219 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003220 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3221 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003222
3223 // Next, solve the constructed addrec
3224 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003225 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3227 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3228 if (R1) {
3229 // Pick the smallest positive root value.
3230 if (ConstantInt *CB =
3231 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3232 R1->getValue(), R2->getValue()))) {
3233 if (CB->getZExtValue() == false)
3234 std::swap(R1, R2); // R1 is the minimum root now.
3235
3236 // Make sure the root is not off by one. The returned iteration should
3237 // not be in the range, but the previous one should be. When solving
3238 // for "X*X < 5", for example, we should not return a root of 2.
3239 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003240 R1->getValue(),
3241 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003242 if (Range.contains(R1Val->getValue())) {
3243 // The next iteration must be out of the range...
3244 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3245
Dan Gohman89f85052007-10-22 18:31:58 +00003246 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003247 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003248 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003249 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003250 }
3251
3252 // If R1 was not in the range, then it is a good return value. Make
3253 // sure that R1-1 WAS in the range though, just in case.
3254 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003255 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256 if (Range.contains(R1Val->getValue()))
3257 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003258 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 }
3260 }
3261 }
3262
Dan Gohman0ad08b02009-04-18 17:58:19 +00003263 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003264}
3265
3266
3267
3268//===----------------------------------------------------------------------===//
3269// ScalarEvolution Class Implementation
3270//===----------------------------------------------------------------------===//
3271
3272bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00003273 Impl = new ScalarEvolutionsImpl(*this, F,
3274 getAnalysis<LoopInfo>(),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003275 &getAnalysis<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003276 return false;
3277}
3278
3279void ScalarEvolution::releaseMemory() {
3280 delete (ScalarEvolutionsImpl*)Impl;
3281 Impl = 0;
3282}
3283
3284void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3285 AU.setPreservesAll();
3286 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003287 AU.addRequiredTransitive<TargetData>();
3288}
3289
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003290bool ScalarEvolution::isSCEVable(const Type *Ty) const {
3291 return ((ScalarEvolutionsImpl*)Impl)->isSCEVable(Ty);
3292}
3293
3294uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
3295 return ((ScalarEvolutionsImpl*)Impl)->getTypeSizeInBits(Ty);
3296}
3297
3298const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
3299 return ((ScalarEvolutionsImpl*)Impl)->getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00003300}
3301
Dan Gohman0ad08b02009-04-18 17:58:19 +00003302SCEVHandle ScalarEvolution::getCouldNotCompute() {
3303 return ((ScalarEvolutionsImpl*)Impl)->getCouldNotCompute();
3304}
3305
Dan Gohman01c2ee72009-04-16 03:18:22 +00003306SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
3307 return ((ScalarEvolutionsImpl*)Impl)->getIntegerSCEV(Val, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308}
3309
3310SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3311 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3312}
3313
3314/// hasSCEV - Return true if the SCEV for this value has already been
3315/// computed.
3316bool ScalarEvolution::hasSCEV(Value *V) const {
3317 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3318}
3319
3320
3321/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3322/// the specified value.
3323void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3324 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3325}
3326
Dan Gohman01c2ee72009-04-16 03:18:22 +00003327/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3328///
3329SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
3330 return ((ScalarEvolutionsImpl*)Impl)->getNegativeSCEV(V);
3331}
3332
3333/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3334///
3335SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
3336 return ((ScalarEvolutionsImpl*)Impl)->getNotSCEV(V);
3337}
3338
3339/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
3340///
3341SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
3342 const SCEVHandle &RHS) {
3343 return ((ScalarEvolutionsImpl*)Impl)->getMinusSCEV(LHS, RHS);
3344}
3345
3346/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
3347/// of the input value to the specified type. If the type must be
3348/// extended, it is zero extended.
3349SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
3350 const Type *Ty) {
3351 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrZeroExtend(V, Ty);
3352}
3353
3354/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
3355/// of the input value to the specified type. If the type must be
3356/// extended, it is sign extended.
3357SCEVHandle ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
3358 const Type *Ty) {
3359 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrSignExtend(V, Ty);
3360}
3361
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003362
Dan Gohmancacd2012009-02-12 22:19:27 +00003363bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3364 ICmpInst::Predicate Pred,
3365 SCEV *LHS, SCEV *RHS) {
3366 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3367 LHS, RHS);
3368}
3369
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003370SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) const {
3371 return ((ScalarEvolutionsImpl*)Impl)->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003372}
3373
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003374bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) const {
3375 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003376}
3377
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003378void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3379 return ((ScalarEvolutionsImpl*)Impl)->forgetLoopBackedgeTakenCount(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003380}
3381
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003382SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3383 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3384}
3385
3386void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3387 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3388}
3389
Dan Gohman13058cc2009-04-21 00:47:46 +00003390static void PrintLoopInfo(raw_ostream &OS, const ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391 const Loop *L) {
3392 // Print all inner loops first
3393 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3394 PrintLoopInfo(OS, SE, *I);
3395
Nick Lewyckye5da1912008-01-02 02:49:20 +00003396 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003397
Devang Patel02451fa2007-08-21 00:31:24 +00003398 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399 L->getExitBlocks(ExitBlocks);
3400 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003401 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003403 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3404 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003406 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003407 }
3408
Nick Lewyckye5da1912008-01-02 02:49:20 +00003409 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003410}
3411
Dan Gohman13058cc2009-04-21 00:47:46 +00003412void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003413 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3414 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3415
3416 OS << "Classifying expressions for: " << F.getName() << "\n";
3417 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3418 if (I->getType()->isInteger()) {
3419 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003420 OS << " --> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421 SCEVHandle SV = getSCEV(&*I);
3422 SV->print(OS);
3423 OS << "\t\t";
3424
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003425 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3426 OS << "Exits: ";
3427 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3428 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3429 OS << "<<Unknown>>";
3430 } else {
3431 OS << *ExitValue;
3432 }
3433 }
3434
3435
3436 OS << "\n";
3437 }
3438
3439 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3440 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3441 PrintLoopInfo(OS, this, *I);
3442}
Dan Gohman13058cc2009-04-21 00:47:46 +00003443
3444void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3445 raw_os_ostream OS(o);
3446 print(OS, M);
3447}