blob: 0dbb2580476e985bb95bfc4f13a82337176de77f [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
Dan Gohman2a381532009-04-21 01:25:57 +0000193SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
194 const SCEVHandle &op, const Type *ty)
195 : SCEV(SCEVTy), Op(op), Ty(ty) {}
196
197SCEVCastExpr::~SCEVCastExpr() {}
198
199bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
200 return Op->dominates(BB, DT);
201}
202
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
204// particular input. Don't use a SCEVHandle here, or else the object will
205// never be deleted!
206static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
207 SCEVTruncateExpr*> > SCEVTruncates;
208
209SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000210 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000211 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
212 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214}
215
216SCEVTruncateExpr::~SCEVTruncateExpr() {
217 SCEVTruncates->erase(std::make_pair(Op, Ty));
218}
219
Dan Gohman13058cc2009-04-21 00:47:46 +0000220void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 OS << "(truncate " << *Op << " to " << *Ty << ")";
222}
223
224// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
225// particular input. Don't use a SCEVHandle here, or else the object will never
226// be deleted!
227static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
228 SCEVZeroExtendExpr*> > SCEVZeroExtends;
229
230SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000231 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000232 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
233 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235}
236
237SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
238 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
239}
240
Dan Gohman13058cc2009-04-21 00:47:46 +0000241void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
243}
244
245// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
246// particular input. Don't use a SCEVHandle here, or else the object will never
247// be deleted!
248static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
249 SCEVSignExtendExpr*> > SCEVSignExtends;
250
251SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000252 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000253 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
254 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256}
257
258SCEVSignExtendExpr::~SCEVSignExtendExpr() {
259 SCEVSignExtends->erase(std::make_pair(Op, Ty));
260}
261
Dan Gohman13058cc2009-04-21 00:47:46 +0000262void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 OS << "(signextend " << *Op << " to " << *Ty << ")";
264}
265
266// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
267// particular input. Don't use a SCEVHandle here, or else the object will never
268// be deleted!
269static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
270 SCEVCommutativeExpr*> > SCEVCommExprs;
271
272SCEVCommutativeExpr::~SCEVCommutativeExpr() {
273 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
274 std::vector<SCEV*>(Operands.begin(),
275 Operands.end())));
276}
277
Dan Gohman13058cc2009-04-21 00:47:46 +0000278void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
280 const char *OpStr = getOperationStr();
281 OS << "(" << *Operands[0];
282 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
283 OS << OpStr << *Operands[i];
284 OS << ")";
285}
286
287SCEVHandle SCEVCommutativeExpr::
288replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000289 const SCEVHandle &Conc,
290 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000292 SCEVHandle H =
293 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 if (H != getOperand(i)) {
295 std::vector<SCEVHandle> NewOps;
296 NewOps.reserve(getNumOperands());
297 for (unsigned j = 0; j != i; ++j)
298 NewOps.push_back(getOperand(j));
299 NewOps.push_back(H);
300 for (++i; i != e; ++i)
301 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000302 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303
304 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000305 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000307 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000308 else if (isa<SCEVSMaxExpr>(this))
309 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000310 else if (isa<SCEVUMaxExpr>(this))
311 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 else
313 assert(0 && "Unknown commutative expr!");
314 }
315 }
316 return this;
317}
318
Evan Cheng98c073b2009-02-17 00:13:06 +0000319bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
320 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
321 if (!getOperand(i)->dominates(BB, DT))
322 return false;
323 }
324 return true;
325}
326
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000328// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329// input. Don't use a SCEVHandle here, or else the object will never be
330// deleted!
331static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000332 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000334SCEVUDivExpr::~SCEVUDivExpr() {
335 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336}
337
Evan Cheng98c073b2009-02-17 00:13:06 +0000338bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
339 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
340}
341
Dan Gohman13058cc2009-04-21 00:47:46 +0000342void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000343 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344}
345
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000346const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 return LHS->getType();
348}
349
350// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
351// particular input. Don't use a SCEVHandle here, or else the object will never
352// be deleted!
353static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
354 SCEVAddRecExpr*> > SCEVAddRecExprs;
355
356SCEVAddRecExpr::~SCEVAddRecExpr() {
357 SCEVAddRecExprs->erase(std::make_pair(L,
358 std::vector<SCEV*>(Operands.begin(),
359 Operands.end())));
360}
361
Evan Cheng98c073b2009-02-17 00:13:06 +0000362bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
364 if (!getOperand(i)->dominates(BB, DT))
365 return false;
366 }
367 return true;
368}
369
370
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371SCEVHandle SCEVAddRecExpr::
372replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000373 const SCEVHandle &Conc,
374 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000376 SCEVHandle H =
377 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 if (H != getOperand(i)) {
379 std::vector<SCEVHandle> NewOps;
380 NewOps.reserve(getNumOperands());
381 for (unsigned j = 0; j != i; ++j)
382 NewOps.push_back(getOperand(j));
383 NewOps.push_back(H);
384 for (++i; i != e; ++i)
385 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000386 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000387
Dan Gohman89f85052007-10-22 18:31:58 +0000388 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 }
390 }
391 return this;
392}
393
394
395bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
396 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
397 // contain L and if the start is invariant.
398 return !QueryLoop->contains(L->getHeader()) &&
399 getOperand(0)->isLoopInvariant(QueryLoop);
400}
401
402
Dan Gohman13058cc2009-04-21 00:47:46 +0000403void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 OS << "{" << *Operands[0];
405 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
406 OS << ",+," << *Operands[i];
407 OS << "}<" << L->getHeader()->getName() + ">";
408}
409
410// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
411// value. Don't use a SCEVHandle here, or else the object will never be
412// deleted!
413static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
414
415SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
416
417bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
418 // All non-instruction values are loop invariant. All instructions are loop
419 // invariant if they are not contained in the specified loop.
420 if (Instruction *I = dyn_cast<Instruction>(V))
421 return !L->contains(I->getParent());
422 return true;
423}
424
Evan Cheng98c073b2009-02-17 00:13:06 +0000425bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
426 if (Instruction *I = dyn_cast<Instruction>(getValue()))
427 return DT->dominates(I->getParent(), BB);
428 return true;
429}
430
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431const Type *SCEVUnknown::getType() const {
432 return V->getType();
433}
434
Dan Gohman13058cc2009-04-21 00:47:46 +0000435void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000436 if (isa<PointerType>(V->getType()))
437 OS << "(ptrtoint " << *V->getType() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 WriteAsOperand(OS, V, false);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000439 if (isa<PointerType>(V->getType()))
440 OS << " to iPTR)";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441}
442
443//===----------------------------------------------------------------------===//
444// SCEV Utilities
445//===----------------------------------------------------------------------===//
446
447namespace {
448 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
449 /// than the complexity of the RHS. This comparator is used to canonicalize
450 /// expressions.
451 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000452 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 return LHS->getSCEVType() < RHS->getSCEVType();
454 }
455 };
456}
457
458/// GroupByComplexity - Given a list of SCEV objects, order them by their
459/// complexity, and group objects of the same complexity together by value.
460/// When this routine is finished, we know that any duplicates in the vector are
461/// consecutive and that complexity is monotonically increasing.
462///
463/// Note that we go take special precautions to ensure that we get determinstic
464/// results from this routine. In other words, we don't want the results of
465/// this to depend on where the addresses of various SCEV objects happened to
466/// land in memory.
467///
468static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
469 if (Ops.size() < 2) return; // Noop
470 if (Ops.size() == 2) {
471 // This is the common case, which also happens to be trivially simple.
472 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000473 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 std::swap(Ops[0], Ops[1]);
475 return;
476 }
477
478 // Do the rough sort by complexity.
479 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
480
481 // Now that we are sorted by complexity, group elements of the same
482 // complexity. Note that this is, at worst, N^2, but the vector is likely to
483 // be extremely short in practice. Note that we take this approach because we
484 // do not want to depend on the addresses of the objects we are grouping.
485 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
486 SCEV *S = Ops[i];
487 unsigned Complexity = S->getSCEVType();
488
489 // If there are any objects of the same complexity and same value as this
490 // one, group them.
491 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
492 if (Ops[j] == S) { // Found a duplicate.
493 // Move it to immediately after i'th element.
494 std::swap(Ops[i+1], Ops[j]);
495 ++i; // no need to rescan it.
496 if (i == e-2) return; // Done!
497 }
498 }
499 }
500}
501
502
503
504//===----------------------------------------------------------------------===//
505// Simple SCEV method implementations
506//===----------------------------------------------------------------------===//
507
Eli Friedman7489ec92008-08-04 23:49:06 +0000508/// BinomialCoefficient - Compute BC(It, K). The result has width W.
509// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000510static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000511 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000512 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000513 // Handle the simplest case efficiently.
514 if (K == 1)
515 return SE.getTruncateOrZeroExtend(It, ResultTy);
516
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000517 // We are using the following formula for BC(It, K):
518 //
519 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
520 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000521 // Suppose, W is the bitwidth of the return value. We must be prepared for
522 // overflow. Hence, we must assure that the result of our computation is
523 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
524 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000525 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000526 // However, this code doesn't use exactly that formula; the formula it uses
527 // is something like the following, where T is the number of factors of 2 in
528 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
529 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000530 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000531 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000532 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000533 // This formula is trivially equivalent to the previous formula. However,
534 // this formula can be implemented much more efficiently. The trick is that
535 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
536 // arithmetic. To do exact division in modular arithmetic, all we have
537 // to do is multiply by the inverse. Therefore, this step can be done at
538 // width W.
539 //
540 // The next issue is how to safely do the division by 2^T. The way this
541 // is done is by doing the multiplication step at a width of at least W + T
542 // bits. This way, the bottom W+T bits of the product are accurate. Then,
543 // when we perform the division by 2^T (which is equivalent to a right shift
544 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
545 // truncated out after the division by 2^T.
546 //
547 // In comparison to just directly using the first formula, this technique
548 // is much more efficient; using the first formula requires W * K bits,
549 // but this formula less than W + K bits. Also, the first formula requires
550 // a division step, whereas this formula only requires multiplies and shifts.
551 //
552 // It doesn't matter whether the subtraction step is done in the calculation
553 // width or the input iteration count's width; if the subtraction overflows,
554 // the result must be zero anyway. We prefer here to do it in the width of
555 // the induction variable because it helps a lot for certain cases; CodeGen
556 // isn't smart enough to ignore the overflow, which leads to much less
557 // efficient code if the width of the subtraction is wider than the native
558 // register width.
559 //
560 // (It's possible to not widen at all by pulling out factors of 2 before
561 // the multiplication; for example, K=2 can be calculated as
562 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
563 // extra arithmetic, so it's not an obvious win, and it gets
564 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000565
Eli Friedman7489ec92008-08-04 23:49:06 +0000566 // Protection from insane SCEVs; this bound is conservative,
567 // but it probably doesn't matter.
568 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000569 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000570
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000571 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000572
Eli Friedman7489ec92008-08-04 23:49:06 +0000573 // Calculate K! / 2^T and T; we divide out the factors of two before
574 // multiplying for calculating K! / 2^T to avoid overflow.
575 // Other overflow doesn't matter because we only care about the bottom
576 // W bits of the result.
577 APInt OddFactorial(W, 1);
578 unsigned T = 1;
579 for (unsigned i = 3; i <= K; ++i) {
580 APInt Mult(W, i);
581 unsigned TwoFactors = Mult.countTrailingZeros();
582 T += TwoFactors;
583 Mult = Mult.lshr(TwoFactors);
584 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000586
Eli Friedman7489ec92008-08-04 23:49:06 +0000587 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000588 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000589
590 // Calcuate 2^T, at width T+W.
591 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
592
593 // Calculate the multiplicative inverse of K! / 2^T;
594 // this multiplication factor will perform the exact division by
595 // K! / 2^T.
596 APInt Mod = APInt::getSignedMinValue(W+1);
597 APInt MultiplyFactor = OddFactorial.zext(W+1);
598 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
599 MultiplyFactor = MultiplyFactor.trunc(W);
600
601 // Calculate the product, at width T+W
602 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
603 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
604 for (unsigned i = 1; i != K; ++i) {
605 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
606 Dividend = SE.getMulExpr(Dividend,
607 SE.getTruncateOrZeroExtend(S, CalculationTy));
608 }
609
610 // Divide by 2^T
611 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
612
613 // Truncate the result, and divide by K! / 2^T.
614
615 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
616 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617}
618
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619/// evaluateAtIteration - Return the value of this chain of recurrences at
620/// the specified iteration number. We can evaluate this recurrence by
621/// multiplying each element in the chain by the binomial coefficient
622/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
623///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000624/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000626/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627///
Dan Gohman89f85052007-10-22 18:31:58 +0000628SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
629 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000632 // The computation is correct in the face of overflow provided that the
633 // multiplication is performed _after_ the evaluation of the binomial
634 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000635 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000636 if (isa<SCEVCouldNotCompute>(Coeff))
637 return Coeff;
638
639 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 }
641 return Result;
642}
643
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644//===----------------------------------------------------------------------===//
645// SCEV Expression folder implementations
646//===----------------------------------------------------------------------===//
647
Dan Gohman89f85052007-10-22 18:31:58 +0000648SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000649 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000650 "This is not a truncating conversion!");
651
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000653 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 ConstantExpr::getTrunc(SC->getValue(), Ty));
655
656 // If the input value is a chrec scev made out of constants, truncate
657 // all of the constants.
658 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
659 std::vector<SCEVHandle> Operands;
660 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
661 // FIXME: This should allow truncation of other expression types!
662 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000663 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 else
665 break;
666 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000667 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 }
669
670 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
671 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
672 return Result;
673}
674
Dan Gohman36d40922009-04-16 19:25:55 +0000675SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
676 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000677 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000678 "This is not an extending conversion!");
679
Dan Gohman01c2ee72009-04-16 03:18:22 +0000680 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000681 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000682 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
683 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
684 return getUnknown(C);
685 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686
687 // FIXME: If the input value is a chrec scev, and we can prove that the value
688 // did not overflow the old, smaller, value, we can zero extend all of the
689 // operands (often constants). This would allow analysis of something like
690 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
691
692 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
693 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
694 return Result;
695}
696
Dan Gohman89f85052007-10-22 18:31:58 +0000697SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000698 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000699 "This is not an extending conversion!");
700
Dan Gohman01c2ee72009-04-16 03:18:22 +0000701 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000702 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000703 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
704 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
705 return getUnknown(C);
706 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707
708 // FIXME: If the input value is a chrec scev, and we can prove that the value
709 // did not overflow the old, smaller, value, we can sign extend all of the
710 // operands (often constants). This would allow analysis of something like
711 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
712
713 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
714 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
715 return Result;
716}
717
718// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000719SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 assert(!Ops.empty() && "Cannot get empty add!");
721 if (Ops.size() == 1) return Ops[0];
722
723 // Sort by complexity, this groups all similar expression types together.
724 GroupByComplexity(Ops);
725
726 // If there are any constants, fold them together.
727 unsigned Idx = 0;
728 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
729 ++Idx;
730 assert(Idx < Ops.size());
731 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
732 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000733 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
734 RHSC->getValue()->getValue());
735 Ops[0] = getConstant(Fold);
736 Ops.erase(Ops.begin()+1); // Erase the folded element
737 if (Ops.size() == 1) return Ops[0];
738 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 }
740
741 // If we are left with a constant zero being added, strip it off.
742 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
743 Ops.erase(Ops.begin());
744 --Idx;
745 }
746 }
747
748 if (Ops.size() == 1) return Ops[0];
749
750 // Okay, check to see if the same value occurs in the operand list twice. If
751 // so, merge them together into an multiply expression. Since we sorted the
752 // list, these values are required to be adjacent.
753 const Type *Ty = Ops[0]->getType();
754 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
755 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
756 // Found a match, merge the two values into a multiply, and add any
757 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000758 SCEVHandle Two = getIntegerSCEV(2, Ty);
759 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 if (Ops.size() == 2)
761 return Mul;
762 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
763 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000764 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 }
766
767 // Now we know the first non-constant operand. Skip past any cast SCEVs.
768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
769 ++Idx;
770
771 // If there are add operands they would be next.
772 if (Idx < Ops.size()) {
773 bool DeletedAdd = false;
774 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
775 // If we have an add, expand the add operands onto the end of the operands
776 // list.
777 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
778 Ops.erase(Ops.begin()+Idx);
779 DeletedAdd = true;
780 }
781
782 // If we deleted at least one add, we added operands to the end of the list,
783 // and they are not necessarily sorted. Recurse to resort and resimplify
784 // any operands we just aquired.
785 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000786 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 }
788
789 // Skip over the add expression until we get to a multiply.
790 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
791 ++Idx;
792
793 // If we are adding something to a multiply expression, make sure the
794 // something is not already an operand of the multiply. If so, merge it into
795 // the multiply.
796 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
797 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
798 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
799 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
800 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
801 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
802 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
803 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
804 if (Mul->getNumOperands() != 2) {
805 // If the multiply has more than two operands, we must get the
806 // Y*Z term.
807 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
808 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000809 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 }
Dan Gohman89f85052007-10-22 18:31:58 +0000811 SCEVHandle One = getIntegerSCEV(1, Ty);
812 SCEVHandle AddOne = getAddExpr(InnerMul, One);
813 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 if (Ops.size() == 2) return OuterMul;
815 if (AddOp < Idx) {
816 Ops.erase(Ops.begin()+AddOp);
817 Ops.erase(Ops.begin()+Idx-1);
818 } else {
819 Ops.erase(Ops.begin()+Idx);
820 Ops.erase(Ops.begin()+AddOp-1);
821 }
822 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000823 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 }
825
826 // Check this multiply against other multiplies being added together.
827 for (unsigned OtherMulIdx = Idx+1;
828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
829 ++OtherMulIdx) {
830 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
831 // If MulOp occurs in OtherMul, we can fold the two multiplies
832 // together.
833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
834 OMulOp != e; ++OMulOp)
835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
837 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
838 if (Mul->getNumOperands() != 2) {
839 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
840 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000841 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000842 }
843 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
844 if (OtherMul->getNumOperands() != 2) {
845 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
846 OtherMul->op_end());
847 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000848 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
Dan Gohman89f85052007-10-22 18:31:58 +0000850 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
851 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 if (Ops.size() == 2) return OuterMul;
853 Ops.erase(Ops.begin()+Idx);
854 Ops.erase(Ops.begin()+OtherMulIdx-1);
855 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000856 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 }
858 }
859 }
860 }
861
862 // If there are any add recurrences in the operands list, see if any other
863 // added values are loop invariant. If so, we can fold them into the
864 // recurrence.
865 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
866 ++Idx;
867
868 // Scan over all recurrences, trying to fold loop invariants into them.
869 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
870 // Scan all of the other operands to this add and add them to the vector if
871 // they are loop invariant w.r.t. the recurrence.
872 std::vector<SCEVHandle> LIOps;
873 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
874 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
875 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
876 LIOps.push_back(Ops[i]);
877 Ops.erase(Ops.begin()+i);
878 --i; --e;
879 }
880
881 // If we found some loop invariants, fold them into the recurrence.
882 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000883 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 LIOps.push_back(AddRec->getStart());
885
886 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000887 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888
Dan Gohman89f85052007-10-22 18:31:58 +0000889 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 // If all of the other operands were loop invariant, we are done.
891 if (Ops.size() == 1) return NewRec;
892
893 // Otherwise, add the folded AddRec by the non-liv parts.
894 for (unsigned i = 0;; ++i)
895 if (Ops[i] == AddRec) {
896 Ops[i] = NewRec;
897 break;
898 }
Dan Gohman89f85052007-10-22 18:31:58 +0000899 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 }
901
902 // Okay, if there weren't any loop invariants to be folded, check to see if
903 // there are multiple AddRec's with the same loop induction variable being
904 // added together. If so, we can fold them.
905 for (unsigned OtherIdx = Idx+1;
906 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
907 if (OtherIdx != Idx) {
908 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
909 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
910 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
911 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
912 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
913 if (i >= NewOps.size()) {
914 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
915 OtherAddRec->op_end());
916 break;
917 }
Dan Gohman89f85052007-10-22 18:31:58 +0000918 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 }
Dan Gohman89f85052007-10-22 18:31:58 +0000920 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921
922 if (Ops.size() == 2) return NewAddRec;
923
924 Ops.erase(Ops.begin()+Idx);
925 Ops.erase(Ops.begin()+OtherIdx-1);
926 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000927 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 }
929 }
930
931 // Otherwise couldn't fold anything into this recurrence. Move onto the
932 // next one.
933 }
934
935 // Okay, it looks like we really DO need an add expr. Check to see if we
936 // already have one, otherwise create a new one.
937 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
938 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
939 SCEVOps)];
940 if (Result == 0) Result = new SCEVAddExpr(Ops);
941 return Result;
942}
943
944
Dan Gohman89f85052007-10-22 18:31:58 +0000945SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 assert(!Ops.empty() && "Cannot get empty mul!");
947
948 // Sort by complexity, this groups all similar expression types together.
949 GroupByComplexity(Ops);
950
951 // If there are any constants, fold them together.
952 unsigned Idx = 0;
953 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
954
955 // C1*(C2+V) -> C1*C2 + C1*V
956 if (Ops.size() == 2)
957 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
958 if (Add->getNumOperands() == 2 &&
959 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000960 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
961 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962
963
964 ++Idx;
965 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
966 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000967 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
968 RHSC->getValue()->getValue());
969 Ops[0] = getConstant(Fold);
970 Ops.erase(Ops.begin()+1); // Erase the folded element
971 if (Ops.size() == 1) return Ops[0];
972 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 }
974
975 // If we are left with a constant one being multiplied, strip it off.
976 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
977 Ops.erase(Ops.begin());
978 --Idx;
979 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
980 // If we have a multiply of zero, it will always be zero.
981 return Ops[0];
982 }
983 }
984
985 // Skip over the add expression until we get to a multiply.
986 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
987 ++Idx;
988
989 if (Ops.size() == 1)
990 return Ops[0];
991
992 // If there are mul operands inline them all into this expression.
993 if (Idx < Ops.size()) {
994 bool DeletedMul = false;
995 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
996 // If we have an mul, expand the mul operands onto the end of the operands
997 // list.
998 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
999 Ops.erase(Ops.begin()+Idx);
1000 DeletedMul = true;
1001 }
1002
1003 // If we deleted at least one mul, we added operands to the end of the list,
1004 // and they are not necessarily sorted. Recurse to resort and resimplify
1005 // any operands we just aquired.
1006 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001007 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008 }
1009
1010 // If there are any add recurrences in the operands list, see if any other
1011 // added values are loop invariant. If so, we can fold them into the
1012 // recurrence.
1013 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1014 ++Idx;
1015
1016 // Scan over all recurrences, trying to fold loop invariants into them.
1017 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1018 // Scan all of the other operands to this mul and add them to the vector if
1019 // they are loop invariant w.r.t. the recurrence.
1020 std::vector<SCEVHandle> LIOps;
1021 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1022 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1023 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1024 LIOps.push_back(Ops[i]);
1025 Ops.erase(Ops.begin()+i);
1026 --i; --e;
1027 }
1028
1029 // If we found some loop invariants, fold them into the recurrence.
1030 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001031 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 std::vector<SCEVHandle> NewOps;
1033 NewOps.reserve(AddRec->getNumOperands());
1034 if (LIOps.size() == 1) {
1035 SCEV *Scale = LIOps[0];
1036 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001037 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 } else {
1039 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1040 std::vector<SCEVHandle> MulOps(LIOps);
1041 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001042 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044 }
1045
Dan Gohman89f85052007-10-22 18:31:58 +00001046 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047
1048 // If all of the other operands were loop invariant, we are done.
1049 if (Ops.size() == 1) return NewRec;
1050
1051 // Otherwise, multiply the folded AddRec by the non-liv parts.
1052 for (unsigned i = 0;; ++i)
1053 if (Ops[i] == AddRec) {
1054 Ops[i] = NewRec;
1055 break;
1056 }
Dan Gohman89f85052007-10-22 18:31:58 +00001057 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 }
1059
1060 // Okay, if there weren't any loop invariants to be folded, check to see if
1061 // there are multiple AddRec's with the same loop induction variable being
1062 // multiplied together. If so, we can fold them.
1063 for (unsigned OtherIdx = Idx+1;
1064 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1065 if (OtherIdx != Idx) {
1066 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1067 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1068 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1069 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001070 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001072 SCEVHandle B = F->getStepRecurrence(*this);
1073 SCEVHandle D = G->getStepRecurrence(*this);
1074 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1075 getMulExpr(G, B),
1076 getMulExpr(B, D));
1077 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1078 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 if (Ops.size() == 2) return NewAddRec;
1080
1081 Ops.erase(Ops.begin()+Idx);
1082 Ops.erase(Ops.begin()+OtherIdx-1);
1083 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001084 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 }
1086 }
1087
1088 // Otherwise couldn't fold anything into this recurrence. Move onto the
1089 // next one.
1090 }
1091
1092 // Okay, it looks like we really DO need an mul expr. Check to see if we
1093 // already have one, otherwise create a new one.
1094 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1095 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1096 SCEVOps)];
1097 if (Result == 0)
1098 Result = new SCEVMulExpr(Ops);
1099 return Result;
1100}
1101
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001102SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1104 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001105 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106
1107 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1108 Constant *LHSCV = LHSC->getValue();
1109 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001110 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 }
1112 }
1113
Nick Lewycky35b56022009-01-13 09:18:58 +00001114 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1115
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001116 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1117 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 return Result;
1119}
1120
1121
1122/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1123/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001124SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 const SCEVHandle &Step, const Loop *L) {
1126 std::vector<SCEVHandle> Operands;
1127 Operands.push_back(Start);
1128 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1129 if (StepChrec->getLoop() == L) {
1130 Operands.insert(Operands.end(), StepChrec->op_begin(),
1131 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001132 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 }
1134
1135 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001136 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137}
1138
1139/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1140/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001141SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 const Loop *L) {
1143 if (Operands.size() == 1) return Operands[0];
1144
Dan Gohman7b560c42008-06-18 16:23:07 +00001145 if (Operands.back()->isZero()) {
1146 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001147 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001148 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149
Dan Gohman42936882008-08-08 18:33:12 +00001150 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1151 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1152 const Loop* NestedLoop = NestedAR->getLoop();
1153 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1154 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1155 NestedAR->op_end());
1156 SCEVHandle NestedARHandle(NestedAR);
1157 Operands[0] = NestedAR->getStart();
1158 NestedOperands[0] = getAddRecExpr(Operands, L);
1159 return getAddRecExpr(NestedOperands, NestedLoop);
1160 }
1161 }
1162
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 SCEVAddRecExpr *&Result =
1164 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1165 Operands.end()))];
1166 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1167 return Result;
1168}
1169
Nick Lewycky711640a2007-11-25 22:41:31 +00001170SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1171 const SCEVHandle &RHS) {
1172 std::vector<SCEVHandle> Ops;
1173 Ops.push_back(LHS);
1174 Ops.push_back(RHS);
1175 return getSMaxExpr(Ops);
1176}
1177
1178SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1179 assert(!Ops.empty() && "Cannot get empty smax!");
1180 if (Ops.size() == 1) return Ops[0];
1181
1182 // Sort by complexity, this groups all similar expression types together.
1183 GroupByComplexity(Ops);
1184
1185 // If there are any constants, fold them together.
1186 unsigned Idx = 0;
1187 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1188 ++Idx;
1189 assert(Idx < Ops.size());
1190 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1191 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001192 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001193 APIntOps::smax(LHSC->getValue()->getValue(),
1194 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001195 Ops[0] = getConstant(Fold);
1196 Ops.erase(Ops.begin()+1); // Erase the folded element
1197 if (Ops.size() == 1) return Ops[0];
1198 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001199 }
1200
1201 // If we are left with a constant -inf, strip it off.
1202 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1203 Ops.erase(Ops.begin());
1204 --Idx;
1205 }
1206 }
1207
1208 if (Ops.size() == 1) return Ops[0];
1209
1210 // Find the first SMax
1211 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1212 ++Idx;
1213
1214 // Check to see if one of the operands is an SMax. If so, expand its operands
1215 // onto our operand list, and recurse to simplify.
1216 if (Idx < Ops.size()) {
1217 bool DeletedSMax = false;
1218 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1219 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1220 Ops.erase(Ops.begin()+Idx);
1221 DeletedSMax = true;
1222 }
1223
1224 if (DeletedSMax)
1225 return getSMaxExpr(Ops);
1226 }
1227
1228 // Okay, check to see if the same value occurs in the operand list twice. If
1229 // so, delete one. Since we sorted the list, these values are required to
1230 // be adjacent.
1231 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1232 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1233 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1234 --i; --e;
1235 }
1236
1237 if (Ops.size() == 1) return Ops[0];
1238
1239 assert(!Ops.empty() && "Reduced smax down to nothing!");
1240
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001241 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001242 // already have one, otherwise create a new one.
1243 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1244 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1245 SCEVOps)];
1246 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1247 return Result;
1248}
1249
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001250SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1251 const SCEVHandle &RHS) {
1252 std::vector<SCEVHandle> Ops;
1253 Ops.push_back(LHS);
1254 Ops.push_back(RHS);
1255 return getUMaxExpr(Ops);
1256}
1257
1258SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1259 assert(!Ops.empty() && "Cannot get empty umax!");
1260 if (Ops.size() == 1) return Ops[0];
1261
1262 // Sort by complexity, this groups all similar expression types together.
1263 GroupByComplexity(Ops);
1264
1265 // If there are any constants, fold them together.
1266 unsigned Idx = 0;
1267 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1268 ++Idx;
1269 assert(Idx < Ops.size());
1270 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1271 // We found two constants, fold them together!
1272 ConstantInt *Fold = ConstantInt::get(
1273 APIntOps::umax(LHSC->getValue()->getValue(),
1274 RHSC->getValue()->getValue()));
1275 Ops[0] = getConstant(Fold);
1276 Ops.erase(Ops.begin()+1); // Erase the folded element
1277 if (Ops.size() == 1) return Ops[0];
1278 LHSC = cast<SCEVConstant>(Ops[0]);
1279 }
1280
1281 // If we are left with a constant zero, strip it off.
1282 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1283 Ops.erase(Ops.begin());
1284 --Idx;
1285 }
1286 }
1287
1288 if (Ops.size() == 1) return Ops[0];
1289
1290 // Find the first UMax
1291 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1292 ++Idx;
1293
1294 // Check to see if one of the operands is a UMax. If so, expand its operands
1295 // onto our operand list, and recurse to simplify.
1296 if (Idx < Ops.size()) {
1297 bool DeletedUMax = false;
1298 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1299 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1300 Ops.erase(Ops.begin()+Idx);
1301 DeletedUMax = true;
1302 }
1303
1304 if (DeletedUMax)
1305 return getUMaxExpr(Ops);
1306 }
1307
1308 // Okay, check to see if the same value occurs in the operand list twice. If
1309 // so, delete one. Since we sorted the list, these values are required to
1310 // be adjacent.
1311 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1312 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1313 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1314 --i; --e;
1315 }
1316
1317 if (Ops.size() == 1) return Ops[0];
1318
1319 assert(!Ops.empty() && "Reduced umax down to nothing!");
1320
1321 // Okay, it looks like we really DO need a umax expr. Check to see if we
1322 // already have one, otherwise create a new one.
1323 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1324 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1325 SCEVOps)];
1326 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1327 return Result;
1328}
1329
Dan Gohman89f85052007-10-22 18:31:58 +00001330SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001332 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001333 if (isa<ConstantPointerNull>(V))
1334 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1336 if (Result == 0) Result = new SCEVUnknown(V);
1337 return Result;
1338}
1339
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340//===----------------------------------------------------------------------===//
1341// ScalarEvolutionsImpl Definition and Implementation
1342//===----------------------------------------------------------------------===//
1343//
1344/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1345/// evolution code.
1346///
1347namespace {
1348 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001349 /// SE - A reference to the public ScalarEvolution object.
1350 ScalarEvolution &SE;
1351
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 /// F - The function we are analyzing.
1353 ///
1354 Function &F;
1355
1356 /// LI - The loop information for the function we are currently analyzing.
1357 ///
1358 LoopInfo &LI;
1359
Dan Gohman01c2ee72009-04-16 03:18:22 +00001360 /// TD - The target data information for the target we are targetting.
1361 ///
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001362 TargetData *TD;
Dan Gohman01c2ee72009-04-16 03:18:22 +00001363
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1365 /// things.
1366 SCEVHandle UnknownValue;
1367
1368 /// Scalars - This is a cache of the scalars we have analyzed so far.
1369 ///
1370 std::map<Value*, SCEVHandle> Scalars;
1371
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001372 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
1373 /// this function as they are computed.
1374 std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001375
1376 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1377 /// the PHI instructions that we attempt to compute constant evolutions for.
1378 /// This allows us to avoid potentially expensive recomputation of these
1379 /// properties. An instruction maps to null if we are unable to compute its
1380 /// exit value.
1381 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1382
1383 public:
Dan Gohman01c2ee72009-04-16 03:18:22 +00001384 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li,
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001385 TargetData *td)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001386 : SE(se), F(f), LI(li), TD(td), UnknownValue(new SCEVCouldNotCompute()) {}
1387
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001388 /// isSCEVable - Test if values of the given type are analyzable within
1389 /// the SCEV framework. This primarily includes integer types, and it
1390 /// can optionally include pointer types if the ScalarEvolution class
1391 /// has access to target-specific information.
1392 bool isSCEVable(const Type *Ty) const;
1393
1394 /// getTypeSizeInBits - Return the size in bits of the specified type,
1395 /// for which isSCEVable must return true.
1396 uint64_t getTypeSizeInBits(const Type *Ty) const;
1397
1398 /// getEffectiveSCEVType - Return a type with the same bitwidth as
1399 /// the given type and which represents how SCEV will treat the given
1400 /// type, for which isSCEVable must return true. For pointer types,
1401 /// this is the pointer-sized integer type.
1402 const Type *getEffectiveSCEVType(const Type *Ty) const;
1403
Dan Gohman0ad08b02009-04-18 17:58:19 +00001404 SCEVHandle getCouldNotCompute();
1405
Dan Gohman01c2ee72009-04-16 03:18:22 +00001406 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1407 /// specified signed integer value and return a SCEV for the constant.
1408 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
1409
1410 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1411 ///
1412 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
1413
1414 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1415 ///
1416 SCEVHandle getNotSCEV(const SCEVHandle &V);
1417
1418 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1419 ///
1420 SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS);
1421
1422 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
1423 /// of the input value to the specified type. If the type must be extended,
1424 /// it is zero extended.
1425 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
1426
1427 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
1428 /// of the input value to the specified type. If the type must be extended,
1429 /// it is sign extended.
1430 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431
1432 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1433 /// expression and create a new one.
1434 SCEVHandle getSCEV(Value *V);
1435
1436 /// hasSCEV - Return true if the SCEV for this value has already been
1437 /// computed.
1438 bool hasSCEV(Value *V) const {
1439 return Scalars.count(V);
1440 }
1441
1442 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1443 /// the specified value.
1444 void setSCEV(Value *V, const SCEVHandle &H) {
1445 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1446 assert(isNew && "This entry already existed!");
Devang Patelfc736502008-11-11 19:17:41 +00001447 isNew = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 }
1449
1450
1451 /// getSCEVAtScope - Compute the value of the specified expression within
1452 /// the indicated loop (which may be null to indicate in no loop). If the
1453 /// expression cannot be evaluated, return UnknownValue itself.
1454 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1455
1456
Dan Gohmancacd2012009-02-12 22:19:27 +00001457 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1458 /// a conditional between LHS and RHS.
1459 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1460 SCEV *LHS, SCEV *RHS);
1461
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001462 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
1463 /// has an analyzable loop-invariant backedge-taken count.
1464 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001465
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001466 /// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001467 /// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001468 /// ScalarEvolution's ability to compute a trip count, or if the loop
1469 /// is deleted.
1470 void forgetLoopBackedgeTakenCount(const Loop *L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001471
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001472 /// getBackedgeTakenCount - If the specified loop has a predictable
1473 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1474 /// object. The backedge-taken count is the number of times the loop header
1475 /// will be branched to from within the loop. This is one less than the
1476 /// trip count of the loop, since it doesn't count the first iteration,
1477 /// when the header is branched to from outside the loop.
1478 ///
1479 /// Note that it is not valid to call this method on a loop without a
1480 /// loop-invariant backedge-taken count (see
1481 /// hasLoopInvariantBackedgeTakenCount).
1482 ///
1483 SCEVHandle getBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484
1485 /// deleteValueFromRecords - This method should be called by the
1486 /// client before it removes a value from the program, to make sure
1487 /// that no dangling references are left around.
1488 void deleteValueFromRecords(Value *V);
1489
1490 private:
1491 /// createSCEV - We know that there is no SCEV for the specified value.
1492 /// Analyze the expression.
1493 SCEVHandle createSCEV(Value *V);
1494
1495 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1496 /// SCEVs.
1497 SCEVHandle createNodeForPHI(PHINode *PN);
1498
1499 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1500 /// for the specified instruction and replaces any references to the
1501 /// symbolic value SymName with the specified value. This is used during
1502 /// PHI resolution.
1503 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1504 const SCEVHandle &SymName,
1505 const SCEVHandle &NewVal);
1506
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001507 /// ComputeBackedgeTakenCount - Compute the number of times the specified
1508 /// loop will iterate.
1509 SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001510
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001511 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
1512 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
1513 SCEVHandle
1514 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
1515 Constant *RHS,
1516 const Loop *L,
1517 ICmpInst::Predicate p);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001519 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
1520 /// a constant number of times (the condition evolves only from constants),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 /// try to evaluate a few iterations of the loop until we get the exit
1522 /// condition gets a value of ExitWhen (true or false). If we cannot
1523 /// evaluate the trip count of the loop, return UnknownValue.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001524 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
1525 bool ExitWhen);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526
1527 /// HowFarToZero - Return the number of times a backedge comparing the
1528 /// specified value to zero will execute. If not computable, return
1529 /// UnknownValue.
1530 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1531
1532 /// HowFarToNonZero - Return the number of times a backedge checking the
1533 /// specified value for nonzero will execute. If not computable, return
1534 /// UnknownValue.
1535 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1536
1537 /// HowManyLessThans - Return the number of times a backedge containing the
1538 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001539 /// UnknownValue. isSigned specifies whether the less-than is signed.
1540 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewycky35b56022009-01-13 09:18:58 +00001541 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542
Dan Gohman1cddf972008-09-15 22:18:04 +00001543 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1544 /// (which may not be an immediate predecessor) which has exactly one
1545 /// successor from which BB is reachable, or null if no such block is
1546 /// found.
1547 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1548
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1550 /// in the header of its containing loop, we know the loop executes a
1551 /// constant number of times, and the PHI node is just a recurrence
1552 /// involving constants, fold it.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001553 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554 const Loop *L);
1555 };
1556}
1557
1558//===----------------------------------------------------------------------===//
1559// Basic SCEV Analysis and PHI Idiom Recognition Code
1560//
1561
1562/// deleteValueFromRecords - This method should be called by the
1563/// client before it removes an instruction from the program, to make sure
1564/// that no dangling references are left around.
1565void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1566 SmallVector<Value *, 16> Worklist;
1567
1568 if (Scalars.erase(V)) {
1569 if (PHINode *PN = dyn_cast<PHINode>(V))
1570 ConstantEvolutionLoopExitValue.erase(PN);
1571 Worklist.push_back(V);
1572 }
1573
1574 while (!Worklist.empty()) {
1575 Value *VV = Worklist.back();
1576 Worklist.pop_back();
1577
1578 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1579 UI != UE; ++UI) {
1580 Instruction *Inst = cast<Instruction>(*UI);
1581 if (Scalars.erase(Inst)) {
1582 if (PHINode *PN = dyn_cast<PHINode>(VV))
1583 ConstantEvolutionLoopExitValue.erase(PN);
1584 Worklist.push_back(Inst);
1585 }
1586 }
1587 }
1588}
1589
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001590/// isSCEVable - Test if values of the given type are analyzable within
1591/// the SCEV framework. This primarily includes integer types, and it
1592/// can optionally include pointer types if the ScalarEvolution class
1593/// has access to target-specific information.
1594bool ScalarEvolutionsImpl::isSCEVable(const Type *Ty) const {
1595 // Integers are always SCEVable.
1596 if (Ty->isInteger())
1597 return true;
1598
1599 // Pointers are SCEVable if TargetData information is available
1600 // to provide pointer size information.
1601 if (isa<PointerType>(Ty))
1602 return TD != NULL;
1603
1604 // Otherwise it's not SCEVable.
1605 return false;
1606}
1607
1608/// getTypeSizeInBits - Return the size in bits of the specified type,
1609/// for which isSCEVable must return true.
1610uint64_t ScalarEvolutionsImpl::getTypeSizeInBits(const Type *Ty) const {
1611 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1612
1613 // If we have a TargetData, use it!
1614 if (TD)
1615 return TD->getTypeSizeInBits(Ty);
1616
1617 // Otherwise, we support only integer types.
1618 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1619 return Ty->getPrimitiveSizeInBits();
1620}
1621
1622/// getEffectiveSCEVType - Return a type with the same bitwidth as
1623/// the given type and which represents how SCEV will treat the given
1624/// type, for which isSCEVable must return true. For pointer types,
1625/// this is the pointer-sized integer type.
1626const Type *ScalarEvolutionsImpl::getEffectiveSCEVType(const Type *Ty) const {
1627 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1628
1629 if (Ty->isInteger())
1630 return Ty;
1631
1632 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1633 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001634}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001635
Dan Gohman0ad08b02009-04-18 17:58:19 +00001636SCEVHandle ScalarEvolutionsImpl::getCouldNotCompute() {
1637 return UnknownValue;
1638}
1639
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001640/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1641/// expression and create a new one.
1642SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001643 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001644
1645 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1646 if (I != Scalars.end()) return I->second;
1647 SCEVHandle S = createSCEV(V);
1648 Scalars.insert(std::make_pair(V, S));
1649 return S;
1650}
1651
Dan Gohman01c2ee72009-04-16 03:18:22 +00001652/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1653/// specified signed integer value and return a SCEV for the constant.
1654SCEVHandle ScalarEvolutionsImpl::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001655 Ty = SE.getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001656 Constant *C;
1657 if (Val == 0)
1658 C = Constant::getNullValue(Ty);
1659 else if (Ty->isFloatingPoint())
1660 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1661 APFloat::IEEEdouble, Val));
1662 else
1663 C = ConstantInt::get(Ty, Val);
1664 return SE.getUnknown(C);
1665}
1666
1667/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1668///
1669SCEVHandle ScalarEvolutionsImpl::getNegativeSCEV(const SCEVHandle &V) {
1670 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1671 return SE.getUnknown(ConstantExpr::getNeg(VC->getValue()));
1672
1673 const Type *Ty = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001674 Ty = SE.getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001675 return SE.getMulExpr(V, SE.getConstant(ConstantInt::getAllOnesValue(Ty)));
1676}
1677
1678/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1679SCEVHandle ScalarEvolutionsImpl::getNotSCEV(const SCEVHandle &V) {
1680 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1681 return SE.getUnknown(ConstantExpr::getNot(VC->getValue()));
1682
1683 const Type *Ty = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001684 Ty = SE.getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001685 SCEVHandle AllOnes = SE.getConstant(ConstantInt::getAllOnesValue(Ty));
1686 return getMinusSCEV(AllOnes, V);
1687}
1688
1689/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1690///
1691SCEVHandle ScalarEvolutionsImpl::getMinusSCEV(const SCEVHandle &LHS,
1692 const SCEVHandle &RHS) {
1693 // X - Y --> X + -Y
1694 return SE.getAddExpr(LHS, SE.getNegativeSCEV(RHS));
1695}
1696
1697/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1698/// input value to the specified type. If the type must be extended, it is zero
1699/// extended.
1700SCEVHandle
1701ScalarEvolutionsImpl::getTruncateOrZeroExtend(const SCEVHandle &V,
1702 const Type *Ty) {
1703 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001704 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1705 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001706 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001707 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001708 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001709 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001710 return SE.getTruncateExpr(V, Ty);
1711 return SE.getZeroExtendExpr(V, Ty);
1712}
1713
1714/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1715/// input value to the specified type. If the type must be extended, it is sign
1716/// extended.
1717SCEVHandle
1718ScalarEvolutionsImpl::getTruncateOrSignExtend(const SCEVHandle &V,
1719 const Type *Ty) {
1720 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001721 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1722 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001723 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001724 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001725 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001726 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001727 return SE.getTruncateExpr(V, Ty);
1728 return SE.getSignExtendExpr(V, Ty);
1729}
1730
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1732/// the specified instruction and replaces any references to the symbolic value
1733/// SymName with the specified value. This is used during PHI resolution.
1734void ScalarEvolutionsImpl::
1735ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1736 const SCEVHandle &NewVal) {
1737 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1738 if (SI == Scalars.end()) return;
1739
1740 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001741 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001742 if (NV == SI->second) return; // No change.
1743
1744 SI->second = NV; // Update the scalars map!
1745
1746 // Any instruction values that use this instruction might also need to be
1747 // updated!
1748 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1749 UI != E; ++UI)
1750 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1751}
1752
1753/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1754/// a loop header, making it a potential recurrence, or it doesn't.
1755///
1756SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1757 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1758 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1759 if (L->getHeader() == PN->getParent()) {
1760 // If it lives in the loop header, it has two incoming values, one
1761 // from outside the loop, and one from inside.
1762 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1763 unsigned BackEdge = IncomingEdge^1;
1764
1765 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001766 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001767 assert(Scalars.find(PN) == Scalars.end() &&
1768 "PHI node already processed?");
1769 Scalars.insert(std::make_pair(PN, SymbolicName));
1770
1771 // Using this symbolic name for the PHI, analyze the value coming around
1772 // the back-edge.
1773 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1774
1775 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1776 // has a special value for the first iteration of the loop.
1777
1778 // If the value coming around the backedge is an add with the symbolic
1779 // value we just inserted, then we found a simple induction variable!
1780 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1781 // If there is a single occurrence of the symbolic value, replace it
1782 // with a recurrence.
1783 unsigned FoundIndex = Add->getNumOperands();
1784 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1785 if (Add->getOperand(i) == SymbolicName)
1786 if (FoundIndex == e) {
1787 FoundIndex = i;
1788 break;
1789 }
1790
1791 if (FoundIndex != Add->getNumOperands()) {
1792 // Create an add with everything but the specified operand.
1793 std::vector<SCEVHandle> Ops;
1794 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1795 if (i != FoundIndex)
1796 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001797 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798
1799 // This is not a valid addrec if the step amount is varying each
1800 // loop iteration, but is not itself an addrec in this loop.
1801 if (Accum->isLoopInvariant(L) ||
1802 (isa<SCEVAddRecExpr>(Accum) &&
1803 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1804 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001805 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001806
1807 // Okay, for the entire analysis of this edge we assumed the PHI
1808 // to be symbolic. We now need to go back and update all of the
1809 // entries for the scalars that use the PHI (except for the PHI
1810 // itself) to use the new analyzed value instead of the "symbolic"
1811 // value.
1812 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1813 return PHISCEV;
1814 }
1815 }
1816 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1817 // Otherwise, this could be a loop like this:
1818 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1819 // In this case, j = {1,+,1} and BEValue is j.
1820 // Because the other in-value of i (0) fits the evolution of BEValue
1821 // i really is an addrec evolution.
1822 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1823 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1824
1825 // If StartVal = j.start - j.stride, we can use StartVal as the
1826 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001827 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1828 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001829 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001830 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831
1832 // Okay, for the entire analysis of this edge we assumed the PHI
1833 // to be symbolic. We now need to go back and update all of the
1834 // entries for the scalars that use the PHI (except for the PHI
1835 // itself) to use the new analyzed value instead of the "symbolic"
1836 // value.
1837 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1838 return PHISCEV;
1839 }
1840 }
1841 }
1842
1843 return SymbolicName;
1844 }
1845
1846 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001847 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848}
1849
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001850/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1851/// guaranteed to end in (at every loop iteration). It is, at the same time,
1852/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1853/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001854static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001855 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001856 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001858 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001859 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1860 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001861
1862 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001863 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1864 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1865 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001866 }
1867
1868 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001869 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1870 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1871 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001872 }
1873
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001875 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001876 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001877 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001878 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001879 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880 }
1881
1882 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001883 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001884 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1885 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001886 for (unsigned i = 1, e = M->getNumOperands();
1887 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001888 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001889 BitWidth);
1890 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001891 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001892
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001894 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001895 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001896 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001897 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001898 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001899 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001900
Nick Lewycky711640a2007-11-25 22:41:31 +00001901 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1902 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001903 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001904 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001905 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001906 return MinOpRes;
1907 }
1908
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001909 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1910 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001911 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001912 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001913 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001914 return MinOpRes;
1915 }
1916
Nick Lewycky35b56022009-01-13 09:18:58 +00001917 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001918 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919}
1920
1921/// createSCEV - We know that there is no SCEV for the specified value.
1922/// Analyze the expression.
1923///
1924SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001925 if (!isSCEVable(V->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00001926 return SE.getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001927
Dan Gohman3996f472008-06-22 19:56:46 +00001928 unsigned Opcode = Instruction::UserOp1;
1929 if (Instruction *I = dyn_cast<Instruction>(V))
1930 Opcode = I->getOpcode();
1931 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1932 Opcode = CE->getOpcode();
1933 else
1934 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001935
Dan Gohman3996f472008-06-22 19:56:46 +00001936 User *U = cast<User>(V);
1937 switch (Opcode) {
1938 case Instruction::Add:
1939 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1940 getSCEV(U->getOperand(1)));
1941 case Instruction::Mul:
1942 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1943 getSCEV(U->getOperand(1)));
1944 case Instruction::UDiv:
1945 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1946 getSCEV(U->getOperand(1)));
1947 case Instruction::Sub:
1948 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1949 getSCEV(U->getOperand(1)));
1950 case Instruction::Or:
1951 // If the RHS of the Or is a constant, we may have something like:
1952 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1953 // optimizations will transparently handle this case.
1954 //
1955 // In order for this transformation to be safe, the LHS must be of the
1956 // form X*(2^n) and the Or constant must be less than 2^n.
1957 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1958 SCEVHandle LHS = getSCEV(U->getOperand(0));
1959 const APInt &CIVal = CI->getValue();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001960 if (GetMinTrailingZeros(LHS, SE) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001961 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1962 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963 }
Dan Gohman3996f472008-06-22 19:56:46 +00001964 break;
1965 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001966 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001967 // If the RHS of the xor is a signbit, then this is just an add.
1968 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001969 if (CI->getValue().isSignBit())
1970 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1971 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001972
1973 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001974 else if (CI->isAllOnesValue())
1975 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1976 }
1977 break;
1978
1979 case Instruction::Shl:
1980 // Turn shift left of a constant amount into a multiply.
1981 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1982 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1983 Constant *X = ConstantInt::get(
1984 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1985 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1986 }
1987 break;
1988
Nick Lewycky7fd27892008-07-07 06:15:49 +00001989 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001990 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001991 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1992 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1993 Constant *X = ConstantInt::get(
1994 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1995 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1996 }
1997 break;
1998
Dan Gohman3996f472008-06-22 19:56:46 +00001999 case Instruction::Trunc:
2000 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
2001
2002 case Instruction::ZExt:
2003 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2004
2005 case Instruction::SExt:
2006 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
2007
2008 case Instruction::BitCast:
2009 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002010 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002011 return getSCEV(U->getOperand(0));
2012 break;
2013
Dan Gohman01c2ee72009-04-16 03:18:22 +00002014 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002015 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002016 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002017 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002018
2019 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002020 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002021 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2022 U->getType());
2023
2024 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002025 if (!TD) break; // Without TD we can't analyze pointers.
2026 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002027 Value *Base = U->getOperand(0);
2028 SCEVHandle TotalOffset = SE.getIntegerSCEV(0, IntPtrTy);
2029 gep_type_iterator GTI = gep_type_begin(U);
2030 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
2031 E = U->op_end();
2032 I != E; ++I) {
2033 Value *Index = *I;
2034 // Compute the (potentially symbolic) offset in bytes for this index.
2035 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2036 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002037 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002038 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2039 uint64_t Offset = SL.getElementOffset(FieldNo);
2040 TotalOffset = SE.getAddExpr(TotalOffset,
2041 SE.getIntegerSCEV(Offset, IntPtrTy));
2042 } else {
2043 // For an array, add the element offset, explicitly scaled.
2044 SCEVHandle LocalOffset = getSCEV(Index);
2045 if (!isa<PointerType>(LocalOffset->getType()))
2046 // Getelementptr indicies are signed.
2047 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2048 IntPtrTy);
2049 LocalOffset =
2050 SE.getMulExpr(LocalOffset,
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002051 SE.getIntegerSCEV(TD->getTypePaddedSize(*GTI),
Dan Gohman01c2ee72009-04-16 03:18:22 +00002052 IntPtrTy));
2053 TotalOffset = SE.getAddExpr(TotalOffset, LocalOffset);
2054 }
2055 }
2056 return SE.getAddExpr(getSCEV(Base), TotalOffset);
2057 }
2058
Dan Gohman3996f472008-06-22 19:56:46 +00002059 case Instruction::PHI:
2060 return createNodeForPHI(cast<PHINode>(U));
2061
2062 case Instruction::Select:
2063 // This could be a smax or umax that was lowered earlier.
2064 // Try to recover it.
2065 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2066 Value *LHS = ICI->getOperand(0);
2067 Value *RHS = ICI->getOperand(1);
2068 switch (ICI->getPredicate()) {
2069 case ICmpInst::ICMP_SLT:
2070 case ICmpInst::ICMP_SLE:
2071 std::swap(LHS, RHS);
2072 // fall through
2073 case ICmpInst::ICMP_SGT:
2074 case ICmpInst::ICMP_SGE:
2075 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2076 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2077 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002078 // ~smax(~x, ~y) == smin(x, y).
2079 return SE.getNotSCEV(SE.getSMaxExpr(
2080 SE.getNotSCEV(getSCEV(LHS)),
2081 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002082 break;
2083 case ICmpInst::ICMP_ULT:
2084 case ICmpInst::ICMP_ULE:
2085 std::swap(LHS, RHS);
2086 // fall through
2087 case ICmpInst::ICMP_UGT:
2088 case ICmpInst::ICMP_UGE:
2089 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2090 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2091 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2092 // ~umax(~x, ~y) == umin(x, y)
2093 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
2094 SE.getNotSCEV(getSCEV(RHS))));
2095 break;
2096 default:
2097 break;
2098 }
2099 }
2100
2101 default: // We cannot analyze this expression.
2102 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002103 }
2104
Dan Gohman89f85052007-10-22 18:31:58 +00002105 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002106}
2107
2108
2109
2110//===----------------------------------------------------------------------===//
2111// Iteration Count Computation Code
2112//
2113
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002114/// getBackedgeTakenCount - If the specified loop has a predictable
2115/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2116/// object. The backedge-taken count is the number of times the loop header
2117/// will be branched to from within the loop. This is one less than the
2118/// trip count of the loop, since it doesn't count the first iteration,
2119/// when the header is branched to from outside the loop.
2120///
2121/// Note that it is not valid to call this method on a loop without a
2122/// loop-invariant backedge-taken count (see
2123/// hasLoopInvariantBackedgeTakenCount).
2124///
2125SCEVHandle ScalarEvolutionsImpl::getBackedgeTakenCount(const Loop *L) {
2126 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
2127 if (I == BackedgeTakenCounts.end()) {
2128 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
2129 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130 if (ItCount != UnknownValue) {
2131 assert(ItCount->isLoopInvariant(L) &&
2132 "Computed trip count isn't loop invariant for loop!");
2133 ++NumTripCountsComputed;
2134 } else if (isa<PHINode>(L->getHeader()->begin())) {
2135 // Only count loops that have phi nodes as not being computable.
2136 ++NumTripCountsNotComputed;
2137 }
2138 }
2139 return I->second;
2140}
2141
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002142/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002143/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002144/// ScalarEvolution's ability to compute a trip count, or if the loop
2145/// is deleted.
2146void ScalarEvolutionsImpl::forgetLoopBackedgeTakenCount(const Loop *L) {
2147 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002148}
2149
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002150/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2151/// of the specified loop will execute.
2152SCEVHandle ScalarEvolutionsImpl::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002153 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002154 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 L->getExitBlocks(ExitBlocks);
2156 if (ExitBlocks.size() != 1) return UnknownValue;
2157
2158 // Okay, there is one exit block. Try to find the condition that causes the
2159 // loop to be exited.
2160 BasicBlock *ExitBlock = ExitBlocks[0];
2161
2162 BasicBlock *ExitingBlock = 0;
2163 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2164 PI != E; ++PI)
2165 if (L->contains(*PI)) {
2166 if (ExitingBlock == 0)
2167 ExitingBlock = *PI;
2168 else
2169 return UnknownValue; // More than one block exiting!
2170 }
2171 assert(ExitingBlock && "No exits from loop, something is broken!");
2172
2173 // Okay, we've computed the exiting block. See what condition causes us to
2174 // exit.
2175 //
2176 // FIXME: we should be able to handle switch instructions (with a single exit)
2177 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2178 if (ExitBr == 0) return UnknownValue;
2179 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2180
2181 // At this point, we know we have a conditional branch that determines whether
2182 // the loop is exited. However, we don't know if the branch is executed each
2183 // time through the loop. If not, then the execution count of the branch will
2184 // not be equal to the trip count of the loop.
2185 //
2186 // Currently we check for this by checking to see if the Exit branch goes to
2187 // the loop header. If so, we know it will always execute the same number of
2188 // times as the loop. We also handle the case where the exit block *is* the
2189 // loop header. This is common for un-rotated loops. More extensive analysis
2190 // could be done to handle more cases here.
2191 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2192 ExitBr->getSuccessor(1) != L->getHeader() &&
2193 ExitBr->getParent() != L->getHeader())
2194 return UnknownValue;
2195
2196 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2197
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002198 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002199 // Note that ICmpInst deals with pointer comparisons too so we must check
2200 // the type of the operand.
2201 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002202 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002203 ExitBr->getSuccessor(0) == ExitBlock);
2204
2205 // If the condition was exit on true, convert the condition to exit on false
2206 ICmpInst::Predicate Cond;
2207 if (ExitBr->getSuccessor(1) == ExitBlock)
2208 Cond = ExitCond->getPredicate();
2209 else
2210 Cond = ExitCond->getInversePredicate();
2211
2212 // Handle common loops like: for (X = "string"; *X; ++X)
2213 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2214 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2215 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002216 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002217 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2218 }
2219
2220 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2221 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2222
2223 // Try to evaluate any dependencies out of the loop.
2224 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2225 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2226 Tmp = getSCEVAtScope(RHS, L);
2227 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2228
2229 // At this point, we would like to compute how many iterations of the
2230 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002231 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2232 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002233 std::swap(LHS, RHS);
2234 Cond = ICmpInst::getSwappedPredicate(Cond);
2235 }
2236
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002237 // If we have a comparison of a chrec against a constant, try to use value
2238 // ranges to answer this query.
2239 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2240 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2241 if (AddRec->getLoop() == L) {
2242 // Form the comparison range using the constant of the correct type so
2243 // that the ConstantRange class knows to do a signed or unsigned
2244 // comparison.
2245 ConstantInt *CompVal = RHSC->getValue();
2246 const Type *RealTy = ExitCond->getOperand(0)->getType();
2247 CompVal = dyn_cast<ConstantInt>(
2248 ConstantExpr::getBitCast(CompVal, RealTy));
2249 if (CompVal) {
2250 // Form the constant range.
2251 ConstantRange CompRange(
2252 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2253
Dan Gohman89f85052007-10-22 18:31:58 +00002254 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2256 }
2257 }
2258
2259 switch (Cond) {
2260 case ICmpInst::ICMP_NE: { // while (X != Y)
2261 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00002262 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2264 break;
2265 }
2266 case ICmpInst::ICMP_EQ: {
2267 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00002268 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2270 break;
2271 }
2272 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002273 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2275 break;
2276 }
2277 case ICmpInst::ICMP_SGT: {
Eli Friedman0dcd4ed2008-07-30 00:04:08 +00002278 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002279 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002280 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2281 break;
2282 }
2283 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002284 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002285 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2286 break;
2287 }
2288 case ICmpInst::ICMP_UGT: {
Dale Johannesend721b952008-04-20 16:58:57 +00002289 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002290 SE.getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2292 break;
2293 }
2294 default:
2295#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002296 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002297 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002298 errs() << "[unsigned] ";
2299 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002300 << Instruction::getOpcodeName(Instruction::ICmp)
2301 << " " << *RHS << "\n";
2302#endif
2303 break;
2304 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002305 return
2306 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2307 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002308}
2309
2310static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002311EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2312 ScalarEvolution &SE) {
2313 SCEVHandle InVal = SE.getConstant(C);
2314 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002315 assert(isa<SCEVConstant>(Val) &&
2316 "Evaluation of SCEV at constant didn't fold correctly?");
2317 return cast<SCEVConstant>(Val)->getValue();
2318}
2319
2320/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2321/// and a GEP expression (missing the pointer index) indexing into it, return
2322/// the addressed element of the initializer or null if the index expression is
2323/// invalid.
2324static Constant *
2325GetAddressedElementFromGlobal(GlobalVariable *GV,
2326 const std::vector<ConstantInt*> &Indices) {
2327 Constant *Init = GV->getInitializer();
2328 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2329 uint64_t Idx = Indices[i]->getZExtValue();
2330 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2331 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2332 Init = cast<Constant>(CS->getOperand(Idx));
2333 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2334 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2335 Init = cast<Constant>(CA->getOperand(Idx));
2336 } else if (isa<ConstantAggregateZero>(Init)) {
2337 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2338 assert(Idx < STy->getNumElements() && "Bad struct index!");
2339 Init = Constant::getNullValue(STy->getElementType(Idx));
2340 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2341 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2342 Init = Constant::getNullValue(ATy->getElementType());
2343 } else {
2344 assert(0 && "Unknown constant aggregate type!");
2345 }
2346 return 0;
2347 } else {
2348 return 0; // Unknown initializer type
2349 }
2350 }
2351 return Init;
2352}
2353
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002354/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2355/// 'icmp op load X, cst', try to see if we can compute the backedge
2356/// execution count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002357SCEVHandle ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002358ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2359 const Loop *L,
2360 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002361 if (LI->isVolatile()) return UnknownValue;
2362
2363 // Check to see if the loaded pointer is a getelementptr of a global.
2364 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2365 if (!GEP) return UnknownValue;
2366
2367 // Make sure that it is really a constant global we are gepping, with an
2368 // initializer, and make sure the first IDX is really 0.
2369 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2370 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2371 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2372 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2373 return UnknownValue;
2374
2375 // Okay, we allow one non-constant index into the GEP instruction.
2376 Value *VarIdx = 0;
2377 std::vector<ConstantInt*> Indexes;
2378 unsigned VarIdxNum = 0;
2379 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2380 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2381 Indexes.push_back(CI);
2382 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2383 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2384 VarIdx = GEP->getOperand(i);
2385 VarIdxNum = i-2;
2386 Indexes.push_back(0);
2387 }
2388
2389 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2390 // Check to see if X is a loop variant variable value now.
2391 SCEVHandle Idx = getSCEV(VarIdx);
2392 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2393 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2394
2395 // We can only recognize very limited forms of loop index expressions, in
2396 // particular, only affine AddRec's like {C1,+,C2}.
2397 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2398 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2399 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2400 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2401 return UnknownValue;
2402
2403 unsigned MaxSteps = MaxBruteForceIterations;
2404 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2405 ConstantInt *ItCst =
2406 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00002407 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002408
2409 // Form the GEP offset.
2410 Indexes[VarIdxNum] = Val;
2411
2412 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2413 if (Result == 0) break; // Cannot compute!
2414
2415 // Evaluate the condition for this iteration.
2416 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2417 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2418 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2419#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002420 errs() << "\n***\n*** Computed loop count " << *ItCst
2421 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2422 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423#endif
2424 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00002425 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002426 }
2427 }
2428 return UnknownValue;
2429}
2430
2431
2432/// CanConstantFold - Return true if we can constant fold an instruction of the
2433/// specified type, assuming that all operands were constants.
2434static bool CanConstantFold(const Instruction *I) {
2435 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2436 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2437 return true;
2438
2439 if (const CallInst *CI = dyn_cast<CallInst>(I))
2440 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002441 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002442 return false;
2443}
2444
2445/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2446/// in the loop that V is derived from. We allow arbitrary operations along the
2447/// way, but the operands of an operation must either be constants or a value
2448/// derived from a constant PHI. If this expression does not fit with these
2449/// constraints, return null.
2450static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2451 // If this is not an instruction, or if this is an instruction outside of the
2452 // loop, it can't be derived from a loop PHI.
2453 Instruction *I = dyn_cast<Instruction>(V);
2454 if (I == 0 || !L->contains(I->getParent())) return 0;
2455
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002456 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002457 if (L->getHeader() == I->getParent())
2458 return PN;
2459 else
2460 // We don't currently keep track of the control flow needed to evaluate
2461 // PHIs, so we cannot handle PHIs inside of loops.
2462 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002463 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002464
2465 // If we won't be able to constant fold this expression even if the operands
2466 // are constants, return early.
2467 if (!CanConstantFold(I)) return 0;
2468
2469 // Otherwise, we can evaluate this instruction if all of its operands are
2470 // constant or derived from a PHI node themselves.
2471 PHINode *PHI = 0;
2472 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2473 if (!(isa<Constant>(I->getOperand(Op)) ||
2474 isa<GlobalValue>(I->getOperand(Op)))) {
2475 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2476 if (P == 0) return 0; // Not evolving from PHI
2477 if (PHI == 0)
2478 PHI = P;
2479 else if (PHI != P)
2480 return 0; // Evolving from multiple different PHIs.
2481 }
2482
2483 // This is a expression evolving from a constant PHI!
2484 return PHI;
2485}
2486
2487/// EvaluateExpression - Given an expression that passes the
2488/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2489/// in the loop has the value PHIVal. If we can't fold this expression for some
2490/// reason, return null.
2491static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2492 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002493 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002494 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002495 Instruction *I = cast<Instruction>(V);
2496
2497 std::vector<Constant*> Operands;
2498 Operands.resize(I->getNumOperands());
2499
2500 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2501 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2502 if (Operands[i] == 0) return 0;
2503 }
2504
Chris Lattnerd6e56912007-12-10 22:53:04 +00002505 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2506 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2507 &Operands[0], Operands.size());
2508 else
2509 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2510 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511}
2512
2513/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2514/// in the header of its containing loop, we know the loop executes a
2515/// constant number of times, and the PHI node is just a recurrence
2516/// involving constants, fold it.
2517Constant *ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002518getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 std::map<PHINode*, Constant*>::iterator I =
2520 ConstantEvolutionLoopExitValue.find(PN);
2521 if (I != ConstantEvolutionLoopExitValue.end())
2522 return I->second;
2523
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002524 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2526
2527 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2528
2529 // Since the loop is canonicalized, the PHI node must have two entries. One
2530 // entry must be a constant (coming in from outside of the loop), and the
2531 // second must be derived from the same PHI.
2532 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2533 Constant *StartCST =
2534 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2535 if (StartCST == 0)
2536 return RetVal = 0; // Must be a constant.
2537
2538 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2539 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2540 if (PN2 != PN)
2541 return RetVal = 0; // Not derived from same PHI.
2542
2543 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002544 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002545 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2546
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002547 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548 unsigned IterationNum = 0;
2549 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2550 if (IterationNum == NumIterations)
2551 return RetVal = PHIVal; // Got exit value!
2552
2553 // Compute the value of the PHI node for the next iteration.
2554 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2555 if (NextPHI == PHIVal)
2556 return RetVal = NextPHI; // Stopped evolving!
2557 if (NextPHI == 0)
2558 return 0; // Couldn't evaluate!
2559 PHIVal = NextPHI;
2560 }
2561}
2562
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002563/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002564/// constant number of times (the condition evolves only from constants),
2565/// try to evaluate a few iterations of the loop until we get the exit
2566/// condition gets a value of ExitWhen (true or false). If we cannot
2567/// evaluate the trip count of the loop, return UnknownValue.
2568SCEVHandle ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002569ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002570 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2571 if (PN == 0) return UnknownValue;
2572
2573 // Since the loop is canonicalized, the PHI node must have two entries. One
2574 // entry must be a constant (coming in from outside of the loop), and the
2575 // second must be derived from the same PHI.
2576 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2577 Constant *StartCST =
2578 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2579 if (StartCST == 0) return UnknownValue; // Must be a constant.
2580
2581 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2582 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2583 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2584
2585 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2586 // the loop symbolically to determine when the condition gets a value of
2587 // "ExitWhen".
2588 unsigned IterationNum = 0;
2589 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2590 for (Constant *PHIVal = StartCST;
2591 IterationNum != MaxIterations; ++IterationNum) {
2592 ConstantInt *CondVal =
2593 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2594
2595 // Couldn't symbolically evaluate.
2596 if (!CondVal) return UnknownValue;
2597
2598 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2599 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2600 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002601 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602 }
2603
2604 // Compute the value of the PHI node for the next iteration.
2605 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2606 if (NextPHI == 0 || NextPHI == PHIVal)
2607 return UnknownValue; // Couldn't evaluate or not making progress...
2608 PHIVal = NextPHI;
2609 }
2610
2611 // Too many iterations were needed to evaluate.
2612 return UnknownValue;
2613}
2614
2615/// getSCEVAtScope - Compute the value of the specified expression within the
2616/// indicated loop (which may be null to indicate in no loop). If the
2617/// expression cannot be evaluated, return UnknownValue.
2618SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2619 // FIXME: this should be turned into a virtual method on SCEV!
2620
2621 if (isa<SCEVConstant>(V)) return V;
2622
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002623 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002624 // exit value from the loop without using SCEVs.
2625 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2626 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2627 const Loop *LI = this->LI[I->getParent()];
2628 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2629 if (PHINode *PN = dyn_cast<PHINode>(I))
2630 if (PN->getParent() == LI->getHeader()) {
2631 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002632 // to see if the loop that contains it has a known backedge-taken
2633 // count. If so, we may be able to force computation of the exit
2634 // value.
2635 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2636 if (SCEVConstant *BTCC =
2637 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 // Okay, we know how many times the containing loop executes. If
2639 // this is a constant evolving PHI node, get the final value at
2640 // the specified iteration number.
2641 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002642 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002643 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002644 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645 }
2646 }
2647
2648 // Okay, this is an expression that we cannot symbolically evaluate
2649 // into a SCEV. Check to see if it's possible to symbolically evaluate
2650 // the arguments into constants, and if so, try to constant propagate the
2651 // result. This is particularly useful for computing loop exit values.
2652 if (CanConstantFold(I)) {
2653 std::vector<Constant*> Operands;
2654 Operands.reserve(I->getNumOperands());
2655 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2656 Value *Op = I->getOperand(i);
2657 if (Constant *C = dyn_cast<Constant>(Op)) {
2658 Operands.push_back(C);
2659 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002660 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002661 // non-integer and non-pointer, don't even try to analyze them
2662 // with scev techniques.
2663 if (!isa<IntegerType>(Op->getType()) &&
2664 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002665 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002666
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002667 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2668 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2669 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2670 Op->getType(),
2671 false));
2672 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2673 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2674 Operands.push_back(ConstantExpr::getIntegerCast(C,
2675 Op->getType(),
2676 false));
2677 else
2678 return V;
2679 } else {
2680 return V;
2681 }
2682 }
2683 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002684
2685 Constant *C;
2686 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2687 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2688 &Operands[0], Operands.size());
2689 else
2690 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2691 &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002692 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002693 }
2694 }
2695
2696 // This is some other type of SCEVUnknown, just return it.
2697 return V;
2698 }
2699
2700 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2701 // Avoid performing the look-up in the common case where the specified
2702 // expression has no loop-variant portions.
2703 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2704 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2705 if (OpAtScope != Comm->getOperand(i)) {
2706 if (OpAtScope == UnknownValue) return UnknownValue;
2707 // Okay, at least one of these operands is loop variant but might be
2708 // foldable. Build a new instance of the folded commutative expression.
2709 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2710 NewOps.push_back(OpAtScope);
2711
2712 for (++i; i != e; ++i) {
2713 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2714 if (OpAtScope == UnknownValue) return UnknownValue;
2715 NewOps.push_back(OpAtScope);
2716 }
2717 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002718 return SE.getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002719 if (isa<SCEVMulExpr>(Comm))
2720 return SE.getMulExpr(NewOps);
2721 if (isa<SCEVSMaxExpr>(Comm))
2722 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002723 if (isa<SCEVUMaxExpr>(Comm))
2724 return SE.getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002725 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002726 }
2727 }
2728 // If we got here, all operands are loop invariant.
2729 return Comm;
2730 }
2731
Nick Lewycky35b56022009-01-13 09:18:58 +00002732 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2733 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002734 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002735 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002736 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002737 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2738 return Div; // must be loop invariant
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002739 return SE.getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002740 }
2741
2742 // If this is a loop recurrence for a loop that does not contain L, then we
2743 // are dealing with the final value computed by the loop.
2744 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2745 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2746 // To evaluate this recurrence, we need to know how many times the AddRec
2747 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002748 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2749 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002750
Eli Friedman7489ec92008-08-04 23:49:06 +00002751 // Then, evaluate the AddRec.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002752 return AddRec->evaluateAtIteration(BackedgeTakenCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 }
2754 return UnknownValue;
2755 }
2756
2757 //assert(0 && "Unknown SCEV type!");
2758 return UnknownValue;
2759}
2760
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002761/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2762/// following equation:
2763///
2764/// A * X = B (mod N)
2765///
2766/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2767/// A and B isn't important.
2768///
2769/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2770static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2771 ScalarEvolution &SE) {
2772 uint32_t BW = A.getBitWidth();
2773 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2774 assert(A != 0 && "A must be non-zero.");
2775
2776 // 1. D = gcd(A, N)
2777 //
2778 // The gcd of A and N may have only one prime factor: 2. The number of
2779 // trailing zeros in A is its multiplicity
2780 uint32_t Mult2 = A.countTrailingZeros();
2781 // D = 2^Mult2
2782
2783 // 2. Check if B is divisible by D.
2784 //
2785 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2786 // is not less than multiplicity of this prime factor for D.
2787 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002788 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002789
2790 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2791 // modulo (N / D).
2792 //
2793 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2794 // bit width during computations.
2795 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2796 APInt Mod(BW + 1, 0);
2797 Mod.set(BW - Mult2); // Mod = N / D
2798 APInt I = AD.multiplicativeInverse(Mod);
2799
2800 // 4. Compute the minimum unsigned root of the equation:
2801 // I * (B / D) mod (N / D)
2802 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2803
2804 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2805 // bits.
2806 return SE.getConstant(Result.trunc(BW));
2807}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002808
2809/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2810/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2811/// might be the same) or two SCEVCouldNotCompute objects.
2812///
2813static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002814SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002815 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2816 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2817 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2818 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2819
2820 // We currently can only solve this if the coefficients are constants.
2821 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002822 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002823 return std::make_pair(CNC, CNC);
2824 }
2825
2826 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2827 const APInt &L = LC->getValue()->getValue();
2828 const APInt &M = MC->getValue()->getValue();
2829 const APInt &N = NC->getValue()->getValue();
2830 APInt Two(BitWidth, 2);
2831 APInt Four(BitWidth, 4);
2832
2833 {
2834 using namespace APIntOps;
2835 const APInt& C = L;
2836 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2837 // The B coefficient is M-N/2
2838 APInt B(M);
2839 B -= sdiv(N,Two);
2840
2841 // The A coefficient is N/2
2842 APInt A(N.sdiv(Two));
2843
2844 // Compute the B^2-4ac term.
2845 APInt SqrtTerm(B);
2846 SqrtTerm *= B;
2847 SqrtTerm -= Four * (A * C);
2848
2849 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2850 // integer value or else APInt::sqrt() will assert.
2851 APInt SqrtVal(SqrtTerm.sqrt());
2852
2853 // Compute the two solutions for the quadratic formula.
2854 // The divisions must be performed as signed divisions.
2855 APInt NegB(-B);
2856 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002857 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002858 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002859 return std::make_pair(CNC, CNC);
2860 }
2861
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2863 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2864
Dan Gohman89f85052007-10-22 18:31:58 +00002865 return std::make_pair(SE.getConstant(Solution1),
2866 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867 } // end APIntOps namespace
2868}
2869
2870/// HowFarToZero - Return the number of times a backedge comparing the specified
2871/// value to zero will execute. If not computable, return UnknownValue
2872SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2873 // If the value is a constant
2874 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2875 // If the value is already zero, the branch will execute zero times.
2876 if (C->getValue()->isZero()) return C;
2877 return UnknownValue; // Otherwise it will loop infinitely.
2878 }
2879
2880 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2881 if (!AddRec || AddRec->getLoop() != L)
2882 return UnknownValue;
2883
2884 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002885 // If this is an affine expression, the execution count of this branch is
2886 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002887 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002888 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002889 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002890 // equivalent to:
2891 //
2892 // Step*N = -Start (mod 2^BW)
2893 //
2894 // where BW is the common bit width of Start and Step.
2895
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002896 // Get the initial value for the loop.
2897 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2898 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002899
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002900 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002901
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002902 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002903 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002904
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002905 // First, handle unitary steps.
2906 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2907 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2908 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2909 return Start; // N = Start (as unsigned)
2910
2911 // Then, try to solve the above equation provided that Start is constant.
2912 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2913 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2914 -StartC->getValue()->getValue(),SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002915 }
2916 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2917 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2918 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002919 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002920 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2921 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2922 if (R1) {
2923#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002924 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2925 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002926#endif
2927 // Pick the smallest positive root value.
2928 if (ConstantInt *CB =
2929 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2930 R1->getValue(), R2->getValue()))) {
2931 if (CB->getZExtValue() == false)
2932 std::swap(R1, R2); // R1 is the minimum root now.
2933
2934 // We can only use this value if the chrec ends up with an exact zero
2935 // value at this index. When solving for "X*X != 5", for example, we
2936 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002937 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohman7b560c42008-06-18 16:23:07 +00002938 if (Val->isZero())
2939 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940 }
2941 }
2942 }
2943
2944 return UnknownValue;
2945}
2946
2947/// HowFarToNonZero - Return the number of times a backedge checking the
2948/// specified value for nonzero will execute. If not computable, return
2949/// UnknownValue
2950SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2951 // Loops that look like: while (X == 0) are very strange indeed. We don't
2952 // handle them yet except for the trivial case. This could be expanded in the
2953 // future as needed.
2954
2955 // If the value is a constant, check to see if it is known to be non-zero
2956 // already. If so, the backedge will execute zero times.
2957 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002958 if (!C->getValue()->isNullValue())
2959 return SE.getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002960 return UnknownValue; // Otherwise it will loop infinitely.
2961 }
2962
2963 // We could implement others, but I really doubt anyone writes loops like
2964 // this, and if they did, they would already be constant folded.
2965 return UnknownValue;
2966}
2967
Dan Gohman1cddf972008-09-15 22:18:04 +00002968/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2969/// (which may not be an immediate predecessor) which has exactly one
2970/// successor from which BB is reachable, or null if no such block is
2971/// found.
2972///
2973BasicBlock *
2974ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2975 // If the block has a unique predecessor, the predecessor must have
2976 // no other successors from which BB is reachable.
2977 if (BasicBlock *Pred = BB->getSinglePredecessor())
2978 return Pred;
2979
2980 // A loop's header is defined to be a block that dominates the loop.
2981 // If the loop has a preheader, it must be a block that has exactly
2982 // one successor that can reach BB. This is slightly more strict
2983 // than necessary, but works if critical edges are split.
2984 if (Loop *L = LI.getLoopFor(BB))
2985 return L->getLoopPreheader();
2986
2987 return 0;
2988}
2989
Dan Gohmancacd2012009-02-12 22:19:27 +00002990/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002991/// a conditional between LHS and RHS.
Dan Gohmancacd2012009-02-12 22:19:27 +00002992bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2993 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002994 SCEV *LHS, SCEV *RHS) {
2995 BasicBlock *Preheader = L->getLoopPreheader();
2996 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002997
Dan Gohmanab678fb2008-08-12 20:17:31 +00002998 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002999 // there are predecessors that can be found that have unique successors
3000 // leading to the original header.
3001 for (; Preheader;
3002 PreheaderDest = Preheader,
3003 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003004
3005 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003006 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003007 if (!LoopEntryPredicate ||
3008 LoopEntryPredicate->isUnconditional())
3009 continue;
3010
3011 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3012 if (!ICI) continue;
3013
3014 // Now that we found a conditional branch that dominates the loop, check to
3015 // see if it is the comparison we are looking for.
3016 Value *PreCondLHS = ICI->getOperand(0);
3017 Value *PreCondRHS = ICI->getOperand(1);
3018 ICmpInst::Predicate Cond;
3019 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3020 Cond = ICI->getPredicate();
3021 else
3022 Cond = ICI->getInversePredicate();
3023
Dan Gohmancacd2012009-02-12 22:19:27 +00003024 if (Cond == Pred)
3025 ; // An exact match.
3026 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3027 ; // The actual condition is beyond sufficient.
3028 else
3029 // Check a few special cases.
3030 switch (Cond) {
3031 case ICmpInst::ICMP_UGT:
3032 if (Pred == ICmpInst::ICMP_ULT) {
3033 std::swap(PreCondLHS, PreCondRHS);
3034 Cond = ICmpInst::ICMP_ULT;
3035 break;
3036 }
3037 continue;
3038 case ICmpInst::ICMP_SGT:
3039 if (Pred == ICmpInst::ICMP_SLT) {
3040 std::swap(PreCondLHS, PreCondRHS);
3041 Cond = ICmpInst::ICMP_SLT;
3042 break;
3043 }
3044 continue;
3045 case ICmpInst::ICMP_NE:
3046 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3047 // so check for this case by checking if the NE is comparing against
3048 // a minimum or maximum constant.
3049 if (!ICmpInst::isTrueWhenEqual(Pred))
3050 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3051 const APInt &A = CI->getValue();
3052 switch (Pred) {
3053 case ICmpInst::ICMP_SLT:
3054 if (A.isMaxSignedValue()) break;
3055 continue;
3056 case ICmpInst::ICMP_SGT:
3057 if (A.isMinSignedValue()) break;
3058 continue;
3059 case ICmpInst::ICMP_ULT:
3060 if (A.isMaxValue()) break;
3061 continue;
3062 case ICmpInst::ICMP_UGT:
3063 if (A.isMinValue()) break;
3064 continue;
3065 default:
3066 continue;
3067 }
3068 Cond = ICmpInst::ICMP_NE;
3069 // NE is symmetric but the original comparison may not be. Swap
3070 // the operands if necessary so that they match below.
3071 if (isa<SCEVConstant>(LHS))
3072 std::swap(PreCondLHS, PreCondRHS);
3073 break;
3074 }
3075 continue;
3076 default:
3077 // We weren't able to reconcile the condition.
3078 continue;
3079 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003080
3081 if (!PreCondLHS->getType()->isInteger()) continue;
3082
3083 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3084 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3085 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3086 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
3087 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
3088 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003089 }
3090
Dan Gohmanab678fb2008-08-12 20:17:31 +00003091 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003092}
3093
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003094/// HowManyLessThans - Return the number of times a backedge containing the
3095/// specified less-than comparison will execute. If not computable, return
3096/// UnknownValue.
3097SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky35b56022009-01-13 09:18:58 +00003098HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003099 // Only handle: "ADDREC < LoopInvariant".
3100 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3101
3102 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3103 if (!AddRec || AddRec->getLoop() != L)
3104 return UnknownValue;
3105
3106 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003107 // FORNOW: We only support unit strides.
3108 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
3109 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003110 return UnknownValue;
3111
Nick Lewycky35b56022009-01-13 09:18:58 +00003112 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3113 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3114 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003115 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003116
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003117 // First, we get the value of the LHS in the first iteration: n
3118 SCEVHandle Start = AddRec->getOperand(0);
3119
Dan Gohmancacd2012009-02-12 22:19:27 +00003120 if (isLoopGuardedByCond(L,
3121 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Nick Lewycky35b56022009-01-13 09:18:58 +00003122 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
3123 // Since we know that the condition is true in order to enter the loop,
3124 // we know that it will run exactly m-n times.
3125 return SE.getMinusSCEV(RHS, Start);
3126 } else {
3127 // Then, we get the value of the LHS in the first iteration in which the
3128 // above condition doesn't hold. This equals to max(m,n).
3129 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
3130 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003131
Nick Lewycky35b56022009-01-13 09:18:58 +00003132 // Finally, we subtract these two values to get the number of times the
3133 // backedge is executed: max(m,n)-n.
3134 return SE.getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00003135 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003136 }
3137
3138 return UnknownValue;
3139}
3140
3141/// getNumIterationsInRange - Return the number of iterations of this loop that
3142/// produce values in the specified constant range. Another way of looking at
3143/// this is that it returns the first iteration number where the value is not in
3144/// the condition, thus computing the exit count. If the iteration count can't
3145/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003146SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3147 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003148 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003149 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003150
3151 // If the start is a non-zero constant, shift the range to simplify things.
3152 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3153 if (!SC->getValue()->isZero()) {
3154 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003155 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3156 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003157 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3158 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003159 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003161 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 }
3163
3164 // The only time we can solve this is when we have all constant indices.
3165 // Otherwise, we cannot determine the overflow conditions.
3166 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3167 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003168 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003169
3170
3171 // Okay at this point we know that all elements of the chrec are constants and
3172 // that the start element is zero.
3173
3174 // First check to see if the range contains zero. If not, the first
3175 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003176 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003177 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003178 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179
3180 if (isAffine()) {
3181 // If this is an affine expression then we have this situation:
3182 // Solve {0,+,A} in Range === Ax in Range
3183
3184 // We know that zero is in the range. If A is positive then we know that
3185 // the upper value of the range must be the first possible exit value.
3186 // If A is negative then the lower of the range is the last possible loop
3187 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003188 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003189 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3190 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3191
3192 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003193 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003194 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3195
3196 // Evaluate at the exit value. If we really did fall out of the valid
3197 // range, then we computed our trip count, otherwise wrap around or other
3198 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003199 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003200 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003201 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003202
3203 // Ensure that the previous value is in the range. This is a sanity check.
3204 assert(Range.contains(
3205 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003206 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003208 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003209 } else if (isQuadratic()) {
3210 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3211 // quadratic equation to solve it. To do this, we must frame our problem in
3212 // terms of figuring out when zero is crossed, instead of when
3213 // Range.getUpper() is crossed.
3214 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003215 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3216 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003217
3218 // Next, solve the constructed addrec
3219 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003220 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3222 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3223 if (R1) {
3224 // Pick the smallest positive root value.
3225 if (ConstantInt *CB =
3226 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3227 R1->getValue(), R2->getValue()))) {
3228 if (CB->getZExtValue() == false)
3229 std::swap(R1, R2); // R1 is the minimum root now.
3230
3231 // Make sure the root is not off by one. The returned iteration should
3232 // not be in the range, but the previous one should be. When solving
3233 // for "X*X < 5", for example, we should not return a root of 2.
3234 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003235 R1->getValue(),
3236 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003237 if (Range.contains(R1Val->getValue())) {
3238 // The next iteration must be out of the range...
3239 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3240
Dan Gohman89f85052007-10-22 18:31:58 +00003241 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003242 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003243 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003244 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003245 }
3246
3247 // If R1 was not in the range, then it is a good return value. Make
3248 // sure that R1-1 WAS in the range though, just in case.
3249 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003250 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003251 if (Range.contains(R1Val->getValue()))
3252 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003253 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254 }
3255 }
3256 }
3257
Dan Gohman0ad08b02009-04-18 17:58:19 +00003258 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259}
3260
3261
3262
3263//===----------------------------------------------------------------------===//
3264// ScalarEvolution Class Implementation
3265//===----------------------------------------------------------------------===//
3266
3267bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00003268 Impl = new ScalarEvolutionsImpl(*this, F,
3269 getAnalysis<LoopInfo>(),
Dan Gohman0eaa40e2009-04-21 01:11:19 +00003270 getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003271 return false;
3272}
3273
3274void ScalarEvolution::releaseMemory() {
3275 delete (ScalarEvolutionsImpl*)Impl;
3276 Impl = 0;
3277}
3278
3279void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3280 AU.setPreservesAll();
3281 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003282}
3283
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003284bool ScalarEvolution::isSCEVable(const Type *Ty) const {
3285 return ((ScalarEvolutionsImpl*)Impl)->isSCEVable(Ty);
3286}
3287
3288uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
3289 return ((ScalarEvolutionsImpl*)Impl)->getTypeSizeInBits(Ty);
3290}
3291
3292const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
3293 return ((ScalarEvolutionsImpl*)Impl)->getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00003294}
3295
Dan Gohman0ad08b02009-04-18 17:58:19 +00003296SCEVHandle ScalarEvolution::getCouldNotCompute() {
3297 return ((ScalarEvolutionsImpl*)Impl)->getCouldNotCompute();
3298}
3299
Dan Gohman01c2ee72009-04-16 03:18:22 +00003300SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
3301 return ((ScalarEvolutionsImpl*)Impl)->getIntegerSCEV(Val, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003302}
3303
3304SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3305 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3306}
3307
3308/// hasSCEV - Return true if the SCEV for this value has already been
3309/// computed.
3310bool ScalarEvolution::hasSCEV(Value *V) const {
3311 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3312}
3313
3314
3315/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3316/// the specified value.
3317void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3318 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3319}
3320
Dan Gohman01c2ee72009-04-16 03:18:22 +00003321/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3322///
3323SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
3324 return ((ScalarEvolutionsImpl*)Impl)->getNegativeSCEV(V);
3325}
3326
3327/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3328///
3329SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
3330 return ((ScalarEvolutionsImpl*)Impl)->getNotSCEV(V);
3331}
3332
3333/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
3334///
3335SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
3336 const SCEVHandle &RHS) {
3337 return ((ScalarEvolutionsImpl*)Impl)->getMinusSCEV(LHS, RHS);
3338}
3339
3340/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
3341/// of the input value to the specified type. If the type must be
3342/// extended, it is zero extended.
3343SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
3344 const Type *Ty) {
3345 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrZeroExtend(V, Ty);
3346}
3347
3348/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
3349/// of the input value to the specified type. If the type must be
3350/// extended, it is sign extended.
3351SCEVHandle ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
3352 const Type *Ty) {
3353 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrSignExtend(V, Ty);
3354}
3355
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356
Dan Gohmancacd2012009-02-12 22:19:27 +00003357bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3358 ICmpInst::Predicate Pred,
3359 SCEV *LHS, SCEV *RHS) {
3360 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3361 LHS, RHS);
3362}
3363
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003364SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) const {
3365 return ((ScalarEvolutionsImpl*)Impl)->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003366}
3367
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003368bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) const {
3369 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003370}
3371
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003372void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3373 return ((ScalarEvolutionsImpl*)Impl)->forgetLoopBackedgeTakenCount(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003374}
3375
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003376SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3377 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3378}
3379
3380void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3381 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3382}
3383
Dan Gohman13058cc2009-04-21 00:47:46 +00003384static void PrintLoopInfo(raw_ostream &OS, const ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003385 const Loop *L) {
3386 // Print all inner loops first
3387 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3388 PrintLoopInfo(OS, SE, *I);
3389
Nick Lewyckye5da1912008-01-02 02:49:20 +00003390 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391
Devang Patel02451fa2007-08-21 00:31:24 +00003392 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393 L->getExitBlocks(ExitBlocks);
3394 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003395 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003396
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003397 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3398 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003400 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003401 }
3402
Nick Lewyckye5da1912008-01-02 02:49:20 +00003403 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003404}
3405
Dan Gohman13058cc2009-04-21 00:47:46 +00003406void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003407 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3408 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3409
3410 OS << "Classifying expressions for: " << F.getName() << "\n";
3411 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3412 if (I->getType()->isInteger()) {
3413 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003414 OS << " --> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003415 SCEVHandle SV = getSCEV(&*I);
3416 SV->print(OS);
3417 OS << "\t\t";
3418
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3420 OS << "Exits: ";
3421 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3422 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3423 OS << "<<Unknown>>";
3424 } else {
3425 OS << *ExitValue;
3426 }
3427 }
3428
3429
3430 OS << "\n";
3431 }
3432
3433 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3434 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3435 PrintLoopInfo(OS, this, *I);
3436}
Dan Gohman13058cc2009-04-21 00:47:46 +00003437
3438void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3439 raw_os_ostream OS(o);
3440 print(OS, M);
3441}