blob: dcd6558d34b27f38f62f2374b87a65c6d31f87a6 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
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
Dan Gohman0bba49c2009-07-07 17:06:11 +000017// can handle. These classes are reference counted, managed by the const SCEV *
Chris Lattner53e677a2004-04-02 20:23:17 +000018// 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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// 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//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// 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
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
John Criswella1156432005-10-27 15:54:34 +000069#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000070#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000071#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000073#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000074#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000075#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000078#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000079#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000080#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000081#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000085#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000086#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000087using namespace llvm;
88
Chris Lattner3b27d682006-12-19 22:30:33 +000089STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohman844731a2008-05-13 00:00:25 +000098static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000101 "symbolically execute a constant "
102 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000103 cl::init(100));
104
Dan Gohman844731a2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000107char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000116
Chris Lattner53e677a2004-04-02 20:23:17 +0000117SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000118
Chris Lattner53e677a2004-04-02 20:23:17 +0000119void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000120 print(errs());
121 errs() << '\n';
122}
123
124void SCEV::print(std::ostream &o) const {
125 raw_os_ostream OS(o);
126 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000127}
128
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000129bool SCEV::isZero() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isZero();
132 return false;
133}
134
Dan Gohman70a1fe72009-05-18 15:22:39 +0000135bool SCEV::isOne() const {
136 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
137 return SC->getValue()->isOne();
138 return false;
139}
Chris Lattner53e677a2004-04-02 20:23:17 +0000140
Dan Gohman4d289bf2009-06-24 00:30:26 +0000141bool SCEV::isAllOnesValue() const {
142 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
143 return SC->getValue()->isAllOnesValue();
144 return false;
145}
146
Owen Anderson753ad612009-06-22 21:57:23 +0000147SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000148 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000149
Chris Lattner53e677a2004-04-02 20:23:17 +0000150bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000151 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000152 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000153}
154
155const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000156 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000157 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000158}
159
160bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000161 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000162 return false;
163}
164
Dan Gohman64a845e2009-06-24 04:48:43 +0000165const SCEV *
166SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
167 const SCEV *Sym,
168 const SCEV *Conc,
169 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000170 return this;
171}
172
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000173void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000174 OS << "***COULDNOTCOMPUTE***";
175}
176
177bool SCEVCouldNotCompute::classof(const SCEV *S) {
178 return S->getSCEVType() == scCouldNotCompute;
179}
180
Dan Gohman0bba49c2009-07-07 17:06:11 +0000181const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000182 FoldingSetNodeID ID;
183 ID.AddInteger(scConstant);
184 ID.AddPointer(V);
185 void *IP = 0;
186 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
187 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000188 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000189 UniqueSCEVs.InsertNode(S, IP);
190 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191}
Chris Lattner53e677a2004-04-02 20:23:17 +0000192
Dan Gohman0bba49c2009-07-07 17:06:11 +0000193const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman246b2562007-10-22 18:31:58 +0000194 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000195}
196
Dan Gohman0bba49c2009-07-07 17:06:11 +0000197const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000198ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000199 return getConstant(
200 Context->getConstantInt(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000201}
202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000204
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000205void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206 WriteAsOperand(OS, V, false);
207}
Chris Lattner53e677a2004-04-02 20:23:17 +0000208
Dan Gohmanc050fd92009-07-13 20:50:19 +0000209SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
210 unsigned SCEVTy, const SCEV *op, const Type *ty)
211 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000212
Dan Gohman84923602009-04-21 01:25:57 +0000213bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
214 return Op->dominates(BB, DT);
215}
216
Dan Gohmanc050fd92009-07-13 20:50:19 +0000217SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
218 const SCEV *op, const Type *ty)
219 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000220 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
221 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000222 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
Chris Lattner53e677a2004-04-02 20:23:17 +0000224
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000225void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000226 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227}
228
Dan Gohmanc050fd92009-07-13 20:50:19 +0000229SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
230 const SCEV *op, const Type *ty)
231 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000232 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
233 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235}
236
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000237void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000238 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000239}
240
Dan Gohmanc050fd92009-07-13 20:50:19 +0000241SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
242 const SCEV *op, const Type *ty)
243 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000244 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
245 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000246 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000247}
248
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000249void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000250 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000251}
252
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000253void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000254 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
255 const char *OpStr = getOperationStr();
256 OS << "(" << *Operands[0];
257 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
258 OS << OpStr << *Operands[i];
259 OS << ")";
260}
261
Dan Gohman64a845e2009-06-24 04:48:43 +0000262const SCEV *
263SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
264 const SCEV *Sym,
265 const SCEV *Conc,
266 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000267 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000268 const SCEV *H =
Dan Gohman246b2562007-10-22 18:31:58 +0000269 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000270 if (H != getOperand(i)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000271 SmallVector<const SCEV *, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000272 NewOps.reserve(getNumOperands());
273 for (unsigned j = 0; j != i; ++j)
274 NewOps.push_back(getOperand(j));
275 NewOps.push_back(H);
276 for (++i; i != e; ++i)
277 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000278 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000279
280 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000281 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000282 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000283 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000284 else if (isa<SCEVSMaxExpr>(this))
285 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000286 else if (isa<SCEVUMaxExpr>(this))
287 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000288 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000289 llvm_unreachable("Unknown commutative expr!");
Chris Lattner4dc534c2005-02-13 04:37:18 +0000290 }
291 }
292 return this;
293}
294
Dan Gohmanecb403a2009-05-07 14:00:19 +0000295bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000296 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
297 if (!getOperand(i)->dominates(BB, DT))
298 return false;
299 }
300 return true;
301}
302
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000303bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
304 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
305}
306
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000307void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000308 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000309}
310
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000311const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000312 // In most cases the types of LHS and RHS will be the same, but in some
313 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
314 // depend on the type for correctness, but handling types carefully can
315 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
316 // a pointer type than the RHS, so use the RHS' type here.
317 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000318}
319
Dan Gohman64a845e2009-06-24 04:48:43 +0000320const SCEV *
321SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
322 const SCEV *Conc,
323 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000324 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000325 const SCEV *H =
Dan Gohman246b2562007-10-22 18:31:58 +0000326 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000327 if (H != getOperand(i)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000328 SmallVector<const SCEV *, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000329 NewOps.reserve(getNumOperands());
330 for (unsigned j = 0; j != i; ++j)
331 NewOps.push_back(getOperand(j));
332 NewOps.push_back(H);
333 for (++i; i != e; ++i)
334 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000335 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000336
Dan Gohman246b2562007-10-22 18:31:58 +0000337 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000338 }
339 }
340 return this;
341}
342
343
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000344bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000345 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000346 if (!QueryLoop)
347 return false;
348
349 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
350 if (QueryLoop->contains(L->getHeader()))
351 return false;
352
353 // This recurrence is variant w.r.t. QueryLoop if any of its operands
354 // are variant.
355 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
356 if (!getOperand(i)->isLoopInvariant(QueryLoop))
357 return false;
358
359 // Otherwise it's loop-invariant.
360 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000361}
362
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000363void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000364 OS << "{" << *Operands[0];
365 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
366 OS << ",+," << *Operands[i];
367 OS << "}<" << L->getHeader()->getName() + ">";
368}
Chris Lattner53e677a2004-04-02 20:23:17 +0000369
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000370bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
371 // All non-instruction values are loop invariant. All instructions are loop
372 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000373 // Instructions are never considered invariant in the function body
374 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000376 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000377 return true;
378}
Chris Lattner53e677a2004-04-02 20:23:17 +0000379
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000380bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
381 if (Instruction *I = dyn_cast<Instruction>(getValue()))
382 return DT->dominates(I->getParent(), BB);
383 return true;
384}
385
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000386const Type *SCEVUnknown::getType() const {
387 return V->getType();
388}
Chris Lattner53e677a2004-04-02 20:23:17 +0000389
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000390void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000391 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000392}
393
Chris Lattner8d741b82004-06-20 06:23:15 +0000394//===----------------------------------------------------------------------===//
395// SCEV Utilities
396//===----------------------------------------------------------------------===//
397
398namespace {
399 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
400 /// than the complexity of the RHS. This comparator is used to canonicalize
401 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000402 class VISIBILITY_HIDDEN SCEVComplexityCompare {
403 LoopInfo *LI;
404 public:
405 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
406
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000407 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000408 // Primarily, sort the SCEVs by their getSCEVType().
409 if (LHS->getSCEVType() != RHS->getSCEVType())
410 return LHS->getSCEVType() < RHS->getSCEVType();
411
412 // Aside from the getSCEVType() ordering, the particular ordering
413 // isn't very important except that it's beneficial to be consistent,
414 // so that (a + b) and (b + a) don't end up as different expressions.
415
416 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
417 // not as complete as it could be.
418 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
419 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
420
Dan Gohman5be18e82009-05-19 02:15:55 +0000421 // Order pointer values after integer values. This helps SCEVExpander
422 // form GEPs.
423 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
424 return false;
425 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
426 return true;
427
Dan Gohman72861302009-05-07 14:39:04 +0000428 // Compare getValueID values.
429 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
430 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
431
432 // Sort arguments by their position.
433 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
434 const Argument *RA = cast<Argument>(RU->getValue());
435 return LA->getArgNo() < RA->getArgNo();
436 }
437
438 // For instructions, compare their loop depth, and their opcode.
439 // This is pretty loose.
440 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
441 Instruction *RV = cast<Instruction>(RU->getValue());
442
443 // Compare loop depths.
444 if (LI->getLoopDepth(LV->getParent()) !=
445 LI->getLoopDepth(RV->getParent()))
446 return LI->getLoopDepth(LV->getParent()) <
447 LI->getLoopDepth(RV->getParent());
448
449 // Compare opcodes.
450 if (LV->getOpcode() != RV->getOpcode())
451 return LV->getOpcode() < RV->getOpcode();
452
453 // Compare the number of operands.
454 if (LV->getNumOperands() != RV->getNumOperands())
455 return LV->getNumOperands() < RV->getNumOperands();
456 }
457
458 return false;
459 }
460
Dan Gohman4dfad292009-06-14 22:51:25 +0000461 // Compare constant values.
462 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
463 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000464 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
465 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000466 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
467 }
468
469 // Compare addrec loop depths.
470 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
471 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
472 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
473 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
474 }
Dan Gohman72861302009-05-07 14:39:04 +0000475
476 // Lexicographically compare n-ary expressions.
477 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
478 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
479 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
480 if (i >= RC->getNumOperands())
481 return false;
482 if (operator()(LC->getOperand(i), RC->getOperand(i)))
483 return true;
484 if (operator()(RC->getOperand(i), LC->getOperand(i)))
485 return false;
486 }
487 return LC->getNumOperands() < RC->getNumOperands();
488 }
489
Dan Gohmana6b35e22009-05-07 19:23:21 +0000490 // Lexicographically compare udiv expressions.
491 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
492 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
493 if (operator()(LC->getLHS(), RC->getLHS()))
494 return true;
495 if (operator()(RC->getLHS(), LC->getLHS()))
496 return false;
497 if (operator()(LC->getRHS(), RC->getRHS()))
498 return true;
499 if (operator()(RC->getRHS(), LC->getRHS()))
500 return false;
501 return false;
502 }
503
Dan Gohman72861302009-05-07 14:39:04 +0000504 // Compare cast expressions by operand.
505 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
506 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
507 return operator()(LC->getOperand(), RC->getOperand());
508 }
509
Torok Edwinc23197a2009-07-14 16:55:14 +0000510 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000511 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000512 }
513 };
514}
515
516/// GroupByComplexity - Given a list of SCEV objects, order them by their
517/// complexity, and group objects of the same complexity together by value.
518/// When this routine is finished, we know that any duplicates in the vector are
519/// consecutive and that complexity is monotonically increasing.
520///
521/// Note that we go take special precautions to ensure that we get determinstic
522/// results from this routine. In other words, we don't want the results of
523/// this to depend on where the addresses of various SCEV objects happened to
524/// land in memory.
525///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000526static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000527 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000528 if (Ops.size() < 2) return; // Noop
529 if (Ops.size() == 2) {
530 // This is the common case, which also happens to be trivially simple.
531 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000532 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000533 std::swap(Ops[0], Ops[1]);
534 return;
535 }
536
537 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000538 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000539
540 // Now that we are sorted by complexity, group elements of the same
541 // complexity. Note that this is, at worst, N^2, but the vector is likely to
542 // be extremely short in practice. Note that we take this approach because we
543 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000544 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000545 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000546 unsigned Complexity = S->getSCEVType();
547
548 // If there are any objects of the same complexity and same value as this
549 // one, group them.
550 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
551 if (Ops[j] == S) { // Found a duplicate.
552 // Move it to immediately after i'th element.
553 std::swap(Ops[i+1], Ops[j]);
554 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000555 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000556 }
557 }
558 }
559}
560
Chris Lattner53e677a2004-04-02 20:23:17 +0000561
Chris Lattner53e677a2004-04-02 20:23:17 +0000562
563//===----------------------------------------------------------------------===//
564// Simple SCEV method implementations
565//===----------------------------------------------------------------------===//
566
Eli Friedmanb42a6262008-08-04 23:49:06 +0000567/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000568/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000569static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000570 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000571 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000572 // Handle the simplest case efficiently.
573 if (K == 1)
574 return SE.getTruncateOrZeroExtend(It, ResultTy);
575
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000576 // We are using the following formula for BC(It, K):
577 //
578 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
579 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000580 // Suppose, W is the bitwidth of the return value. We must be prepared for
581 // overflow. Hence, we must assure that the result of our computation is
582 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
583 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000584 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000585 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000586 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000587 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
588 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000589 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000590 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000591 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000592 // This formula is trivially equivalent to the previous formula. However,
593 // this formula can be implemented much more efficiently. The trick is that
594 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
595 // arithmetic. To do exact division in modular arithmetic, all we have
596 // to do is multiply by the inverse. Therefore, this step can be done at
597 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000598 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000599 // The next issue is how to safely do the division by 2^T. The way this
600 // is done is by doing the multiplication step at a width of at least W + T
601 // bits. This way, the bottom W+T bits of the product are accurate. Then,
602 // when we perform the division by 2^T (which is equivalent to a right shift
603 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
604 // truncated out after the division by 2^T.
605 //
606 // In comparison to just directly using the first formula, this technique
607 // is much more efficient; using the first formula requires W * K bits,
608 // but this formula less than W + K bits. Also, the first formula requires
609 // a division step, whereas this formula only requires multiplies and shifts.
610 //
611 // It doesn't matter whether the subtraction step is done in the calculation
612 // width or the input iteration count's width; if the subtraction overflows,
613 // the result must be zero anyway. We prefer here to do it in the width of
614 // the induction variable because it helps a lot for certain cases; CodeGen
615 // isn't smart enough to ignore the overflow, which leads to much less
616 // efficient code if the width of the subtraction is wider than the native
617 // register width.
618 //
619 // (It's possible to not widen at all by pulling out factors of 2 before
620 // the multiplication; for example, K=2 can be calculated as
621 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
622 // extra arithmetic, so it's not an obvious win, and it gets
623 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000624
Eli Friedmanb42a6262008-08-04 23:49:06 +0000625 // Protection from insane SCEVs; this bound is conservative,
626 // but it probably doesn't matter.
627 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000628 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000629
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000630 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000631
Eli Friedmanb42a6262008-08-04 23:49:06 +0000632 // Calculate K! / 2^T and T; we divide out the factors of two before
633 // multiplying for calculating K! / 2^T to avoid overflow.
634 // Other overflow doesn't matter because we only care about the bottom
635 // W bits of the result.
636 APInt OddFactorial(W, 1);
637 unsigned T = 1;
638 for (unsigned i = 3; i <= K; ++i) {
639 APInt Mult(W, i);
640 unsigned TwoFactors = Mult.countTrailingZeros();
641 T += TwoFactors;
642 Mult = Mult.lshr(TwoFactors);
643 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000644 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000645
Eli Friedmanb42a6262008-08-04 23:49:06 +0000646 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000647 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000648
649 // Calcuate 2^T, at width T+W.
650 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
651
652 // Calculate the multiplicative inverse of K! / 2^T;
653 // this multiplication factor will perform the exact division by
654 // K! / 2^T.
655 APInt Mod = APInt::getSignedMinValue(W+1);
656 APInt MultiplyFactor = OddFactorial.zext(W+1);
657 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
658 MultiplyFactor = MultiplyFactor.trunc(W);
659
660 // Calculate the product, at width T+W
661 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000662 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000663 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000664 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000665 Dividend = SE.getMulExpr(Dividend,
666 SE.getTruncateOrZeroExtend(S, CalculationTy));
667 }
668
669 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000670 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000671
672 // Truncate the result, and divide by K! / 2^T.
673
674 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
675 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000676}
677
Chris Lattner53e677a2004-04-02 20:23:17 +0000678/// evaluateAtIteration - Return the value of this chain of recurrences at
679/// the specified iteration number. We can evaluate this recurrence by
680/// multiplying each element in the chain by the binomial coefficient
681/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
682///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000683/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000684///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000685/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000686///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000687const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman246b2562007-10-22 18:31:58 +0000688 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000689 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000690 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000691 // The computation is correct in the face of overflow provided that the
692 // multiplication is performed _after_ the evaluation of the binomial
693 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000694 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000695 if (isa<SCEVCouldNotCompute>(Coeff))
696 return Coeff;
697
698 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000699 }
700 return Result;
701}
702
Chris Lattner53e677a2004-04-02 20:23:17 +0000703//===----------------------------------------------------------------------===//
704// SCEV Expression folder implementations
705//===----------------------------------------------------------------------===//
706
Dan Gohman0bba49c2009-07-07 17:06:11 +0000707const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000708 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000709 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000710 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000711 assert(isSCEVable(Ty) &&
712 "This is not a conversion to a SCEVable type!");
713 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000714
Dan Gohmanc050fd92009-07-13 20:50:19 +0000715 FoldingSetNodeID ID;
716 ID.AddInteger(scTruncate);
717 ID.AddPointer(Op);
718 ID.AddPointer(Ty);
719 void *IP = 0;
720 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
721
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000722 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000723 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000724 return getConstant(
725 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000726
Dan Gohman20900ca2009-04-22 16:20:48 +0000727 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000728 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000729 return getTruncateExpr(ST->getOperand(), Ty);
730
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000731 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000732 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000733 return getTruncateOrSignExtend(SS->getOperand(), Ty);
734
735 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000736 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000737 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
738
Dan Gohman6864db62009-06-18 16:24:47 +0000739 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000740 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000741 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000742 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000743 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
744 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000745 }
746
Dan Gohmanc050fd92009-07-13 20:50:19 +0000747 // The cast wasn't folded; create an explicit cast node.
748 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000749 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
750 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000751 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000752 UniqueSCEVs.InsertNode(S, IP);
753 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000754}
755
Dan Gohman0bba49c2009-07-07 17:06:11 +0000756const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000757 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000758 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000759 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000760 assert(isSCEVable(Ty) &&
761 "This is not a conversion to a SCEVable type!");
762 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000763
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000764 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000765 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000766 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000767 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
768 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000769 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000770 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000771
Dan Gohman20900ca2009-04-22 16:20:48 +0000772 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000773 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000774 return getZeroExtendExpr(SZ->getOperand(), Ty);
775
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000776 // Before doing any expensive analysis, check to see if we've already
777 // computed a SCEV for this Op and Ty.
778 FoldingSetNodeID ID;
779 ID.AddInteger(scZeroExtend);
780 ID.AddPointer(Op);
781 ID.AddPointer(Ty);
782 void *IP = 0;
783 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
784
Dan Gohman01ecca22009-04-27 20:16:15 +0000785 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000786 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000787 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000788 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000789 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000790 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000791 const SCEV *Start = AR->getStart();
792 const SCEV *Step = AR->getStepRecurrence(*this);
793 unsigned BitWidth = getTypeSizeInBits(AR->getType());
794 const Loop *L = AR->getLoop();
795
Dan Gohman01ecca22009-04-27 20:16:15 +0000796 // Check whether the backedge-taken count is SCEVCouldNotCompute.
797 // Note that this serves two purposes: It filters out loops that are
798 // simply not analyzable, and it covers the case where this code is
799 // being called from within backedge-taken count analysis, such that
800 // attempting to ask for the backedge-taken count would likely result
801 // in infinite recursion. In the later case, the analysis code will
802 // cope with a conservative value, and it will take care to purge
803 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000804 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000805 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000806 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000807 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000808
809 // Check whether the backedge-taken count can be losslessly casted to
810 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000811 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000812 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000813 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000814 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
815 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000816 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000817 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000818 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000819 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000820 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000821 const SCEV *Add = getAddExpr(Start, ZMul);
822 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000823 getAddExpr(getZeroExtendExpr(Start, WideTy),
824 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
825 getZeroExtendExpr(Step, WideTy)));
826 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000827 // Return the expression with the addrec on the outside.
828 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
829 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000830 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000831
832 // Similar to above, only this time treat the step value as signed.
833 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000834 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000835 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000836 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000837 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000838 OperandExtendedAdd =
839 getAddExpr(getZeroExtendExpr(Start, WideTy),
840 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
841 getSignExtendExpr(Step, WideTy)));
842 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000843 // Return the expression with the addrec on the outside.
844 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
845 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000846 L);
847 }
848
849 // If the backedge is guarded by a comparison with the pre-inc value
850 // the addrec is safe. Also, if the entry is guarded by a comparison
851 // with the start value and the backedge is guarded by a comparison
852 // with the post-inc value, the addrec is safe.
853 if (isKnownPositive(Step)) {
854 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
855 getUnsignedRange(Step).getUnsignedMax());
856 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
857 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
858 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
859 AR->getPostIncExpr(*this), N)))
860 // Return the expression with the addrec on the outside.
861 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
862 getZeroExtendExpr(Step, Ty),
863 L);
864 } else if (isKnownNegative(Step)) {
865 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
866 getSignedRange(Step).getSignedMin());
867 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
868 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
869 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
870 AR->getPostIncExpr(*this), N)))
871 // Return the expression with the addrec on the outside.
872 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
873 getSignExtendExpr(Step, Ty),
874 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000875 }
876 }
877 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000878
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000879 // The cast wasn't folded; create an explicit cast node.
880 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000881 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
882 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000883 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000884 UniqueSCEVs.InsertNode(S, IP);
885 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000886}
887
Dan Gohman0bba49c2009-07-07 17:06:11 +0000888const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000889 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000890 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000891 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000892 assert(isSCEVable(Ty) &&
893 "This is not a conversion to a SCEVable type!");
894 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000895
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000896 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000897 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000898 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000899 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
900 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000901 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000902 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000903
Dan Gohman20900ca2009-04-22 16:20:48 +0000904 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000905 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000906 return getSignExtendExpr(SS->getOperand(), Ty);
907
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000908 // Before doing any expensive analysis, check to see if we've already
909 // computed a SCEV for this Op and Ty.
910 FoldingSetNodeID ID;
911 ID.AddInteger(scSignExtend);
912 ID.AddPointer(Op);
913 ID.AddPointer(Ty);
914 void *IP = 0;
915 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
916
Dan Gohman01ecca22009-04-27 20:16:15 +0000917 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000918 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000919 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000920 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000921 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000922 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000923 const SCEV *Start = AR->getStart();
924 const SCEV *Step = AR->getStepRecurrence(*this);
925 unsigned BitWidth = getTypeSizeInBits(AR->getType());
926 const Loop *L = AR->getLoop();
927
Dan Gohman01ecca22009-04-27 20:16:15 +0000928 // Check whether the backedge-taken count is SCEVCouldNotCompute.
929 // Note that this serves two purposes: It filters out loops that are
930 // simply not analyzable, and it covers the case where this code is
931 // being called from within backedge-taken count analysis, such that
932 // attempting to ask for the backedge-taken count would likely result
933 // in infinite recursion. In the later case, the analysis code will
934 // cope with a conservative value, and it will take care to purge
935 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000936 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000937 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000938 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000939 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000940
941 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000942 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000943 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000944 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000945 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000946 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
947 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000948 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000949 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000950 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000951 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000952 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000953 const SCEV *Add = getAddExpr(Start, SMul);
954 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000955 getAddExpr(getSignExtendExpr(Start, WideTy),
956 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
957 getSignExtendExpr(Step, WideTy)));
958 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000959 // Return the expression with the addrec on the outside.
960 return getAddRecExpr(getSignExtendExpr(Start, Ty),
961 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000962 L);
Dan Gohman850f7912009-07-16 17:34:36 +0000963
964 // Similar to above, only this time treat the step value as unsigned.
965 // This covers loops that count up with an unsigned step.
966 const SCEV *UMul =
967 getMulExpr(CastedMaxBECount,
968 getTruncateOrZeroExtend(Step, Start->getType()));
969 Add = getAddExpr(Start, UMul);
970 OperandExtendedAdd =
971 getAddExpr(getZeroExtendExpr(Start, WideTy),
972 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
973 getZeroExtendExpr(Step, WideTy)));
974 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
975 // Return the expression with the addrec on the outside.
976 return getAddRecExpr(getSignExtendExpr(Start, Ty),
977 getZeroExtendExpr(Step, Ty),
978 L);
Dan Gohman85b05a22009-07-13 21:35:55 +0000979 }
980
981 // If the backedge is guarded by a comparison with the pre-inc value
982 // the addrec is safe. Also, if the entry is guarded by a comparison
983 // with the start value and the backedge is guarded by a comparison
984 // with the post-inc value, the addrec is safe.
985 if (isKnownPositive(Step)) {
986 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
987 getSignedRange(Step).getSignedMax());
988 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
989 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
990 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
991 AR->getPostIncExpr(*this), N)))
992 // Return the expression with the addrec on the outside.
993 return getAddRecExpr(getSignExtendExpr(Start, Ty),
994 getSignExtendExpr(Step, Ty),
995 L);
996 } else if (isKnownNegative(Step)) {
997 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
998 getSignedRange(Step).getSignedMin());
999 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1000 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1001 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1002 AR->getPostIncExpr(*this), N)))
1003 // Return the expression with the addrec on the outside.
1004 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1005 getSignExtendExpr(Step, Ty),
1006 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001007 }
1008 }
1009 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001010
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001011 // The cast wasn't folded; create an explicit cast node.
1012 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001013 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1014 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001015 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001016 UniqueSCEVs.InsertNode(S, IP);
1017 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001018}
1019
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001020/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1021/// unspecified bits out to the given type.
1022///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001023const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001024 const Type *Ty) {
1025 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1026 "This is not an extending conversion!");
1027 assert(isSCEVable(Ty) &&
1028 "This is not a conversion to a SCEVable type!");
1029 Ty = getEffectiveSCEVType(Ty);
1030
1031 // Sign-extend negative constants.
1032 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1033 if (SC->getValue()->getValue().isNegative())
1034 return getSignExtendExpr(Op, Ty);
1035
1036 // Peel off a truncate cast.
1037 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001038 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001039 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1040 return getAnyExtendExpr(NewOp, Ty);
1041 return getTruncateOrNoop(NewOp, Ty);
1042 }
1043
1044 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001045 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001046 if (!isa<SCEVZeroExtendExpr>(ZExt))
1047 return ZExt;
1048
1049 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001050 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001051 if (!isa<SCEVSignExtendExpr>(SExt))
1052 return SExt;
1053
1054 // If the expression is obviously signed, use the sext cast value.
1055 if (isa<SCEVSMaxExpr>(Op))
1056 return SExt;
1057
1058 // Absent any other information, use the zext cast value.
1059 return ZExt;
1060}
1061
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001062/// CollectAddOperandsWithScales - Process the given Ops list, which is
1063/// a list of operands to be added under the given scale, update the given
1064/// map. This is a helper function for getAddRecExpr. As an example of
1065/// what it does, given a sequence of operands that would form an add
1066/// expression like this:
1067///
1068/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1069///
1070/// where A and B are constants, update the map with these values:
1071///
1072/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1073///
1074/// and add 13 + A*B*29 to AccumulatedConstant.
1075/// This will allow getAddRecExpr to produce this:
1076///
1077/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1078///
1079/// This form often exposes folding opportunities that are hidden in
1080/// the original operand list.
1081///
1082/// Return true iff it appears that any interesting folding opportunities
1083/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1084/// the common case where no interesting opportunities are present, and
1085/// is also used as a check to avoid infinite recursion.
1086///
1087static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001088CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1089 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001090 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001091 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001092 const APInt &Scale,
1093 ScalarEvolution &SE) {
1094 bool Interesting = false;
1095
1096 // Iterate over the add operands.
1097 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1098 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1099 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1100 APInt NewScale =
1101 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1102 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1103 // A multiplication of a constant with another add; recurse.
1104 Interesting |=
1105 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1106 cast<SCEVAddExpr>(Mul->getOperand(1))
1107 ->getOperands(),
1108 NewScale, SE);
1109 } else {
1110 // A multiplication of a constant with some other value. Update
1111 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001112 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1113 const SCEV *Key = SE.getMulExpr(MulOps);
1114 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001115 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001116 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001117 NewOps.push_back(Pair.first->first);
1118 } else {
1119 Pair.first->second += NewScale;
1120 // The map already had an entry for this value, which may indicate
1121 // a folding opportunity.
1122 Interesting = true;
1123 }
1124 }
1125 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1126 // Pull a buried constant out to the outside.
1127 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1128 Interesting = true;
1129 AccumulatedConstant += Scale * C->getValue()->getValue();
1130 } else {
1131 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001132 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001133 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001134 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001135 NewOps.push_back(Pair.first->first);
1136 } else {
1137 Pair.first->second += Scale;
1138 // The map already had an entry for this value, which may indicate
1139 // a folding opportunity.
1140 Interesting = true;
1141 }
1142 }
1143 }
1144
1145 return Interesting;
1146}
1147
1148namespace {
1149 struct APIntCompare {
1150 bool operator()(const APInt &LHS, const APInt &RHS) const {
1151 return LHS.ult(RHS);
1152 }
1153 };
1154}
1155
Dan Gohman6c0866c2009-05-24 23:45:28 +00001156/// getAddExpr - Get a canonical add expression, or something simpler if
1157/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001158const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001159 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001160 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001161#ifndef NDEBUG
1162 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1163 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1164 getEffectiveSCEVType(Ops[0]->getType()) &&
1165 "SCEVAddExpr operand types don't match!");
1166#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001167
1168 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001169 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001170
1171 // If there are any constants, fold them together.
1172 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001173 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001174 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001175 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001176 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001177 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001178 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1179 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001180 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001181 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001182 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001183 }
1184
1185 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001186 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001187 Ops.erase(Ops.begin());
1188 --Idx;
1189 }
1190 }
1191
Chris Lattner627018b2004-04-07 16:16:11 +00001192 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001193
Chris Lattner53e677a2004-04-02 20:23:17 +00001194 // Okay, check to see if the same value occurs in the operand list twice. If
1195 // so, merge them together into an multiply expression. Since we sorted the
1196 // list, these values are required to be adjacent.
1197 const Type *Ty = Ops[0]->getType();
1198 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1199 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1200 // Found a match, merge the two values into a multiply, and add any
1201 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001202 const SCEV *Two = getIntegerSCEV(2, Ty);
1203 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001204 if (Ops.size() == 2)
1205 return Mul;
1206 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1207 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001208 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001209 }
1210
Dan Gohman728c7f32009-05-08 21:03:19 +00001211 // Check for truncates. If all the operands are truncated from the same
1212 // type, see if factoring out the truncate would permit the result to be
1213 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1214 // if the contents of the resulting outer trunc fold to something simple.
1215 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1216 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1217 const Type *DstType = Trunc->getType();
1218 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001219 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001220 bool Ok = true;
1221 // Check all the operands to see if they can be represented in the
1222 // source type of the truncate.
1223 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1224 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1225 if (T->getOperand()->getType() != SrcType) {
1226 Ok = false;
1227 break;
1228 }
1229 LargeOps.push_back(T->getOperand());
1230 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1231 // This could be either sign or zero extension, but sign extension
1232 // is much more likely to be foldable here.
1233 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1234 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001235 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001236 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1237 if (const SCEVTruncateExpr *T =
1238 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1239 if (T->getOperand()->getType() != SrcType) {
1240 Ok = false;
1241 break;
1242 }
1243 LargeMulOps.push_back(T->getOperand());
1244 } else if (const SCEVConstant *C =
1245 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1246 // This could be either sign or zero extension, but sign extension
1247 // is much more likely to be foldable here.
1248 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1249 } else {
1250 Ok = false;
1251 break;
1252 }
1253 }
1254 if (Ok)
1255 LargeOps.push_back(getMulExpr(LargeMulOps));
1256 } else {
1257 Ok = false;
1258 break;
1259 }
1260 }
1261 if (Ok) {
1262 // Evaluate the expression in the larger type.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001263 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001264 // If it folds to something simple, use it. Otherwise, don't.
1265 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1266 return getTruncateExpr(Fold, DstType);
1267 }
1268 }
1269
1270 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001271 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1272 ++Idx;
1273
1274 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001275 if (Idx < Ops.size()) {
1276 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001277 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001278 // If we have an add, expand the add operands onto the end of the operands
1279 // list.
1280 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1281 Ops.erase(Ops.begin()+Idx);
1282 DeletedAdd = true;
1283 }
1284
1285 // If we deleted at least one add, we added operands to the end of the list,
1286 // and they are not necessarily sorted. Recurse to resort and resimplify
1287 // any operands we just aquired.
1288 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001289 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001290 }
1291
1292 // Skip over the add expression until we get to a multiply.
1293 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1294 ++Idx;
1295
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001296 // Check to see if there are any folding opportunities present with
1297 // operands multiplied by constant values.
1298 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1299 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001300 DenseMap<const SCEV *, APInt> M;
1301 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001302 APInt AccumulatedConstant(BitWidth, 0);
1303 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1304 Ops, APInt(BitWidth, 1), *this)) {
1305 // Some interesting folding opportunity is present, so its worthwhile to
1306 // re-generate the operands list. Group the operands by constant scale,
1307 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001308 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1309 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001310 E = NewOps.end(); I != E; ++I)
1311 MulOpLists[M.find(*I)->second].push_back(*I);
1312 // Re-generate the operands list.
1313 Ops.clear();
1314 if (AccumulatedConstant != 0)
1315 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001316 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1317 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001318 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001319 Ops.push_back(getMulExpr(getConstant(I->first),
1320 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001321 if (Ops.empty())
1322 return getIntegerSCEV(0, Ty);
1323 if (Ops.size() == 1)
1324 return Ops[0];
1325 return getAddExpr(Ops);
1326 }
1327 }
1328
Chris Lattner53e677a2004-04-02 20:23:17 +00001329 // If we are adding something to a multiply expression, make sure the
1330 // something is not already an operand of the multiply. If so, merge it into
1331 // the multiply.
1332 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001333 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001334 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001335 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001336 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001337 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001339 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001340 if (Mul->getNumOperands() != 2) {
1341 // If the multiply has more than two operands, we must get the
1342 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001343 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001344 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001345 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001346 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001347 const SCEV *One = getIntegerSCEV(1, Ty);
1348 const SCEV *AddOne = getAddExpr(InnerMul, One);
1349 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001350 if (Ops.size() == 2) return OuterMul;
1351 if (AddOp < Idx) {
1352 Ops.erase(Ops.begin()+AddOp);
1353 Ops.erase(Ops.begin()+Idx-1);
1354 } else {
1355 Ops.erase(Ops.begin()+Idx);
1356 Ops.erase(Ops.begin()+AddOp-1);
1357 }
1358 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001359 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001361
Chris Lattner53e677a2004-04-02 20:23:17 +00001362 // Check this multiply against other multiplies being added together.
1363 for (unsigned OtherMulIdx = Idx+1;
1364 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1365 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001366 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001367 // If MulOp occurs in OtherMul, we can fold the two multiplies
1368 // together.
1369 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1370 OMulOp != e; ++OMulOp)
1371 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1372 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001373 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001374 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001375 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1376 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001377 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001378 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001379 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001380 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001381 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001382 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1383 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001384 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001385 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001386 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001387 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1388 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001389 if (Ops.size() == 2) return OuterMul;
1390 Ops.erase(Ops.begin()+Idx);
1391 Ops.erase(Ops.begin()+OtherMulIdx-1);
1392 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001393 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001394 }
1395 }
1396 }
1397 }
1398
1399 // If there are any add recurrences in the operands list, see if any other
1400 // added values are loop invariant. If so, we can fold them into the
1401 // recurrence.
1402 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1403 ++Idx;
1404
1405 // Scan over all recurrences, trying to fold loop invariants into them.
1406 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1407 // Scan all of the other operands to this add and add them to the vector if
1408 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001409 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001410 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001411 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1412 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1413 LIOps.push_back(Ops[i]);
1414 Ops.erase(Ops.begin()+i);
1415 --i; --e;
1416 }
1417
1418 // If we found some loop invariants, fold them into the recurrence.
1419 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001420 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001421 LIOps.push_back(AddRec->getStart());
1422
Dan Gohman0bba49c2009-07-07 17:06:11 +00001423 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001424 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001425 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001426
Dan Gohman0bba49c2009-07-07 17:06:11 +00001427 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001428 // If all of the other operands were loop invariant, we are done.
1429 if (Ops.size() == 1) return NewRec;
1430
1431 // Otherwise, add the folded AddRec by the non-liv parts.
1432 for (unsigned i = 0;; ++i)
1433 if (Ops[i] == AddRec) {
1434 Ops[i] = NewRec;
1435 break;
1436 }
Dan Gohman246b2562007-10-22 18:31:58 +00001437 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001438 }
1439
1440 // Okay, if there weren't any loop invariants to be folded, check to see if
1441 // there are multiple AddRec's with the same loop induction variable being
1442 // added together. If so, we can fold them.
1443 for (unsigned OtherIdx = Idx+1;
1444 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1445 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001446 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001447 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1448 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001449 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1450 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001451 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1452 if (i >= NewOps.size()) {
1453 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1454 OtherAddRec->op_end());
1455 break;
1456 }
Dan Gohman246b2562007-10-22 18:31:58 +00001457 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001458 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001459 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001460
1461 if (Ops.size() == 2) return NewAddRec;
1462
1463 Ops.erase(Ops.begin()+Idx);
1464 Ops.erase(Ops.begin()+OtherIdx-1);
1465 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001466 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001467 }
1468 }
1469
1470 // Otherwise couldn't fold anything into this recurrence. Move onto the
1471 // next one.
1472 }
1473
1474 // Okay, it looks like we really DO need an add expr. Check to see if we
1475 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001476 FoldingSetNodeID ID;
1477 ID.AddInteger(scAddExpr);
1478 ID.AddInteger(Ops.size());
1479 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1480 ID.AddPointer(Ops[i]);
1481 void *IP = 0;
1482 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1483 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001484 new (S) SCEVAddExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001485 UniqueSCEVs.InsertNode(S, IP);
1486 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001487}
1488
1489
Dan Gohman6c0866c2009-05-24 23:45:28 +00001490/// getMulExpr - Get a canonical multiply expression, or something simpler if
1491/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001492const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001494#ifndef NDEBUG
1495 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1496 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1497 getEffectiveSCEVType(Ops[0]->getType()) &&
1498 "SCEVMulExpr operand types don't match!");
1499#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001500
1501 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001502 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001503
1504 // If there are any constants, fold them together.
1505 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001506 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001507
1508 // C1*(C2+V) -> C1*C2 + C1*V
1509 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001510 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001511 if (Add->getNumOperands() == 2 &&
1512 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001513 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1514 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001515
1516
1517 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001518 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001519 // We found two constants, fold them together!
Dan Gohman64a845e2009-06-24 04:48:43 +00001520 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001521 RHSC->getValue()->getValue());
1522 Ops[0] = getConstant(Fold);
1523 Ops.erase(Ops.begin()+1); // Erase the folded element
1524 if (Ops.size() == 1) return Ops[0];
1525 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001526 }
1527
1528 // If we are left with a constant one being multiplied, strip it off.
1529 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1530 Ops.erase(Ops.begin());
1531 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001532 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001533 // If we have a multiply of zero, it will always be zero.
1534 return Ops[0];
1535 }
1536 }
1537
1538 // Skip over the add expression until we get to a multiply.
1539 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1540 ++Idx;
1541
1542 if (Ops.size() == 1)
1543 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001544
Chris Lattner53e677a2004-04-02 20:23:17 +00001545 // If there are mul operands inline them all into this expression.
1546 if (Idx < Ops.size()) {
1547 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001548 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001549 // If we have an mul, expand the mul operands onto the end of the operands
1550 // list.
1551 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1552 Ops.erase(Ops.begin()+Idx);
1553 DeletedMul = true;
1554 }
1555
1556 // If we deleted at least one mul, we added operands to the end of the list,
1557 // and they are not necessarily sorted. Recurse to resort and resimplify
1558 // any operands we just aquired.
1559 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001560 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001561 }
1562
1563 // If there are any add recurrences in the operands list, see if any other
1564 // added values are loop invariant. If so, we can fold them into the
1565 // recurrence.
1566 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1567 ++Idx;
1568
1569 // Scan over all recurrences, trying to fold loop invariants into them.
1570 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1571 // Scan all of the other operands to this mul and add them to the vector if
1572 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001573 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001574 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1576 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1577 LIOps.push_back(Ops[i]);
1578 Ops.erase(Ops.begin()+i);
1579 --i; --e;
1580 }
1581
1582 // If we found some loop invariants, fold them into the recurrence.
1583 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001584 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001585 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001586 NewOps.reserve(AddRec->getNumOperands());
1587 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001588 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001590 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001591 } else {
1592 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001593 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001594 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001595 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001596 }
1597 }
1598
Dan Gohman0bba49c2009-07-07 17:06:11 +00001599 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001600
1601 // If all of the other operands were loop invariant, we are done.
1602 if (Ops.size() == 1) return NewRec;
1603
1604 // Otherwise, multiply the folded AddRec by the non-liv parts.
1605 for (unsigned i = 0;; ++i)
1606 if (Ops[i] == AddRec) {
1607 Ops[i] = NewRec;
1608 break;
1609 }
Dan Gohman246b2562007-10-22 18:31:58 +00001610 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001611 }
1612
1613 // Okay, if there weren't any loop invariants to be folded, check to see if
1614 // there are multiple AddRec's with the same loop induction variable being
1615 // multiplied together. If so, we can fold them.
1616 for (unsigned OtherIdx = Idx+1;
1617 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1618 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001619 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1621 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001622 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001623 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001624 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001625 const SCEV *B = F->getStepRecurrence(*this);
1626 const SCEV *D = G->getStepRecurrence(*this);
1627 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001628 getMulExpr(G, B),
1629 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001630 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001631 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001632 if (Ops.size() == 2) return NewAddRec;
1633
1634 Ops.erase(Ops.begin()+Idx);
1635 Ops.erase(Ops.begin()+OtherIdx-1);
1636 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001637 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001638 }
1639 }
1640
1641 // Otherwise couldn't fold anything into this recurrence. Move onto the
1642 // next one.
1643 }
1644
1645 // Okay, it looks like we really DO need an mul expr. Check to see if we
1646 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001647 FoldingSetNodeID ID;
1648 ID.AddInteger(scMulExpr);
1649 ID.AddInteger(Ops.size());
1650 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1651 ID.AddPointer(Ops[i]);
1652 void *IP = 0;
1653 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1654 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001655 new (S) SCEVMulExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001656 UniqueSCEVs.InsertNode(S, IP);
1657 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001658}
1659
Dan Gohman6c0866c2009-05-24 23:45:28 +00001660/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1661/// possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001662const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1663 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001664 assert(getEffectiveSCEVType(LHS->getType()) ==
1665 getEffectiveSCEVType(RHS->getType()) &&
1666 "SCEVUDivExpr operand types don't match!");
1667
Dan Gohman622ed672009-05-04 22:02:23 +00001668 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001669 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001670 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001671 if (RHSC->isZero())
1672 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001673
Dan Gohman185cf032009-05-08 20:18:49 +00001674 // Determine if the division can be folded into the operands of
1675 // its operands.
1676 // TODO: Generalize this to non-constants by using known-bits information.
1677 const Type *Ty = LHS->getType();
1678 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1679 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1680 // For non-power-of-two values, effectively round the value up to the
1681 // nearest power of two.
1682 if (!RHSC->getValue()->getValue().isPowerOf2())
1683 ++MaxShiftAmt;
1684 const IntegerType *ExtTy =
1685 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1686 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1687 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1688 if (const SCEVConstant *Step =
1689 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1690 if (!Step->getValue()->getValue()
1691 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001692 getZeroExtendExpr(AR, ExtTy) ==
1693 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1694 getZeroExtendExpr(Step, ExtTy),
1695 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001696 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001697 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1698 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1699 return getAddRecExpr(Operands, AR->getLoop());
1700 }
1701 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001702 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001703 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001704 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1705 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1706 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001707 // Find an operand that's safely divisible.
1708 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001709 const SCEV *Op = M->getOperand(i);
1710 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001711 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001712 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1713 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001714 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001715 Operands[i] = Div;
1716 return getMulExpr(Operands);
1717 }
1718 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001719 }
Dan Gohman185cf032009-05-08 20:18:49 +00001720 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001721 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001722 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001723 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1724 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1725 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1726 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001727 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001728 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001729 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1730 break;
1731 Operands.push_back(Op);
1732 }
1733 if (Operands.size() == A->getNumOperands())
1734 return getAddExpr(Operands);
1735 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001736 }
Dan Gohman185cf032009-05-08 20:18:49 +00001737
1738 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001739 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001740 Constant *LHSCV = LHSC->getValue();
1741 Constant *RHSCV = RHSC->getValue();
Owen Anderson385396222009-07-13 23:50:59 +00001742 return getConstant(cast<ConstantInt>(Context->getConstantExprUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001743 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001744 }
1745 }
1746
Dan Gohman1c343752009-06-27 21:21:31 +00001747 FoldingSetNodeID ID;
1748 ID.AddInteger(scUDivExpr);
1749 ID.AddPointer(LHS);
1750 ID.AddPointer(RHS);
1751 void *IP = 0;
1752 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1753 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001754 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001755 UniqueSCEVs.InsertNode(S, IP);
1756 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001757}
1758
1759
Dan Gohman6c0866c2009-05-24 23:45:28 +00001760/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1761/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001762const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1763 const SCEV *Step, const Loop *L) {
1764 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001765 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001766 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001767 if (StepChrec->getLoop() == L) {
1768 Operands.insert(Operands.end(), StepChrec->op_begin(),
1769 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001770 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001771 }
1772
1773 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001774 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001775}
1776
Dan Gohman6c0866c2009-05-24 23:45:28 +00001777/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1778/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001779const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001780ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman64a845e2009-06-24 04:48:43 +00001781 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001782 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001783#ifndef NDEBUG
1784 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1785 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1786 getEffectiveSCEVType(Operands[0]->getType()) &&
1787 "SCEVAddRecExpr operand types don't match!");
1788#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001789
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001790 if (Operands.back()->isZero()) {
1791 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001792 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001793 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001794
Dan Gohmand9cc7492008-08-08 18:33:12 +00001795 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001796 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001797 const Loop* NestedLoop = NestedAR->getLoop();
1798 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001799 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001800 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001801 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001802 // AddRecs require their operands be loop-invariant with respect to their
1803 // loops. Don't perform this transformation if it would break this
1804 // requirement.
1805 bool AllInvariant = true;
1806 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1807 if (!Operands[i]->isLoopInvariant(L)) {
1808 AllInvariant = false;
1809 break;
1810 }
1811 if (AllInvariant) {
1812 NestedOperands[0] = getAddRecExpr(Operands, L);
1813 AllInvariant = true;
1814 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1815 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1816 AllInvariant = false;
1817 break;
1818 }
1819 if (AllInvariant)
1820 // Ok, both add recurrences are valid after the transformation.
1821 return getAddRecExpr(NestedOperands, NestedLoop);
1822 }
1823 // Reset Operands to its original state.
1824 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001825 }
1826 }
1827
Dan Gohman1c343752009-06-27 21:21:31 +00001828 FoldingSetNodeID ID;
1829 ID.AddInteger(scAddRecExpr);
1830 ID.AddInteger(Operands.size());
1831 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1832 ID.AddPointer(Operands[i]);
1833 ID.AddPointer(L);
1834 void *IP = 0;
1835 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1836 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001837 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohman1c343752009-06-27 21:21:31 +00001838 UniqueSCEVs.InsertNode(S, IP);
1839 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001840}
1841
Dan Gohman9311ef62009-06-24 14:49:00 +00001842const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1843 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001844 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001845 Ops.push_back(LHS);
1846 Ops.push_back(RHS);
1847 return getSMaxExpr(Ops);
1848}
1849
Dan Gohman0bba49c2009-07-07 17:06:11 +00001850const SCEV *
1851ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001852 assert(!Ops.empty() && "Cannot get empty smax!");
1853 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001854#ifndef NDEBUG
1855 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1856 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1857 getEffectiveSCEVType(Ops[0]->getType()) &&
1858 "SCEVSMaxExpr operand types don't match!");
1859#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001860
1861 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001862 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001863
1864 // If there are any constants, fold them together.
1865 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001866 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001867 ++Idx;
1868 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001869 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001870 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001871 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001872 APIntOps::smax(LHSC->getValue()->getValue(),
1873 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001874 Ops[0] = getConstant(Fold);
1875 Ops.erase(Ops.begin()+1); // Erase the folded element
1876 if (Ops.size() == 1) return Ops[0];
1877 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001878 }
1879
Dan Gohmane5aceed2009-06-24 14:46:22 +00001880 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001881 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1882 Ops.erase(Ops.begin());
1883 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001884 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1885 // If we have an smax with a constant maximum-int, it will always be
1886 // maximum-int.
1887 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001888 }
1889 }
1890
1891 if (Ops.size() == 1) return Ops[0];
1892
1893 // Find the first SMax
1894 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1895 ++Idx;
1896
1897 // Check to see if one of the operands is an SMax. If so, expand its operands
1898 // onto our operand list, and recurse to simplify.
1899 if (Idx < Ops.size()) {
1900 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001901 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001902 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1903 Ops.erase(Ops.begin()+Idx);
1904 DeletedSMax = true;
1905 }
1906
1907 if (DeletedSMax)
1908 return getSMaxExpr(Ops);
1909 }
1910
1911 // Okay, check to see if the same value occurs in the operand list twice. If
1912 // so, delete one. Since we sorted the list, these values are required to
1913 // be adjacent.
1914 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1915 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1916 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1917 --i; --e;
1918 }
1919
1920 if (Ops.size() == 1) return Ops[0];
1921
1922 assert(!Ops.empty() && "Reduced smax down to nothing!");
1923
Nick Lewycky3e630762008-02-20 06:48:22 +00001924 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001925 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001926 FoldingSetNodeID ID;
1927 ID.AddInteger(scSMaxExpr);
1928 ID.AddInteger(Ops.size());
1929 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1930 ID.AddPointer(Ops[i]);
1931 void *IP = 0;
1932 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1933 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001934 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001935 UniqueSCEVs.InsertNode(S, IP);
1936 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001937}
1938
Dan Gohman9311ef62009-06-24 14:49:00 +00001939const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1940 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001941 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001942 Ops.push_back(LHS);
1943 Ops.push_back(RHS);
1944 return getUMaxExpr(Ops);
1945}
1946
Dan Gohman0bba49c2009-07-07 17:06:11 +00001947const SCEV *
1948ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001949 assert(!Ops.empty() && "Cannot get empty umax!");
1950 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001951#ifndef NDEBUG
1952 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1953 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1954 getEffectiveSCEVType(Ops[0]->getType()) &&
1955 "SCEVUMaxExpr operand types don't match!");
1956#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001957
1958 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001959 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001960
1961 // If there are any constants, fold them together.
1962 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001963 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001964 ++Idx;
1965 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001966 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001967 // We found two constants, fold them together!
1968 ConstantInt *Fold = ConstantInt::get(
1969 APIntOps::umax(LHSC->getValue()->getValue(),
1970 RHSC->getValue()->getValue()));
1971 Ops[0] = getConstant(Fold);
1972 Ops.erase(Ops.begin()+1); // Erase the folded element
1973 if (Ops.size() == 1) return Ops[0];
1974 LHSC = cast<SCEVConstant>(Ops[0]);
1975 }
1976
Dan Gohmane5aceed2009-06-24 14:46:22 +00001977 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00001978 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1979 Ops.erase(Ops.begin());
1980 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001981 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1982 // If we have an umax with a constant maximum-int, it will always be
1983 // maximum-int.
1984 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001985 }
1986 }
1987
1988 if (Ops.size() == 1) return Ops[0];
1989
1990 // Find the first UMax
1991 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1992 ++Idx;
1993
1994 // Check to see if one of the operands is a UMax. If so, expand its operands
1995 // onto our operand list, and recurse to simplify.
1996 if (Idx < Ops.size()) {
1997 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001998 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001999 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2000 Ops.erase(Ops.begin()+Idx);
2001 DeletedUMax = true;
2002 }
2003
2004 if (DeletedUMax)
2005 return getUMaxExpr(Ops);
2006 }
2007
2008 // Okay, check to see if the same value occurs in the operand list twice. If
2009 // so, delete one. Since we sorted the list, these values are required to
2010 // be adjacent.
2011 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2012 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2013 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2014 --i; --e;
2015 }
2016
2017 if (Ops.size() == 1) return Ops[0];
2018
2019 assert(!Ops.empty() && "Reduced umax down to nothing!");
2020
2021 // Okay, it looks like we really DO need a umax expr. Check to see if we
2022 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002023 FoldingSetNodeID ID;
2024 ID.AddInteger(scUMaxExpr);
2025 ID.AddInteger(Ops.size());
2026 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2027 ID.AddPointer(Ops[i]);
2028 void *IP = 0;
2029 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2030 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002031 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002032 UniqueSCEVs.InsertNode(S, IP);
2033 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002034}
2035
Dan Gohman9311ef62009-06-24 14:49:00 +00002036const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2037 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002038 // ~smax(~x, ~y) == smin(x, y).
2039 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2040}
2041
Dan Gohman9311ef62009-06-24 14:49:00 +00002042const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2043 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002044 // ~umax(~x, ~y) == umin(x, y)
2045 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2046}
2047
Dan Gohman0bba49c2009-07-07 17:06:11 +00002048const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002049 // Don't attempt to do anything other than create a SCEVUnknown object
2050 // here. createSCEV only calls getUnknown after checking for all other
2051 // interesting possibilities, and any other code that calls getUnknown
2052 // is doing so in order to hide a value from SCEV canonicalization.
2053
Dan Gohman1c343752009-06-27 21:21:31 +00002054 FoldingSetNodeID ID;
2055 ID.AddInteger(scUnknown);
2056 ID.AddPointer(V);
2057 void *IP = 0;
2058 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2059 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002060 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002061 UniqueSCEVs.InsertNode(S, IP);
2062 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002063}
2064
Chris Lattner53e677a2004-04-02 20:23:17 +00002065//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002066// Basic SCEV Analysis and PHI Idiom Recognition Code
2067//
2068
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002069/// isSCEVable - Test if values of the given type are analyzable within
2070/// the SCEV framework. This primarily includes integer types, and it
2071/// can optionally include pointer types if the ScalarEvolution class
2072/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002073bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002074 // Integers are always SCEVable.
2075 if (Ty->isInteger())
2076 return true;
2077
2078 // Pointers are SCEVable if TargetData information is available
2079 // to provide pointer size information.
2080 if (isa<PointerType>(Ty))
2081 return TD != NULL;
2082
2083 // Otherwise it's not SCEVable.
2084 return false;
2085}
2086
2087/// getTypeSizeInBits - Return the size in bits of the specified type,
2088/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002089uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002090 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2091
2092 // If we have a TargetData, use it!
2093 if (TD)
2094 return TD->getTypeSizeInBits(Ty);
2095
2096 // Otherwise, we support only integer types.
2097 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2098 return Ty->getPrimitiveSizeInBits();
2099}
2100
2101/// getEffectiveSCEVType - Return a type with the same bitwidth as
2102/// the given type and which represents how SCEV will treat the given
2103/// type, for which isSCEVable must return true. For pointer types,
2104/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002105const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002106 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2107
2108 if (Ty->isInteger())
2109 return Ty;
2110
2111 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2112 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00002113}
Chris Lattner53e677a2004-04-02 20:23:17 +00002114
Dan Gohman0bba49c2009-07-07 17:06:11 +00002115const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002116 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002117}
2118
Chris Lattner53e677a2004-04-02 20:23:17 +00002119/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2120/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002121const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002122 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002123
Dan Gohman0bba49c2009-07-07 17:06:11 +00002124 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002125 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002126 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002127 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002128 return S;
2129}
2130
Dan Gohman6bbcba12009-06-24 00:54:57 +00002131/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002132/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002133const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002134 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Anderson9adc0ab2009-07-14 23:09:55 +00002135 return getConstant(Context->getConstantInt(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002136}
2137
2138/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2139///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002140const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002141 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002142 return getConstant(
2143 cast<ConstantInt>(Context->getConstantExprNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002144
2145 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002146 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002147 return getMulExpr(V,
2148 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002149}
2150
2151/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002152const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002153 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002154 return getConstant(
2155 cast<ConstantInt>(Context->getConstantExprNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002156
2157 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002158 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002159 const SCEV *AllOnes =
2160 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002161 return getMinusSCEV(AllOnes, V);
2162}
2163
2164/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2165///
Dan Gohman9311ef62009-06-24 14:49:00 +00002166const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2167 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002168 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002169 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002170}
2171
2172/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2173/// input value to the specified type. If the type must be extended, it is zero
2174/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002175const SCEV *
2176ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002177 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002178 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002179 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2180 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002181 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002182 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002183 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002184 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002185 return getTruncateExpr(V, Ty);
2186 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002187}
2188
2189/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2190/// input value to the specified type. If the type must be extended, it is sign
2191/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002192const SCEV *
2193ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002194 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002195 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002196 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2197 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002198 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002199 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002200 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002201 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002202 return getTruncateExpr(V, Ty);
2203 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002204}
2205
Dan Gohman467c4302009-05-13 03:46:30 +00002206/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2207/// input value to the specified type. If the type must be extended, it is zero
2208/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002209const SCEV *
2210ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002211 const Type *SrcTy = V->getType();
2212 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2213 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2214 "Cannot noop or zero extend with non-integer arguments!");
2215 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2216 "getNoopOrZeroExtend cannot truncate!");
2217 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2218 return V; // No conversion
2219 return getZeroExtendExpr(V, Ty);
2220}
2221
2222/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2223/// input value to the specified type. If the type must be extended, it is sign
2224/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002225const SCEV *
2226ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002227 const Type *SrcTy = V->getType();
2228 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2229 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2230 "Cannot noop or sign extend with non-integer arguments!");
2231 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2232 "getNoopOrSignExtend cannot truncate!");
2233 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2234 return V; // No conversion
2235 return getSignExtendExpr(V, Ty);
2236}
2237
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002238/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2239/// the input value to the specified type. If the type must be extended,
2240/// it is extended with unspecified bits. The conversion must not be
2241/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002242const SCEV *
2243ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002244 const Type *SrcTy = V->getType();
2245 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2246 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2247 "Cannot noop or any extend with non-integer arguments!");
2248 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2249 "getNoopOrAnyExtend cannot truncate!");
2250 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2251 return V; // No conversion
2252 return getAnyExtendExpr(V, Ty);
2253}
2254
Dan Gohman467c4302009-05-13 03:46:30 +00002255/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2256/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002257const SCEV *
2258ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002259 const Type *SrcTy = V->getType();
2260 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2261 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2262 "Cannot truncate or noop with non-integer arguments!");
2263 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2264 "getTruncateOrNoop cannot extend!");
2265 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2266 return V; // No conversion
2267 return getTruncateExpr(V, Ty);
2268}
2269
Dan Gohmana334aa72009-06-22 00:31:57 +00002270/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2271/// the types using zero-extension, and then perform a umax operation
2272/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002273const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2274 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002275 const SCEV *PromotedLHS = LHS;
2276 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002277
2278 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2279 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2280 else
2281 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2282
2283 return getUMaxExpr(PromotedLHS, PromotedRHS);
2284}
2285
Dan Gohmanc9759e82009-06-22 15:03:27 +00002286/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2287/// the types using zero-extension, and then perform a umin operation
2288/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002289const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2290 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002291 const SCEV *PromotedLHS = LHS;
2292 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002293
2294 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2295 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2296 else
2297 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2298
2299 return getUMinExpr(PromotedLHS, PromotedRHS);
2300}
2301
Chris Lattner4dc534c2005-02-13 04:37:18 +00002302/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2303/// the specified instruction and replaces any references to the symbolic value
2304/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002305void
2306ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2307 const SCEV *SymName,
2308 const SCEV *NewVal) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002309 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohman35738ac2009-05-04 22:30:44 +00002310 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002311 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002312
Dan Gohman0bba49c2009-07-07 17:06:11 +00002313 const SCEV *NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002314 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002315 if (NV == SI->second) return; // No change.
2316
2317 SI->second = NV; // Update the scalars map!
2318
2319 // Any instruction values that use this instruction might also need to be
2320 // updated!
2321 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2322 UI != E; ++UI)
2323 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2324}
Chris Lattner53e677a2004-04-02 20:23:17 +00002325
2326/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2327/// a loop header, making it a potential recurrence, or it doesn't.
2328///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002329const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002330 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002331 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002332 if (L->getHeader() == PN->getParent()) {
2333 // If it lives in the loop header, it has two incoming values, one
2334 // from outside the loop, and one from inside.
2335 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2336 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002337
Chris Lattner53e677a2004-04-02 20:23:17 +00002338 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002339 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002340 assert(Scalars.find(PN) == Scalars.end() &&
2341 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002342 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002343
2344 // Using this symbolic name for the PHI, analyze the value coming around
2345 // the back-edge.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002346 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Chris Lattner53e677a2004-04-02 20:23:17 +00002347
2348 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2349 // has a special value for the first iteration of the loop.
2350
2351 // If the value coming around the backedge is an add with the symbolic
2352 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002353 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002354 // If there is a single occurrence of the symbolic value, replace it
2355 // with a recurrence.
2356 unsigned FoundIndex = Add->getNumOperands();
2357 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2358 if (Add->getOperand(i) == SymbolicName)
2359 if (FoundIndex == e) {
2360 FoundIndex = i;
2361 break;
2362 }
2363
2364 if (FoundIndex != Add->getNumOperands()) {
2365 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002366 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002367 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2368 if (i != FoundIndex)
2369 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002370 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002371
2372 // This is not a valid addrec if the step amount is varying each
2373 // loop iteration, but is not itself an addrec in this loop.
2374 if (Accum->isLoopInvariant(L) ||
2375 (isa<SCEVAddRecExpr>(Accum) &&
2376 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002377 const SCEV *StartVal =
2378 getSCEV(PN->getIncomingValue(IncomingEdge));
2379 const SCEV *PHISCEV =
2380 getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002381
2382 // Okay, for the entire analysis of this edge we assumed the PHI
2383 // to be symbolic. We now need to go back and update all of the
2384 // entries for the scalars that use the PHI (except for the PHI
2385 // itself) to use the new analyzed value instead of the "symbolic"
2386 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002387 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002388 return PHISCEV;
2389 }
2390 }
Dan Gohman622ed672009-05-04 22:02:23 +00002391 } else if (const SCEVAddRecExpr *AddRec =
2392 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002393 // Otherwise, this could be a loop like this:
2394 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2395 // In this case, j = {1,+,1} and BEValue is j.
2396 // Because the other in-value of i (0) fits the evolution of BEValue
2397 // i really is an addrec evolution.
2398 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002399 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002400
2401 // If StartVal = j.start - j.stride, we can use StartVal as the
2402 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002403 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002404 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002405 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002406 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002407
2408 // Okay, for the entire analysis of this edge we assumed the PHI
2409 // to be symbolic. We now need to go back and update all of the
2410 // entries for the scalars that use the PHI (except for the PHI
2411 // itself) to use the new analyzed value instead of the "symbolic"
2412 // value.
2413 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2414 return PHISCEV;
2415 }
2416 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002417 }
2418
2419 return SymbolicName;
2420 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002421
Dan Gohmana653fc52009-07-14 14:06:25 +00002422 // It's tempting to recognize PHIs with a unique incoming value, however
2423 // this leads passes like indvars to break LCSSA form. Fortunately, such
2424 // PHIs are rare, as instcombine zaps them.
2425
Chris Lattner53e677a2004-04-02 20:23:17 +00002426 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002427 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002428}
2429
Dan Gohman26466c02009-05-08 20:26:55 +00002430/// createNodeForGEP - Expand GEP instructions into add and multiply
2431/// operations. This allows them to be analyzed by regular SCEV code.
2432///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002433const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002434
2435 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002436 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002437 // Don't attempt to analyze GEPs over unsized objects.
2438 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2439 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002440 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002441 gep_type_iterator GTI = gep_type_begin(GEP);
2442 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2443 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002444 I != E; ++I) {
2445 Value *Index = *I;
2446 // Compute the (potentially symbolic) offset in bytes for this index.
2447 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2448 // For a struct, add the member offset.
2449 const StructLayout &SL = *TD->getStructLayout(STy);
2450 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2451 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohman85b05a22009-07-13 21:35:55 +00002452 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman26466c02009-05-08 20:26:55 +00002453 } else {
2454 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002455 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002456 if (!isa<PointerType>(LocalOffset->getType()))
2457 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002458 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohman26466c02009-05-08 20:26:55 +00002459 LocalOffset =
2460 getMulExpr(LocalOffset,
Dan Gohman85b05a22009-07-13 21:35:55 +00002461 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
Dan Gohman26466c02009-05-08 20:26:55 +00002462 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2463 }
2464 }
2465 return getAddExpr(getSCEV(Base), TotalOffset);
2466}
2467
Nick Lewycky83bb0052007-11-22 07:59:40 +00002468/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2469/// guaranteed to end in (at every loop iteration). It is, at the same time,
2470/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2471/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002472uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002473ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002474 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002475 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002476
Dan Gohman622ed672009-05-04 22:02:23 +00002477 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002478 return std::min(GetMinTrailingZeros(T->getOperand()),
2479 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002480
Dan Gohman622ed672009-05-04 22:02:23 +00002481 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002482 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2483 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2484 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002485 }
2486
Dan Gohman622ed672009-05-04 22:02:23 +00002487 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002488 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2489 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2490 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002491 }
2492
Dan Gohman622ed672009-05-04 22:02:23 +00002493 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002494 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002495 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002496 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002497 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002498 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002499 }
2500
Dan Gohman622ed672009-05-04 22:02:23 +00002501 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002502 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002503 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2504 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002505 for (unsigned i = 1, e = M->getNumOperands();
2506 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002507 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002508 BitWidth);
2509 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002510 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002511
Dan Gohman622ed672009-05-04 22:02:23 +00002512 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002513 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002514 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002515 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002516 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002517 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002518 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002519
Dan Gohman622ed672009-05-04 22:02:23 +00002520 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002521 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002522 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002523 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002524 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002525 return MinOpRes;
2526 }
2527
Dan Gohman622ed672009-05-04 22:02:23 +00002528 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002529 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002530 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002531 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002532 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002533 return MinOpRes;
2534 }
2535
Dan Gohman2c364ad2009-06-19 23:29:04 +00002536 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2537 // For a SCEVUnknown, ask ValueTracking.
2538 unsigned BitWidth = getTypeSizeInBits(U->getType());
2539 APInt Mask = APInt::getAllOnesValue(BitWidth);
2540 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2541 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2542 return Zeros.countTrailingOnes();
2543 }
2544
2545 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002546 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002547}
Chris Lattner53e677a2004-04-02 20:23:17 +00002548
Dan Gohman85b05a22009-07-13 21:35:55 +00002549/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2550///
2551ConstantRange
2552ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002553
2554 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002555 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002556
Dan Gohman85b05a22009-07-13 21:35:55 +00002557 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2558 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2559 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2560 X = X.add(getUnsignedRange(Add->getOperand(i)));
2561 return X;
2562 }
2563
2564 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2565 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2566 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2567 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2568 return X;
2569 }
2570
2571 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2572 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2573 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2574 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2575 return X;
2576 }
2577
2578 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2579 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2580 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2581 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2582 return X;
2583 }
2584
2585 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2586 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2587 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2588 return X.udiv(Y);
2589 }
2590
2591 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2592 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2593 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2594 }
2595
2596 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2597 ConstantRange X = getUnsignedRange(SExt->getOperand());
2598 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2599 }
2600
2601 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2602 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2603 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2604 }
2605
2606 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2607
2608 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2609 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2610 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2611 if (!Trip) return FullSet;
2612
2613 // TODO: non-affine addrec
2614 if (AddRec->isAffine()) {
2615 const Type *Ty = AddRec->getType();
2616 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2617 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2618 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2619
2620 const SCEV *Start = AddRec->getStart();
2621 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2622
2623 // Check for overflow.
2624 if (!isKnownPredicate(ICmpInst::ICMP_ULE, Start, End))
2625 return FullSet;
2626
2627 ConstantRange StartRange = getUnsignedRange(Start);
2628 ConstantRange EndRange = getUnsignedRange(End);
2629 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2630 EndRange.getUnsignedMin());
2631 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2632 EndRange.getUnsignedMax());
2633 if (Min.isMinValue() && Max.isMaxValue())
2634 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2635 return ConstantRange(Min, Max+1);
2636 }
2637 }
Dan Gohman2c364ad2009-06-19 23:29:04 +00002638 }
2639
2640 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2641 // For a SCEVUnknown, ask ValueTracking.
2642 unsigned BitWidth = getTypeSizeInBits(U->getType());
2643 APInt Mask = APInt::getAllOnesValue(BitWidth);
2644 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2645 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman85b05a22009-07-13 21:35:55 +00002646 return ConstantRange(Ones, ~Zeros);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002647 }
2648
Dan Gohman85b05a22009-07-13 21:35:55 +00002649 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002650}
2651
Dan Gohman85b05a22009-07-13 21:35:55 +00002652/// getSignedRange - Determine the signed range for a particular SCEV.
2653///
2654ConstantRange
2655ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002656
Dan Gohman85b05a22009-07-13 21:35:55 +00002657 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2658 return ConstantRange(C->getValue()->getValue());
2659
2660 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2661 ConstantRange X = getSignedRange(Add->getOperand(0));
2662 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2663 X = X.add(getSignedRange(Add->getOperand(i)));
2664 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002665 }
2666
Dan Gohman85b05a22009-07-13 21:35:55 +00002667 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2668 ConstantRange X = getSignedRange(Mul->getOperand(0));
2669 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2670 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2671 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002672 }
2673
Dan Gohman85b05a22009-07-13 21:35:55 +00002674 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2675 ConstantRange X = getSignedRange(SMax->getOperand(0));
2676 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2677 X = X.smax(getSignedRange(SMax->getOperand(i)));
2678 return X;
2679 }
Dan Gohman62849c02009-06-24 01:05:09 +00002680
Dan Gohman85b05a22009-07-13 21:35:55 +00002681 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2682 ConstantRange X = getSignedRange(UMax->getOperand(0));
2683 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2684 X = X.umax(getSignedRange(UMax->getOperand(i)));
2685 return X;
2686 }
Dan Gohman62849c02009-06-24 01:05:09 +00002687
Dan Gohman85b05a22009-07-13 21:35:55 +00002688 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2689 ConstantRange X = getSignedRange(UDiv->getLHS());
2690 ConstantRange Y = getSignedRange(UDiv->getRHS());
2691 return X.udiv(Y);
2692 }
Dan Gohman62849c02009-06-24 01:05:09 +00002693
Dan Gohman85b05a22009-07-13 21:35:55 +00002694 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2695 ConstantRange X = getSignedRange(ZExt->getOperand());
2696 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2697 }
2698
2699 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2700 ConstantRange X = getSignedRange(SExt->getOperand());
2701 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2702 }
2703
2704 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2705 ConstantRange X = getSignedRange(Trunc->getOperand());
2706 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2707 }
2708
2709 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2710
2711 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2712 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2713 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2714 if (!Trip) return FullSet;
2715
2716 // TODO: non-affine addrec
2717 if (AddRec->isAffine()) {
2718 const Type *Ty = AddRec->getType();
2719 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2720 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2721 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2722
2723 const SCEV *Start = AddRec->getStart();
2724 const SCEV *Step = AddRec->getStepRecurrence(*this);
2725 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2726
2727 // Check for overflow.
2728 if (!(isKnownPositive(Step) &&
2729 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2730 !(isKnownNegative(Step) &&
2731 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2732 return FullSet;
2733
2734 ConstantRange StartRange = getSignedRange(Start);
2735 ConstantRange EndRange = getSignedRange(End);
2736 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2737 EndRange.getSignedMin());
2738 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2739 EndRange.getSignedMax());
2740 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2741 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2742 return ConstantRange(Min, Max+1);
Dan Gohman62849c02009-06-24 01:05:09 +00002743 }
Dan Gohman62849c02009-06-24 01:05:09 +00002744 }
Dan Gohman62849c02009-06-24 01:05:09 +00002745 }
2746
Dan Gohman2c364ad2009-06-19 23:29:04 +00002747 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2748 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman85b05a22009-07-13 21:35:55 +00002749 unsigned BitWidth = getTypeSizeInBits(U->getType());
2750 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2751 if (NS == 1)
2752 return FullSet;
2753 return
2754 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2755 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002756 }
2757
Dan Gohman85b05a22009-07-13 21:35:55 +00002758 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002759}
2760
Chris Lattner53e677a2004-04-02 20:23:17 +00002761/// createSCEV - We know that there is no SCEV for the specified value.
2762/// Analyze the expression.
2763///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002764const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002765 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002766 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002767
Dan Gohman6c459a22008-06-22 19:56:46 +00002768 unsigned Opcode = Instruction::UserOp1;
2769 if (Instruction *I = dyn_cast<Instruction>(V))
2770 Opcode = I->getOpcode();
2771 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2772 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002773 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2774 return getConstant(CI);
2775 else if (isa<ConstantPointerNull>(V))
2776 return getIntegerSCEV(0, V->getType());
2777 else if (isa<UndefValue>(V))
2778 return getIntegerSCEV(0, V->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002779 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002780 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002781
Dan Gohman6c459a22008-06-22 19:56:46 +00002782 User *U = cast<User>(V);
2783 switch (Opcode) {
2784 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002785 return getAddExpr(getSCEV(U->getOperand(0)),
2786 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002787 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002788 return getMulExpr(getSCEV(U->getOperand(0)),
2789 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002790 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002791 return getUDivExpr(getSCEV(U->getOperand(0)),
2792 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002793 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002794 return getMinusSCEV(getSCEV(U->getOperand(0)),
2795 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002796 case Instruction::And:
2797 // For an expression like x&255 that merely masks off the high bits,
2798 // use zext(trunc(x)) as the SCEV expression.
2799 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002800 if (CI->isNullValue())
2801 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002802 if (CI->isAllOnesValue())
2803 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002804 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002805
2806 // Instcombine's ShrinkDemandedConstant may strip bits out of
2807 // constants, obscuring what would otherwise be a low-bits mask.
2808 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2809 // knew about to reconstruct a low-bits mask value.
2810 unsigned LZ = A.countLeadingZeros();
2811 unsigned BitWidth = A.getBitWidth();
2812 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2813 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2814 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2815
2816 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2817
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002818 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002819 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002820 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002821 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002822 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002823 }
2824 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002825
Dan Gohman6c459a22008-06-22 19:56:46 +00002826 case Instruction::Or:
2827 // If the RHS of the Or is a constant, we may have something like:
2828 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2829 // optimizations will transparently handle this case.
2830 //
2831 // In order for this transformation to be safe, the LHS must be of the
2832 // form X*(2^n) and the Or constant must be less than 2^n.
2833 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002834 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002835 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002836 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002837 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002838 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002839 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002840 break;
2841 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002842 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002843 // If the RHS of the xor is a signbit, then this is just an add.
2844 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002845 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002846 return getAddExpr(getSCEV(U->getOperand(0)),
2847 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002848
2849 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002850 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002851 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002852
2853 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2854 // This is a variant of the check for xor with -1, and it handles
2855 // the case where instcombine has trimmed non-demanded bits out
2856 // of an xor with -1.
2857 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2858 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2859 if (BO->getOpcode() == Instruction::And &&
2860 LCI->getValue() == CI->getValue())
2861 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002862 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002863 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00002864 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002865 const Type *Z0Ty = Z0->getType();
2866 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2867
2868 // If C is a low-bits mask, the zero extend is zerving to
2869 // mask off the high bits. Complement the operand and
2870 // re-apply the zext.
2871 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2872 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2873
2874 // If C is a single bit, it may be in the sign-bit position
2875 // before the zero-extend. In this case, represent the xor
2876 // using an add, which is equivalent, and re-apply the zext.
2877 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2878 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2879 Trunc.isSignBit())
2880 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2881 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002882 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002883 }
2884 break;
2885
2886 case Instruction::Shl:
2887 // Turn shift left of a constant amount into a multiply.
2888 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2889 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2890 Constant *X = ConstantInt::get(
2891 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002892 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002893 }
2894 break;
2895
Nick Lewycky01eaf802008-07-07 06:15:49 +00002896 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002897 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002898 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2899 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2900 Constant *X = ConstantInt::get(
2901 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002902 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002903 }
2904 break;
2905
Dan Gohman4ee29af2009-04-21 02:26:00 +00002906 case Instruction::AShr:
2907 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2908 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2909 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2910 if (L->getOpcode() == Instruction::Shl &&
2911 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002912 unsigned BitWidth = getTypeSizeInBits(U->getType());
2913 uint64_t Amt = BitWidth - CI->getZExtValue();
2914 if (Amt == BitWidth)
2915 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2916 if (Amt > BitWidth)
2917 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002918 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002919 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002920 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002921 U->getType());
2922 }
2923 break;
2924
Dan Gohman6c459a22008-06-22 19:56:46 +00002925 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002926 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002927
2928 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002929 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002930
2931 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002932 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002933
2934 case Instruction::BitCast:
2935 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002936 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002937 return getSCEV(U->getOperand(0));
2938 break;
2939
Dan Gohman2d1be872009-04-16 03:18:22 +00002940 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002941 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002942 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002943 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002944
2945 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002946 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002947 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2948 U->getType());
2949
Dan Gohman26466c02009-05-08 20:26:55 +00002950 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002951 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002952 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002953
Dan Gohman6c459a22008-06-22 19:56:46 +00002954 case Instruction::PHI:
2955 return createNodeForPHI(cast<PHINode>(U));
2956
2957 case Instruction::Select:
2958 // This could be a smax or umax that was lowered earlier.
2959 // Try to recover it.
2960 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2961 Value *LHS = ICI->getOperand(0);
2962 Value *RHS = ICI->getOperand(1);
2963 switch (ICI->getPredicate()) {
2964 case ICmpInst::ICMP_SLT:
2965 case ICmpInst::ICMP_SLE:
2966 std::swap(LHS, RHS);
2967 // fall through
2968 case ICmpInst::ICMP_SGT:
2969 case ICmpInst::ICMP_SGE:
2970 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002971 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002972 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002973 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002974 break;
2975 case ICmpInst::ICMP_ULT:
2976 case ICmpInst::ICMP_ULE:
2977 std::swap(LHS, RHS);
2978 // fall through
2979 case ICmpInst::ICMP_UGT:
2980 case ICmpInst::ICMP_UGE:
2981 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002982 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002983 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002984 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002985 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002986 case ICmpInst::ICMP_NE:
2987 // n != 0 ? n : 1 -> umax(n, 1)
2988 if (LHS == U->getOperand(1) &&
2989 isa<ConstantInt>(U->getOperand(2)) &&
2990 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2991 isa<ConstantInt>(RHS) &&
2992 cast<ConstantInt>(RHS)->isZero())
2993 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2994 break;
2995 case ICmpInst::ICMP_EQ:
2996 // n == 0 ? 1 : n -> umax(n, 1)
2997 if (LHS == U->getOperand(2) &&
2998 isa<ConstantInt>(U->getOperand(1)) &&
2999 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3000 isa<ConstantInt>(RHS) &&
3001 cast<ConstantInt>(RHS)->isZero())
3002 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3003 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003004 default:
3005 break;
3006 }
3007 }
3008
3009 default: // We cannot analyze this expression.
3010 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003011 }
3012
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003013 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003014}
3015
3016
3017
3018//===----------------------------------------------------------------------===//
3019// Iteration Count Computation Code
3020//
3021
Dan Gohman46bdfb02009-02-24 18:55:53 +00003022/// getBackedgeTakenCount - If the specified loop has a predictable
3023/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3024/// object. The backedge-taken count is the number of times the loop header
3025/// will be branched to from within the loop. This is one less than the
3026/// trip count of the loop, since it doesn't count the first iteration,
3027/// when the header is branched to from outside the loop.
3028///
3029/// Note that it is not valid to call this method on a loop without a
3030/// loop-invariant backedge-taken count (see
3031/// hasLoopInvariantBackedgeTakenCount).
3032///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003033const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003034 return getBackedgeTakenInfo(L).Exact;
3035}
3036
3037/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3038/// return the least SCEV value that is known never to be less than the
3039/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003040const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003041 return getBackedgeTakenInfo(L).Max;
3042}
3043
Dan Gohman59ae6b92009-07-08 19:23:34 +00003044/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3045/// onto the given Worklist.
3046static void
3047PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3048 BasicBlock *Header = L->getHeader();
3049
3050 // Push all Loop-header PHIs onto the Worklist stack.
3051 for (BasicBlock::iterator I = Header->begin();
3052 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3053 Worklist.push_back(PN);
3054}
3055
3056/// PushDefUseChildren - Push users of the given Instruction
3057/// onto the given Worklist.
3058static void
3059PushDefUseChildren(Instruction *I,
3060 SmallVectorImpl<Instruction *> &Worklist) {
3061 // Push the def-use children onto the Worklist stack.
3062 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3063 UI != UE; ++UI)
3064 Worklist.push_back(cast<Instruction>(UI));
3065}
3066
Dan Gohmana1af7572009-04-30 20:47:05 +00003067const ScalarEvolution::BackedgeTakenInfo &
3068ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003069 // Initially insert a CouldNotCompute for this loop. If the insertion
3070 // succeeds, procede to actually compute a backedge-taken count and
3071 // update the value. The temporary CouldNotCompute value tells SCEV
3072 // code elsewhere that it shouldn't attempt to request a new
3073 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00003074 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003075 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3076 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003077 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00003078 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003079 assert(ItCount.Exact->isLoopInvariant(L) &&
3080 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003081 "Computed trip count isn't loop invariant for loop!");
3082 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003083
Dan Gohman01ecca22009-04-27 20:16:15 +00003084 // Update the value in the map.
3085 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003086 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00003087 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003088 // Update the value in the map.
3089 Pair.first->second = ItCount;
3090 if (isa<PHINode>(L->getHeader()->begin()))
3091 // Only count loops that have phi nodes as not being computable.
3092 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003093 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003094
3095 // Now that we know more about the trip count for this loop, forget any
3096 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003097 // conservative estimates made without the benefit of trip count
3098 // information. This is similar to the code in
3099 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3100 // nodes specially.
3101 if (ItCount.hasAnyInfo()) {
3102 SmallVector<Instruction *, 16> Worklist;
3103 PushLoopPHIs(L, Worklist);
3104
3105 SmallPtrSet<Instruction *, 8> Visited;
3106 while (!Worklist.empty()) {
3107 Instruction *I = Worklist.pop_back_val();
3108 if (!Visited.insert(I)) continue;
3109
3110 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3111 Scalars.find(static_cast<Value *>(I));
3112 if (It != Scalars.end()) {
3113 // SCEVUnknown for a PHI either means that it has an unrecognized
3114 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003115 // by createNodeForPHI. In the former case, additional loop trip
3116 // count information isn't going to change anything. In the later
3117 // case, createNodeForPHI will perform the necessary updates on its
3118 // own when it gets to that point.
Dan Gohman59ae6b92009-07-08 19:23:34 +00003119 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3120 Scalars.erase(It);
3121 ValuesAtScopes.erase(I);
3122 if (PHINode *PN = dyn_cast<PHINode>(I))
3123 ConstantEvolutionLoopExitValue.erase(PN);
3124 }
3125
3126 PushDefUseChildren(I, Worklist);
3127 }
3128 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003129 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003130 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003131}
3132
Dan Gohman46bdfb02009-02-24 18:55:53 +00003133/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00003134/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00003135/// ScalarEvolution's ability to compute a trip count, or if the loop
3136/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003137void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003138 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003139
Dan Gohman35738ac2009-05-04 22:30:44 +00003140 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003141 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003142
Dan Gohman59ae6b92009-07-08 19:23:34 +00003143 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003144 while (!Worklist.empty()) {
3145 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003146 if (!Visited.insert(I)) continue;
3147
3148 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3149 Scalars.find(static_cast<Value *>(I));
3150 if (It != Scalars.end()) {
3151 Scalars.erase(It);
3152 ValuesAtScopes.erase(I);
3153 if (PHINode *PN = dyn_cast<PHINode>(I))
3154 ConstantEvolutionLoopExitValue.erase(PN);
3155 }
3156
3157 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003158 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003159}
3160
Dan Gohman46bdfb02009-02-24 18:55:53 +00003161/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3162/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003163ScalarEvolution::BackedgeTakenInfo
3164ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003165 SmallVector<BasicBlock*, 8> ExitingBlocks;
3166 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003167
Dan Gohmana334aa72009-06-22 00:31:57 +00003168 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003169 const SCEV *BECount = getCouldNotCompute();
3170 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003171 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003172 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3173 BackedgeTakenInfo NewBTI =
3174 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003175
Dan Gohman1c343752009-06-27 21:21:31 +00003176 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003177 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003178 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003179 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003180 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003181 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003182 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003183 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003184 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003185 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003186 }
Dan Gohman1c343752009-06-27 21:21:31 +00003187 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003188 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003189 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003190 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003191 }
3192
3193 return BackedgeTakenInfo(BECount, MaxBECount);
3194}
3195
3196/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3197/// of the specified loop will execute if it exits via the specified block.
3198ScalarEvolution::BackedgeTakenInfo
3199ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3200 BasicBlock *ExitingBlock) {
3201
3202 // Okay, we've chosen an exiting block. See what condition causes us to
3203 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003204 //
3205 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003206 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003207 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003208 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003209
Chris Lattner8b0e3602007-01-07 02:24:26 +00003210 // At this point, we know we have a conditional branch that determines whether
3211 // the loop is exited. However, we don't know if the branch is executed each
3212 // time through the loop. If not, then the execution count of the branch will
3213 // not be equal to the trip count of the loop.
3214 //
3215 // Currently we check for this by checking to see if the Exit branch goes to
3216 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003217 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003218 // loop header. This is common for un-rotated loops.
3219 //
3220 // If both of those tests fail, walk up the unique predecessor chain to the
3221 // header, stopping if there is an edge that doesn't exit the loop. If the
3222 // header is reached, the execution count of the branch will be equal to the
3223 // trip count of the loop.
3224 //
3225 // More extensive analysis could be done to handle more cases here.
3226 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003227 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003228 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003229 ExitBr->getParent() != L->getHeader()) {
3230 // The simple checks failed, try climbing the unique predecessor chain
3231 // up to the header.
3232 bool Ok = false;
3233 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3234 BasicBlock *Pred = BB->getUniquePredecessor();
3235 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003236 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003237 TerminatorInst *PredTerm = Pred->getTerminator();
3238 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3239 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3240 if (PredSucc == BB)
3241 continue;
3242 // If the predecessor has a successor that isn't BB and isn't
3243 // outside the loop, assume the worst.
3244 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003245 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003246 }
3247 if (Pred == L->getHeader()) {
3248 Ok = true;
3249 break;
3250 }
3251 BB = Pred;
3252 }
3253 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003254 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003255 }
3256
3257 // Procede to the next level to examine the exit condition expression.
3258 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3259 ExitBr->getSuccessor(0),
3260 ExitBr->getSuccessor(1));
3261}
3262
3263/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3264/// backedge of the specified loop will execute if its exit condition
3265/// were a conditional branch of ExitCond, TBB, and FBB.
3266ScalarEvolution::BackedgeTakenInfo
3267ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3268 Value *ExitCond,
3269 BasicBlock *TBB,
3270 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003271 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003272 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3273 if (BO->getOpcode() == Instruction::And) {
3274 // Recurse on the operands of the and.
3275 BackedgeTakenInfo BTI0 =
3276 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3277 BackedgeTakenInfo BTI1 =
3278 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003279 const SCEV *BECount = getCouldNotCompute();
3280 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003281 if (L->contains(TBB)) {
3282 // Both conditions must be true for the loop to continue executing.
3283 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003284 if (BTI0.Exact == getCouldNotCompute() ||
3285 BTI1.Exact == getCouldNotCompute())
3286 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003287 else
3288 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003289 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003290 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003291 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003292 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003293 else
3294 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003295 } else {
3296 // Both conditions must be true for the loop to exit.
3297 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003298 if (BTI0.Exact != getCouldNotCompute() &&
3299 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003300 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003301 if (BTI0.Max != getCouldNotCompute() &&
3302 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003303 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3304 }
3305
3306 return BackedgeTakenInfo(BECount, MaxBECount);
3307 }
3308 if (BO->getOpcode() == Instruction::Or) {
3309 // Recurse on the operands of the or.
3310 BackedgeTakenInfo BTI0 =
3311 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3312 BackedgeTakenInfo BTI1 =
3313 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003314 const SCEV *BECount = getCouldNotCompute();
3315 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003316 if (L->contains(FBB)) {
3317 // Both conditions must be false for the loop to continue executing.
3318 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003319 if (BTI0.Exact == getCouldNotCompute() ||
3320 BTI1.Exact == getCouldNotCompute())
3321 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003322 else
3323 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003324 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003325 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003326 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003327 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003328 else
3329 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003330 } else {
3331 // Both conditions must be false for the loop to exit.
3332 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003333 if (BTI0.Exact != getCouldNotCompute() &&
3334 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003335 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003336 if (BTI0.Max != getCouldNotCompute() &&
3337 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003338 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3339 }
3340
3341 return BackedgeTakenInfo(BECount, MaxBECount);
3342 }
3343 }
3344
3345 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3346 // Procede to the next level to examine the icmp.
3347 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3348 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003349
Eli Friedman361e54d2009-05-09 12:32:42 +00003350 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003351 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3352}
3353
3354/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3355/// backedge of the specified loop will execute if its exit condition
3356/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3357ScalarEvolution::BackedgeTakenInfo
3358ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3359 ICmpInst *ExitCond,
3360 BasicBlock *TBB,
3361 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003362
Reid Spencere4d87aa2006-12-23 06:05:41 +00003363 // If the condition was exit on true, convert the condition to exit on false
3364 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003365 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003367 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003368 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003369
3370 // Handle common loops like: for (X = "string"; *X; ++X)
3371 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3372 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003373 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003374 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003375 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3376 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3377 return BackedgeTakenInfo(ItCnt,
3378 isa<SCEVConstant>(ItCnt) ? ItCnt :
3379 getConstant(APInt::getMaxValue(BitWidth)-1));
3380 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003381 }
3382
Dan Gohman0bba49c2009-07-07 17:06:11 +00003383 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3384 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003385
3386 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003387 LHS = getSCEVAtScope(LHS, L);
3388 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003389
Dan Gohman64a845e2009-06-24 04:48:43 +00003390 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003392 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3393 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003394 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003396 }
3397
Chris Lattner53e677a2004-04-02 20:23:17 +00003398 // If we have a comparison of a chrec against a constant, try to use value
3399 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003400 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3401 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003402 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003403 // Form the constant range.
3404 ConstantRange CompRange(
3405 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003406
Dan Gohman0bba49c2009-07-07 17:06:11 +00003407 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003408 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003409 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003410
Chris Lattner53e677a2004-04-02 20:23:17 +00003411 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003412 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003413 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003414 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003415 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003416 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003417 }
3418 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003419 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003420 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003421 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003422 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003423 }
3424 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003425 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3426 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003427 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003428 }
3429 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003430 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3431 getNotSCEV(RHS), L, true);
3432 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003433 break;
3434 }
3435 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003436 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3437 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003438 break;
3439 }
3440 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003441 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3442 getNotSCEV(RHS), L, false);
3443 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003444 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003445 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003446 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003447#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003448 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003449 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003450 errs() << "[unsigned] ";
3451 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003452 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003454#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003455 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003456 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003457 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003458 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003459}
3460
Chris Lattner673e02b2004-10-12 01:49:27 +00003461static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003462EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3463 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003464 const SCEV *InVal = SE.getConstant(C);
3465 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003466 assert(isa<SCEVConstant>(Val) &&
3467 "Evaluation of SCEV at constant didn't fold correctly?");
3468 return cast<SCEVConstant>(Val)->getValue();
3469}
3470
3471/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3472/// and a GEP expression (missing the pointer index) indexing into it, return
3473/// the addressed element of the initializer or null if the index expression is
3474/// invalid.
3475static Constant *
Owen Anderson0a5372e2009-07-13 04:09:18 +00003476GetAddressedElementFromGlobal(LLVMContext *Context, GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003477 const std::vector<ConstantInt*> &Indices) {
3478 Constant *Init = GV->getInitializer();
3479 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003480 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003481 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3482 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3483 Init = cast<Constant>(CS->getOperand(Idx));
3484 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3485 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3486 Init = cast<Constant>(CA->getOperand(Idx));
3487 } else if (isa<ConstantAggregateZero>(Init)) {
3488 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3489 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Anderson0a5372e2009-07-13 04:09:18 +00003490 Init = Context->getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003491 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3492 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Anderson0a5372e2009-07-13 04:09:18 +00003493 Init = Context->getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003494 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003495 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003496 }
3497 return 0;
3498 } else {
3499 return 0; // Unknown initializer type
3500 }
3501 }
3502 return Init;
3503}
3504
Dan Gohman46bdfb02009-02-24 18:55:53 +00003505/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3506/// 'icmp op load X, cst', try to see if we can compute the backedge
3507/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003508const SCEV *
3509ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3510 LoadInst *LI,
3511 Constant *RHS,
3512 const Loop *L,
3513 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003514 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003515
3516 // Check to see if the loaded pointer is a getelementptr of a global.
3517 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003518 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003519
3520 // Make sure that it is really a constant global we are gepping, with an
3521 // initializer, and make sure the first IDX is really 0.
3522 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3523 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3524 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3525 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003526 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003527
3528 // Okay, we allow one non-constant index into the GEP instruction.
3529 Value *VarIdx = 0;
3530 std::vector<ConstantInt*> Indexes;
3531 unsigned VarIdxNum = 0;
3532 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3533 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3534 Indexes.push_back(CI);
3535 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003536 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003537 VarIdx = GEP->getOperand(i);
3538 VarIdxNum = i-2;
3539 Indexes.push_back(0);
3540 }
3541
3542 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3543 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003544 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003545 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003546
3547 // We can only recognize very limited forms of loop index expressions, in
3548 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003549 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003550 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3551 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3552 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003553 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003554
3555 unsigned MaxSteps = MaxBruteForceIterations;
3556 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003557 ConstantInt *ItCst = Context->getConstantInt(
3558 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003559 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003560
3561 // Form the GEP offset.
3562 Indexes[VarIdxNum] = Val;
3563
Owen Anderson0a5372e2009-07-13 04:09:18 +00003564 Constant *Result = GetAddressedElementFromGlobal(Context, GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003565 if (Result == 0) break; // Cannot compute!
3566
3567 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003568 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003569 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003570 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003571#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003572 errs() << "\n***\n*** Computed loop count " << *ItCst
3573 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3574 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003575#endif
3576 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003577 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003578 }
3579 }
Dan Gohman1c343752009-06-27 21:21:31 +00003580 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003581}
3582
3583
Chris Lattner3221ad02004-04-17 22:58:41 +00003584/// CanConstantFold - Return true if we can constant fold an instruction of the
3585/// specified type, assuming that all operands were constants.
3586static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003587 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003588 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3589 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003590
Chris Lattner3221ad02004-04-17 22:58:41 +00003591 if (const CallInst *CI = dyn_cast<CallInst>(I))
3592 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003593 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003594 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003595}
3596
Chris Lattner3221ad02004-04-17 22:58:41 +00003597/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3598/// in the loop that V is derived from. We allow arbitrary operations along the
3599/// way, but the operands of an operation must either be constants or a value
3600/// derived from a constant PHI. If this expression does not fit with these
3601/// constraints, return null.
3602static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3603 // If this is not an instruction, or if this is an instruction outside of the
3604 // loop, it can't be derived from a loop PHI.
3605 Instruction *I = dyn_cast<Instruction>(V);
3606 if (I == 0 || !L->contains(I->getParent())) return 0;
3607
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003608 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003609 if (L->getHeader() == I->getParent())
3610 return PN;
3611 else
3612 // We don't currently keep track of the control flow needed to evaluate
3613 // PHIs, so we cannot handle PHIs inside of loops.
3614 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003615 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003616
3617 // If we won't be able to constant fold this expression even if the operands
3618 // are constants, return early.
3619 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003620
Chris Lattner3221ad02004-04-17 22:58:41 +00003621 // Otherwise, we can evaluate this instruction if all of its operands are
3622 // constant or derived from a PHI node themselves.
3623 PHINode *PHI = 0;
3624 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3625 if (!(isa<Constant>(I->getOperand(Op)) ||
3626 isa<GlobalValue>(I->getOperand(Op)))) {
3627 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3628 if (P == 0) return 0; // Not evolving from PHI
3629 if (PHI == 0)
3630 PHI = P;
3631 else if (PHI != P)
3632 return 0; // Evolving from multiple different PHIs.
3633 }
3634
3635 // This is a expression evolving from a constant PHI!
3636 return PHI;
3637}
3638
3639/// EvaluateExpression - Given an expression that passes the
3640/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3641/// in the loop has the value PHIVal. If we can't fold this expression for some
3642/// reason, return null.
3643static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3644 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003645 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003646 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003647 Instruction *I = cast<Instruction>(V);
Owen Anderson07cf79e2009-07-06 23:00:19 +00003648 LLVMContext *Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003649
3650 std::vector<Constant*> Operands;
3651 Operands.resize(I->getNumOperands());
3652
3653 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3654 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3655 if (Operands[i] == 0) return 0;
3656 }
3657
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003658 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3659 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003660 &Operands[0], Operands.size(),
3661 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003662 else
3663 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003664 &Operands[0], Operands.size(),
3665 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003666}
3667
3668/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3669/// in the header of its containing loop, we know the loop executes a
3670/// constant number of times, and the PHI node is just a recurrence
3671/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003672Constant *
3673ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3674 const APInt& BEs,
3675 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003676 std::map<PHINode*, Constant*>::iterator I =
3677 ConstantEvolutionLoopExitValue.find(PN);
3678 if (I != ConstantEvolutionLoopExitValue.end())
3679 return I->second;
3680
Dan Gohman46bdfb02009-02-24 18:55:53 +00003681 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003682 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3683
3684 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3685
3686 // Since the loop is canonicalized, the PHI node must have two entries. One
3687 // entry must be a constant (coming in from outside of the loop), and the
3688 // second must be derived from the same PHI.
3689 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3690 Constant *StartCST =
3691 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3692 if (StartCST == 0)
3693 return RetVal = 0; // Must be a constant.
3694
3695 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3696 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3697 if (PN2 != PN)
3698 return RetVal = 0; // Not derived from same PHI.
3699
3700 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003701 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003702 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003703
Dan Gohman46bdfb02009-02-24 18:55:53 +00003704 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003705 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003706 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3707 if (IterationNum == NumIterations)
3708 return RetVal = PHIVal; // Got exit value!
3709
3710 // Compute the value of the PHI node for the next iteration.
3711 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3712 if (NextPHI == PHIVal)
3713 return RetVal = NextPHI; // Stopped evolving!
3714 if (NextPHI == 0)
3715 return 0; // Couldn't evaluate!
3716 PHIVal = NextPHI;
3717 }
3718}
3719
Dan Gohman46bdfb02009-02-24 18:55:53 +00003720/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003721/// constant number of times (the condition evolves only from constants),
3722/// try to evaluate a few iterations of the loop until we get the exit
3723/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003724/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003725const SCEV *
3726ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3727 Value *Cond,
3728 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003729 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003730 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003731
3732 // Since the loop is canonicalized, the PHI node must have two entries. One
3733 // entry must be a constant (coming in from outside of the loop), and the
3734 // second must be derived from the same PHI.
3735 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3736 Constant *StartCST =
3737 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003738 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003739
3740 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3741 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003742 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003743
3744 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3745 // the loop symbolically to determine when the condition gets a value of
3746 // "ExitWhen".
3747 unsigned IterationNum = 0;
3748 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3749 for (Constant *PHIVal = StartCST;
3750 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003751 ConstantInt *CondVal =
3752 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003753
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003754 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003755 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003756
Reid Spencere8019bb2007-03-01 07:25:48 +00003757 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003758 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003759 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003760 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003761
Chris Lattner3221ad02004-04-17 22:58:41 +00003762 // Compute the value of the PHI node for the next iteration.
3763 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3764 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003765 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003766 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003767 }
3768
3769 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003770 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003771}
3772
Dan Gohman66a7e852009-05-08 20:38:54 +00003773/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3774/// at the specified scope in the program. The L value specifies a loop
3775/// nest to evaluate the expression at, where null is the top-level or a
3776/// specified loop is immediately inside of the loop.
3777///
3778/// This method can be used to compute the exit value for a variable defined
3779/// in a loop by querying what the value will hold in the parent loop.
3780///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003781/// In the case that a relevant loop exit value cannot be computed, the
3782/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003783const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003784 // FIXME: this should be turned into a virtual method on SCEV!
3785
Chris Lattner3221ad02004-04-17 22:58:41 +00003786 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003787
Nick Lewycky3e630762008-02-20 06:48:22 +00003788 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003789 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003790 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003791 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003792 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003793 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3794 if (PHINode *PN = dyn_cast<PHINode>(I))
3795 if (PN->getParent() == LI->getHeader()) {
3796 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003797 // to see if the loop that contains it has a known backedge-taken
3798 // count. If so, we may be able to force computation of the exit
3799 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003800 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003801 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003802 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003803 // Okay, we know how many times the containing loop executes. If
3804 // this is a constant evolving PHI node, get the final value at
3805 // the specified iteration number.
3806 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003807 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003808 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003809 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003810 }
3811 }
3812
Reid Spencer09906f32006-12-04 21:33:23 +00003813 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003814 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003815 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003816 // result. This is particularly useful for computing loop exit values.
3817 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003818 // Check to see if we've folded this instruction at this loop before.
3819 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3820 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3821 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3822 if (!Pair.second)
Dan Gohman09987962009-06-29 21:31:18 +00003823 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohman6bce6432009-05-08 20:47:27 +00003824
Chris Lattner3221ad02004-04-17 22:58:41 +00003825 std::vector<Constant*> Operands;
3826 Operands.reserve(I->getNumOperands());
3827 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3828 Value *Op = I->getOperand(i);
3829 if (Constant *C = dyn_cast<Constant>(Op)) {
3830 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003831 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003832 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003833 // non-integer and non-pointer, don't even try to analyze them
3834 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003835 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003836 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003837
Dan Gohman85b05a22009-07-13 21:35:55 +00003838 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00003839 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003840 Constant *C = SC->getValue();
3841 if (C->getType() != Op->getType())
3842 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3843 Op->getType(),
3844 false),
3845 C, Op->getType());
3846 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003847 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003848 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3849 if (C->getType() != Op->getType())
3850 C =
3851 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3852 Op->getType(),
3853 false),
3854 C, Op->getType());
3855 Operands.push_back(C);
3856 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003857 return V;
3858 } else {
3859 return V;
3860 }
3861 }
3862 }
Dan Gohman64a845e2009-06-24 04:48:43 +00003863
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003864 Constant *C;
3865 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3866 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003867 &Operands[0], Operands.size(),
3868 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003869 else
3870 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003871 &Operands[0], Operands.size(), Context);
Dan Gohman6bce6432009-05-08 20:47:27 +00003872 Pair.first->second = C;
Dan Gohman09987962009-06-29 21:31:18 +00003873 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003874 }
3875 }
3876
3877 // This is some other type of SCEVUnknown, just return it.
3878 return V;
3879 }
3880
Dan Gohman622ed672009-05-04 22:02:23 +00003881 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003882 // Avoid performing the look-up in the common case where the specified
3883 // expression has no loop-variant portions.
3884 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003885 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003886 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003887 // Okay, at least one of these operands is loop variant but might be
3888 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00003889 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3890 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003891 NewOps.push_back(OpAtScope);
3892
3893 for (++i; i != e; ++i) {
3894 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003895 NewOps.push_back(OpAtScope);
3896 }
3897 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003898 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003899 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003900 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003901 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003902 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003903 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003904 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00003905 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003906 }
3907 }
3908 // If we got here, all operands are loop invariant.
3909 return Comm;
3910 }
3911
Dan Gohman622ed672009-05-04 22:02:23 +00003912 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003913 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3914 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003915 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3916 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003917 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003918 }
3919
3920 // If this is a loop recurrence for a loop that does not contain L, then we
3921 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003922 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003923 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3924 // To evaluate this recurrence, we need to know how many times the AddRec
3925 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003926 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00003927 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003928
Eli Friedmanb42a6262008-08-04 23:49:06 +00003929 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003930 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003931 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003932 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003933 }
3934
Dan Gohman622ed672009-05-04 22:02:23 +00003935 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003936 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003937 if (Op == Cast->getOperand())
3938 return Cast; // must be loop invariant
3939 return getZeroExtendExpr(Op, Cast->getType());
3940 }
3941
Dan Gohman622ed672009-05-04 22:02:23 +00003942 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003943 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003944 if (Op == Cast->getOperand())
3945 return Cast; // must be loop invariant
3946 return getSignExtendExpr(Op, Cast->getType());
3947 }
3948
Dan Gohman622ed672009-05-04 22:02:23 +00003949 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003950 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003951 if (Op == Cast->getOperand())
3952 return Cast; // must be loop invariant
3953 return getTruncateExpr(Op, Cast->getType());
3954 }
3955
Torok Edwinc23197a2009-07-14 16:55:14 +00003956 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003957 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003958}
3959
Dan Gohman66a7e852009-05-08 20:38:54 +00003960/// getSCEVAtScope - This is a convenience function which does
3961/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00003962const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003963 return getSCEVAtScope(getSCEV(V), L);
3964}
3965
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003966/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3967/// following equation:
3968///
3969/// A * X = B (mod N)
3970///
3971/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3972/// A and B isn't important.
3973///
3974/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003975static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003976 ScalarEvolution &SE) {
3977 uint32_t BW = A.getBitWidth();
3978 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3979 assert(A != 0 && "A must be non-zero.");
3980
3981 // 1. D = gcd(A, N)
3982 //
3983 // The gcd of A and N may have only one prime factor: 2. The number of
3984 // trailing zeros in A is its multiplicity
3985 uint32_t Mult2 = A.countTrailingZeros();
3986 // D = 2^Mult2
3987
3988 // 2. Check if B is divisible by D.
3989 //
3990 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3991 // is not less than multiplicity of this prime factor for D.
3992 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003993 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003994
3995 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3996 // modulo (N / D).
3997 //
3998 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3999 // bit width during computations.
4000 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4001 APInt Mod(BW + 1, 0);
4002 Mod.set(BW - Mult2); // Mod = N / D
4003 APInt I = AD.multiplicativeInverse(Mod);
4004
4005 // 4. Compute the minimum unsigned root of the equation:
4006 // I * (B / D) mod (N / D)
4007 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4008
4009 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4010 // bits.
4011 return SE.getConstant(Result.trunc(BW));
4012}
Chris Lattner53e677a2004-04-02 20:23:17 +00004013
4014/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4015/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4016/// might be the same) or two SCEVCouldNotCompute objects.
4017///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004018static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004019SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004020 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004021 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4022 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4023 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004024
Chris Lattner53e677a2004-04-02 20:23:17 +00004025 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004026 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004027 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004028 return std::make_pair(CNC, CNC);
4029 }
4030
Reid Spencere8019bb2007-03-01 07:25:48 +00004031 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004032 const APInt &L = LC->getValue()->getValue();
4033 const APInt &M = MC->getValue()->getValue();
4034 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004035 APInt Two(BitWidth, 2);
4036 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004037
Dan Gohman64a845e2009-06-24 04:48:43 +00004038 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004039 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004040 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004041 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4042 // The B coefficient is M-N/2
4043 APInt B(M);
4044 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004045
Reid Spencere8019bb2007-03-01 07:25:48 +00004046 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004047 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004048
Reid Spencere8019bb2007-03-01 07:25:48 +00004049 // Compute the B^2-4ac term.
4050 APInt SqrtTerm(B);
4051 SqrtTerm *= B;
4052 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004053
Reid Spencere8019bb2007-03-01 07:25:48 +00004054 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4055 // integer value or else APInt::sqrt() will assert.
4056 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004057
Dan Gohman64a845e2009-06-24 04:48:43 +00004058 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004059 // The divisions must be performed as signed divisions.
4060 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004061 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004062 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004063 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004064 return std::make_pair(CNC, CNC);
4065 }
4066
Owen Anderson76f600b2009-07-06 22:37:39 +00004067 LLVMContext *Context = SE.getContext();
4068
4069 ConstantInt *Solution1 =
4070 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
4071 ConstantInt *Solution2 =
4072 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004073
Dan Gohman64a845e2009-06-24 04:48:43 +00004074 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004075 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004076 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004077}
4078
4079/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004080/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004081const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004082 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004083 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004084 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004085 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004086 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004087 }
4088
Dan Gohman35738ac2009-05-04 22:30:44 +00004089 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004090 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004091 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004092
4093 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004094 // If this is an affine expression, the execution count of this branch is
4095 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004096 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004097 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004098 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004099 // equivalent to:
4100 //
4101 // Step*N = -Start (mod 2^BW)
4102 //
4103 // where BW is the common bit width of Start and Step.
4104
Chris Lattner53e677a2004-04-02 20:23:17 +00004105 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004106 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4107 L->getParentLoop());
4108 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4109 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004110
Dan Gohman622ed672009-05-04 22:02:23 +00004111 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004112 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004113
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004114 // First, handle unitary steps.
4115 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004116 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004117 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4118 return Start; // N = Start (as unsigned)
4119
4120 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004121 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004122 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004123 -StartC->getValue()->getValue(),
4124 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004125 }
Chris Lattner42a75512007-01-15 02:27:26 +00004126 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004127 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4128 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004129 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004130 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004131 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4132 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004133 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004134#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004135 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4136 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004137#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004138 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004139 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004140 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004141 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004142 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004143 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004144
Chris Lattner53e677a2004-04-02 20:23:17 +00004145 // We can only use this value if the chrec ends up with an exact zero
4146 // value at this index. When solving for "X*X != 5", for example, we
4147 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004148 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004149 if (Val->isZero())
4150 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004151 }
4152 }
4153 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004154
Dan Gohman1c343752009-06-27 21:21:31 +00004155 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004156}
4157
4158/// HowFarToNonZero - Return the number of times a backedge checking the
4159/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004160/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004161const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004162 // Loops that look like: while (X == 0) are very strange indeed. We don't
4163 // handle them yet except for the trivial case. This could be expanded in the
4164 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004165
Chris Lattner53e677a2004-04-02 20:23:17 +00004166 // If the value is a constant, check to see if it is known to be non-zero
4167 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004168 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004169 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004170 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004171 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004172 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004173
Chris Lattner53e677a2004-04-02 20:23:17 +00004174 // We could implement others, but I really doubt anyone writes loops like
4175 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004176 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004177}
4178
Dan Gohman859b4822009-05-18 15:36:09 +00004179/// getLoopPredecessor - If the given loop's header has exactly one unique
4180/// predecessor outside the loop, return it. Otherwise return null.
4181///
4182BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4183 BasicBlock *Header = L->getHeader();
4184 BasicBlock *Pred = 0;
4185 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4186 PI != E; ++PI)
4187 if (!L->contains(*PI)) {
4188 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4189 Pred = *PI;
4190 }
4191 return Pred;
4192}
4193
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004194/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4195/// (which may not be an immediate predecessor) which has exactly one
4196/// successor from which BB is reachable, or null if no such block is
4197/// found.
4198///
4199BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004200ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004201 // If the block has a unique predecessor, then there is no path from the
4202 // predecessor to the block that does not go through the direct edge
4203 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004204 if (BasicBlock *Pred = BB->getSinglePredecessor())
4205 return Pred;
4206
4207 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004208 // If the header has a unique predecessor outside the loop, it must be
4209 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004210 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004211 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004212
4213 return 0;
4214}
4215
Dan Gohman763bad12009-06-20 00:35:32 +00004216/// HasSameValue - SCEV structural equivalence is usually sufficient for
4217/// testing whether two expressions are equal, however for the purposes of
4218/// looking for a condition guarding a loop, it can be useful to be a little
4219/// more general, since a front-end may have replicated the controlling
4220/// expression.
4221///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004222static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004223 // Quick check to see if they are the same SCEV.
4224 if (A == B) return true;
4225
4226 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4227 // two different instructions with the same value. Check for this case.
4228 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4229 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4230 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4231 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4232 if (AI->isIdenticalTo(BI))
4233 return true;
4234
4235 // Otherwise assume they may have a different value.
4236 return false;
4237}
4238
Dan Gohman85b05a22009-07-13 21:35:55 +00004239bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4240 return getSignedRange(S).getSignedMax().isNegative();
4241}
4242
4243bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4244 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4245}
4246
4247bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4248 return !getSignedRange(S).getSignedMin().isNegative();
4249}
4250
4251bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4252 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4253}
4254
4255bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4256 return isKnownNegative(S) || isKnownPositive(S);
4257}
4258
4259bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4260 const SCEV *LHS, const SCEV *RHS) {
4261
4262 if (HasSameValue(LHS, RHS))
4263 return ICmpInst::isTrueWhenEqual(Pred);
4264
4265 switch (Pred) {
4266 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004267 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004268 break;
4269 case ICmpInst::ICMP_SGT:
4270 Pred = ICmpInst::ICMP_SLT;
4271 std::swap(LHS, RHS);
4272 case ICmpInst::ICMP_SLT: {
4273 ConstantRange LHSRange = getSignedRange(LHS);
4274 ConstantRange RHSRange = getSignedRange(RHS);
4275 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4276 return true;
4277 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4278 return false;
4279
4280 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4281 ConstantRange DiffRange = getUnsignedRange(Diff);
4282 if (isKnownNegative(Diff)) {
4283 if (DiffRange.getUnsignedMax().ult(LHSRange.getUnsignedMin()))
4284 return true;
4285 if (DiffRange.getUnsignedMin().uge(LHSRange.getUnsignedMax()))
4286 return false;
4287 } else if (isKnownPositive(Diff)) {
4288 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4289 return true;
4290 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4291 return false;
4292 }
4293 break;
4294 }
4295 case ICmpInst::ICMP_SGE:
4296 Pred = ICmpInst::ICMP_SLE;
4297 std::swap(LHS, RHS);
4298 case ICmpInst::ICMP_SLE: {
4299 ConstantRange LHSRange = getSignedRange(LHS);
4300 ConstantRange RHSRange = getSignedRange(RHS);
4301 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4302 return true;
4303 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4304 return false;
4305
4306 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4307 ConstantRange DiffRange = getUnsignedRange(Diff);
4308 if (isKnownNonPositive(Diff)) {
4309 if (DiffRange.getUnsignedMax().ule(LHSRange.getUnsignedMin()))
4310 return true;
4311 if (DiffRange.getUnsignedMin().ugt(LHSRange.getUnsignedMax()))
4312 return false;
4313 } else if (isKnownNonNegative(Diff)) {
4314 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4315 return true;
4316 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4317 return false;
4318 }
4319 break;
4320 }
4321 case ICmpInst::ICMP_UGT:
4322 Pred = ICmpInst::ICMP_ULT;
4323 std::swap(LHS, RHS);
4324 case ICmpInst::ICMP_ULT: {
4325 ConstantRange LHSRange = getUnsignedRange(LHS);
4326 ConstantRange RHSRange = getUnsignedRange(RHS);
4327 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4328 return true;
4329 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4330 return false;
4331
4332 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4333 ConstantRange DiffRange = getUnsignedRange(Diff);
4334 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4335 return true;
4336 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4337 return false;
4338 break;
4339 }
4340 case ICmpInst::ICMP_UGE:
4341 Pred = ICmpInst::ICMP_ULE;
4342 std::swap(LHS, RHS);
4343 case ICmpInst::ICMP_ULE: {
4344 ConstantRange LHSRange = getUnsignedRange(LHS);
4345 ConstantRange RHSRange = getUnsignedRange(RHS);
4346 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4347 return true;
4348 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4349 return false;
4350
4351 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4352 ConstantRange DiffRange = getUnsignedRange(Diff);
4353 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4354 return true;
4355 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4356 return false;
4357 break;
4358 }
4359 case ICmpInst::ICMP_NE: {
4360 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4361 return true;
4362 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4363 return true;
4364
4365 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4366 if (isKnownNonZero(Diff))
4367 return true;
4368 break;
4369 }
4370 case ICmpInst::ICMP_EQ:
4371 break;
4372 }
4373 return false;
4374}
4375
4376/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4377/// protected by a conditional between LHS and RHS. This is used to
4378/// to eliminate casts.
4379bool
4380ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4381 ICmpInst::Predicate Pred,
4382 const SCEV *LHS, const SCEV *RHS) {
4383 // Interpret a null as meaning no loop, where there is obviously no guard
4384 // (interprocedural conditions notwithstanding).
4385 if (!L) return true;
4386
4387 BasicBlock *Latch = L->getLoopLatch();
4388 if (!Latch)
4389 return false;
4390
4391 BranchInst *LoopContinuePredicate =
4392 dyn_cast<BranchInst>(Latch->getTerminator());
4393 if (!LoopContinuePredicate ||
4394 LoopContinuePredicate->isUnconditional())
4395 return false;
4396
4397 return
4398 isNecessaryCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4399 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4400}
4401
4402/// isLoopGuardedByCond - Test whether entry to the loop is protected
4403/// by a conditional between LHS and RHS. This is used to help avoid max
4404/// expressions in loop trip counts, and to eliminate casts.
4405bool
4406ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4407 ICmpInst::Predicate Pred,
4408 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004409 // Interpret a null as meaning no loop, where there is obviously no guard
4410 // (interprocedural conditions notwithstanding).
4411 if (!L) return false;
4412
Dan Gohman859b4822009-05-18 15:36:09 +00004413 BasicBlock *Predecessor = getLoopPredecessor(L);
4414 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004415
Dan Gohman859b4822009-05-18 15:36:09 +00004416 // Starting at the loop predecessor, climb up the predecessor chain, as long
4417 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004418 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004419 for (; Predecessor;
4420 PredecessorDest = Predecessor,
4421 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004422
4423 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004424 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004425 if (!LoopEntryPredicate ||
4426 LoopEntryPredicate->isUnconditional())
4427 continue;
4428
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004429 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4430 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004431 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004432 }
4433
Dan Gohman38372182008-08-12 20:17:31 +00004434 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004435}
4436
Dan Gohman85b05a22009-07-13 21:35:55 +00004437/// isNecessaryCond - Test whether the condition described by Pred, LHS,
4438/// and RHS is a necessary condition for the given Cond value to evaluate
4439/// to true.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004440bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4441 ICmpInst::Predicate Pred,
4442 const SCEV *LHS, const SCEV *RHS,
4443 bool Inverse) {
4444 // Recursivly handle And and Or conditions.
4445 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4446 if (BO->getOpcode() == Instruction::And) {
4447 if (!Inverse)
4448 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4449 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4450 } else if (BO->getOpcode() == Instruction::Or) {
4451 if (Inverse)
4452 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4453 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4454 }
4455 }
4456
4457 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4458 if (!ICI) return false;
4459
4460 // Now that we found a conditional branch that dominates the loop, check to
4461 // see if it is the comparison we are looking for.
4462 Value *PreCondLHS = ICI->getOperand(0);
4463 Value *PreCondRHS = ICI->getOperand(1);
Dan Gohman85b05a22009-07-13 21:35:55 +00004464 ICmpInst::Predicate FoundPred;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004465 if (Inverse)
Dan Gohman85b05a22009-07-13 21:35:55 +00004466 FoundPred = ICI->getInversePredicate();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004467 else
Dan Gohman85b05a22009-07-13 21:35:55 +00004468 FoundPred = ICI->getPredicate();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004469
Dan Gohman85b05a22009-07-13 21:35:55 +00004470 if (FoundPred == Pred)
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004471 ; // An exact match.
Dan Gohman85b05a22009-07-13 21:35:55 +00004472 else if (!ICmpInst::isTrueWhenEqual(FoundPred) && Pred == ICmpInst::ICMP_NE) {
4473 // The actual condition is beyond sufficient.
4474 FoundPred = ICmpInst::ICMP_NE;
4475 // NE is symmetric but the original comparison may not be. Swap
4476 // the operands if necessary so that they match below.
4477 if (isa<SCEVConstant>(LHS))
4478 std::swap(PreCondLHS, PreCondRHS);
4479 } else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004480 // Check a few special cases.
Dan Gohman85b05a22009-07-13 21:35:55 +00004481 switch (FoundPred) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004482 case ICmpInst::ICMP_UGT:
4483 if (Pred == ICmpInst::ICMP_ULT) {
4484 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman85b05a22009-07-13 21:35:55 +00004485 FoundPred = ICmpInst::ICMP_ULT;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004486 break;
4487 }
4488 return false;
4489 case ICmpInst::ICMP_SGT:
4490 if (Pred == ICmpInst::ICMP_SLT) {
4491 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman85b05a22009-07-13 21:35:55 +00004492 FoundPred = ICmpInst::ICMP_SLT;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004493 break;
4494 }
4495 return false;
4496 case ICmpInst::ICMP_NE:
4497 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4498 // so check for this case by checking if the NE is comparing against
4499 // a minimum or maximum constant.
4500 if (!ICmpInst::isTrueWhenEqual(Pred))
Dan Gohman85b05a22009-07-13 21:35:55 +00004501 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(RHS)) {
4502 const APInt &A = C->getValue()->getValue();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004503 switch (Pred) {
4504 case ICmpInst::ICMP_SLT:
4505 if (A.isMaxSignedValue()) break;
4506 return false;
4507 case ICmpInst::ICMP_SGT:
4508 if (A.isMinSignedValue()) break;
4509 return false;
4510 case ICmpInst::ICMP_ULT:
4511 if (A.isMaxValue()) break;
4512 return false;
4513 case ICmpInst::ICMP_UGT:
4514 if (A.isMinValue()) break;
4515 return false;
4516 default:
4517 return false;
4518 }
Dan Gohman85b05a22009-07-13 21:35:55 +00004519 FoundPred = Pred;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004520 // NE is symmetric but the original comparison may not be. Swap
4521 // the operands if necessary so that they match below.
4522 if (isa<SCEVConstant>(LHS))
4523 std::swap(PreCondLHS, PreCondRHS);
4524 break;
4525 }
4526 return false;
4527 default:
4528 // We weren't able to reconcile the condition.
4529 return false;
4530 }
4531
Dan Gohman85b05a22009-07-13 21:35:55 +00004532 assert(Pred == FoundPred && "Conditions were not reconciled!");
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004533
Dan Gohman85b05a22009-07-13 21:35:55 +00004534 // Bail if the ICmp's operands' types are wider than the needed type
4535 // before attempting to call getSCEV on them. This avoids infinite
4536 // recursion, since the analysis of widening casts can require loop
4537 // exit condition information for overflow checking, which would
4538 // lead back here.
4539 if (getTypeSizeInBits(LHS->getType()) <
4540 getTypeSizeInBits(PreCondLHS->getType()))
4541 return false;
4542
4543 const SCEV *FoundLHS = getSCEV(PreCondLHS);
4544 const SCEV *FoundRHS = getSCEV(PreCondRHS);
4545
4546 // Balance the types. The case where FoundLHS' type is wider than
4547 // LHS' type is checked for above.
4548 if (getTypeSizeInBits(LHS->getType()) >
4549 getTypeSizeInBits(FoundLHS->getType())) {
4550 if (CmpInst::isSigned(Pred)) {
4551 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4552 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4553 } else {
4554 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4555 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4556 }
4557 }
4558
4559 return isNecessaryCondOperands(Pred, LHS, RHS,
4560 FoundLHS, FoundRHS) ||
4561 // ~x < ~y --> x > y
4562 isNecessaryCondOperands(Pred, LHS, RHS,
4563 getNotSCEV(FoundRHS), getNotSCEV(FoundLHS));
4564}
4565
4566/// isNecessaryCondOperands - Test whether the condition described by Pred,
4567/// LHS, and RHS is a necessary condition for the condition described by
4568/// Pred, FoundLHS, and FoundRHS to evaluate to true.
4569bool
4570ScalarEvolution::isNecessaryCondOperands(ICmpInst::Predicate Pred,
4571 const SCEV *LHS, const SCEV *RHS,
4572 const SCEV *FoundLHS,
4573 const SCEV *FoundRHS) {
4574 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004575 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4576 case ICmpInst::ICMP_EQ:
4577 case ICmpInst::ICMP_NE:
4578 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4579 return true;
4580 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004581 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004582 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004583 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4584 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4585 return true;
4586 break;
4587 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004588 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004589 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4590 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4591 return true;
4592 break;
4593 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004594 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004595 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4596 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4597 return true;
4598 break;
4599 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004600 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004601 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4602 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4603 return true;
4604 break;
4605 }
4606
4607 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004608}
4609
Dan Gohman51f53b72009-06-21 23:46:38 +00004610/// getBECount - Subtract the end and start values and divide by the step,
4611/// rounding up, to get the number of times the backedge is executed. Return
4612/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004613const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004614 const SCEV *End,
4615 const SCEV *Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004616 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004617 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4618 const SCEV *Diff = getMinusSCEV(End, Start);
4619 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004620
4621 // Add an adjustment to the difference between End and Start so that
4622 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004623 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004624
4625 // Check Add for unsigned overflow.
4626 // TODO: More sophisticated things could be done here.
Owen Anderson76f600b2009-07-06 22:37:39 +00004627 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman85b05a22009-07-13 21:35:55 +00004628 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4629 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4630 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004631 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohman1c343752009-06-27 21:21:31 +00004632 return getCouldNotCompute();
Dan Gohman51f53b72009-06-21 23:46:38 +00004633
4634 return getUDivExpr(Add, Step);
4635}
4636
Chris Lattnerdb25de42005-08-15 23:33:51 +00004637/// HowManyLessThans - Return the number of times a backedge containing the
4638/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004639/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004640ScalarEvolution::BackedgeTakenInfo
4641ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4642 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004643 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004644 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004645
Dan Gohman35738ac2009-05-04 22:30:44 +00004646 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004647 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004648 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004649
4650 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004651 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004652 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004653 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004654
4655 // TODO: handle non-constant strides.
4656 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4657 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004658 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004659 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004660 // With unit stride, the iteration never steps past the limit value.
4661 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4662 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4663 // Test whether a positive iteration iteration can step past the limit
4664 // value and past the maximum value for its type in a single step.
4665 if (isSigned) {
4666 APInt Max = APInt::getSignedMaxValue(BitWidth);
4667 if ((Max - CStep->getValue()->getValue())
4668 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004669 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004670 } else {
4671 APInt Max = APInt::getMaxValue(BitWidth);
4672 if ((Max - CStep->getValue()->getValue())
4673 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004674 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004675 }
4676 } else
4677 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004678 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004679 } else
4680 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004681 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004682
Dan Gohmana1af7572009-04-30 20:47:05 +00004683 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4684 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4685 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004686 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004687
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004688 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004689 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004690
Dan Gohmana1af7572009-04-30 20:47:05 +00004691 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004692 const SCEV *MinStart = getConstant(isSigned ?
4693 getSignedRange(Start).getSignedMin() :
4694 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004695
Dan Gohmana1af7572009-04-30 20:47:05 +00004696 // If we know that the condition is true in order to enter the loop,
4697 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004698 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4699 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004700 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004701 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00004702 isSigned ? ICmpInst::ICMP_SLT :
4703 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00004704 getMinusSCEV(Start, Step), RHS))
4705 End = isSigned ? getSMaxExpr(RHS, Start)
4706 : getUMaxExpr(RHS, Start);
4707
4708 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004709 const SCEV *MaxEnd = getConstant(isSigned ?
4710 getSignedRange(End).getSignedMax() :
4711 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00004712
4713 // Finally, we subtract these two values and divide, rounding up, to get
4714 // the number of times the backedge is executed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004715 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004716
4717 // The maximum backedge count is similar, except using the minimum start
4718 // value and the maximum end value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004719 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004720
4721 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004722 }
4723
Dan Gohman1c343752009-06-27 21:21:31 +00004724 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004725}
4726
Chris Lattner53e677a2004-04-02 20:23:17 +00004727/// getNumIterationsInRange - Return the number of iterations of this loop that
4728/// produce values in the specified constant range. Another way of looking at
4729/// this is that it returns the first iteration number where the value is not in
4730/// the condition, thus computing the exit count. If the iteration count can't
4731/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004732const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004733 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004734 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004735 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004736
4737 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004738 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004739 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004740 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004741 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004742 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004743 if (const SCEVAddRecExpr *ShiftedAddRec =
4744 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004745 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004746 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004747 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004748 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004749 }
4750
4751 // The only time we can solve this is when we have all constant indices.
4752 // Otherwise, we cannot determine the overflow conditions.
4753 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4754 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004755 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004756
4757
4758 // Okay at this point we know that all elements of the chrec are constants and
4759 // that the start element is zero.
4760
4761 // First check to see if the range contains zero. If not, the first
4762 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004763 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004764 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004765 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004766
Chris Lattner53e677a2004-04-02 20:23:17 +00004767 if (isAffine()) {
4768 // If this is an affine expression then we have this situation:
4769 // Solve {0,+,A} in Range === Ax in Range
4770
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004771 // We know that zero is in the range. If A is positive then we know that
4772 // the upper value of the range must be the first possible exit value.
4773 // If A is negative then the lower of the range is the last possible loop
4774 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004775 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004776 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4777 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004778
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004779 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004780 APInt ExitVal = (End + A).udiv(A);
Owen Anderson76f600b2009-07-06 22:37:39 +00004781 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004782
4783 // Evaluate at the exit value. If we really did fall out of the valid
4784 // range, then we computed our trip count, otherwise wrap around or other
4785 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004786 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004787 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004788 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004789
4790 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004791 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00004792 EvaluateConstantChrecAtConstant(this,
Owen Anderson76f600b2009-07-06 22:37:39 +00004793 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004794 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004795 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004796 } else if (isQuadratic()) {
4797 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4798 // quadratic equation to solve it. To do this, we must frame our problem in
4799 // terms of figuring out when zero is crossed, instead of when
4800 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004801 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004802 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00004803 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004804
4805 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00004806 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004807 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004808 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4809 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004810 if (R1) {
4811 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004812 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004813 dyn_cast<ConstantInt>(
4814 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4815 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004816 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004817 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004818
Chris Lattner53e677a2004-04-02 20:23:17 +00004819 // Make sure the root is not off by one. The returned iteration should
4820 // not be in the range, but the previous one should be. When solving
4821 // for "X*X < 5", for example, we should not return a root of 2.
4822 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004823 R1->getValue(),
4824 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004825 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004826 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00004827 ConstantInt *NextVal =
4828 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004829
Dan Gohman246b2562007-10-22 18:31:58 +00004830 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004831 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004832 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004833 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004834 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004835
Chris Lattner53e677a2004-04-02 20:23:17 +00004836 // If R1 was not in the range, then it is a good return value. Make
4837 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00004838 ConstantInt *NextVal =
4839 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004840 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004841 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004842 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004843 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004844 }
4845 }
4846 }
4847
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004848 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004849}
4850
4851
4852
4853//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004854// SCEVCallbackVH Class Implementation
4855//===----------------------------------------------------------------------===//
4856
Dan Gohman1959b752009-05-19 19:22:47 +00004857void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00004858 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004859 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4860 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004861 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4862 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004863 SE->Scalars.erase(getValPtr());
4864 // this now dangles!
4865}
4866
Dan Gohman1959b752009-05-19 19:22:47 +00004867void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00004868 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004869
4870 // Forget all the expressions associated with users of the old value,
4871 // so that future queries will recompute the expressions using the new
4872 // value.
4873 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00004874 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00004875 Value *Old = getValPtr();
4876 bool DeleteOld = false;
4877 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4878 UI != UE; ++UI)
4879 Worklist.push_back(*UI);
4880 while (!Worklist.empty()) {
4881 User *U = Worklist.pop_back_val();
4882 // Deleting the Old value will cause this to dangle. Postpone
4883 // that until everything else is done.
4884 if (U == Old) {
4885 DeleteOld = true;
4886 continue;
4887 }
Dan Gohman69fcae92009-07-14 14:34:04 +00004888 if (!Visited.insert(U))
4889 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00004890 if (PHINode *PN = dyn_cast<PHINode>(U))
4891 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004892 if (Instruction *I = dyn_cast<Instruction>(U))
4893 SE->ValuesAtScopes.erase(I);
Dan Gohman69fcae92009-07-14 14:34:04 +00004894 SE->Scalars.erase(U);
4895 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4896 UI != UE; ++UI)
4897 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00004898 }
Dan Gohman69fcae92009-07-14 14:34:04 +00004899 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00004900 if (DeleteOld) {
4901 if (PHINode *PN = dyn_cast<PHINode>(Old))
4902 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004903 if (Instruction *I = dyn_cast<Instruction>(Old))
4904 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004905 SE->Scalars.erase(Old);
4906 // this now dangles!
4907 }
4908 // this may dangle!
4909}
4910
Dan Gohman1959b752009-05-19 19:22:47 +00004911ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004912 : CallbackVH(V), SE(se) {}
4913
4914//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004915// ScalarEvolution Class Implementation
4916//===----------------------------------------------------------------------===//
4917
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004918ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00004919 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004920}
4921
Chris Lattner53e677a2004-04-02 20:23:17 +00004922bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004923 this->F = &F;
4924 LI = &getAnalysis<LoopInfo>();
4925 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004926 return false;
4927}
4928
4929void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004930 Scalars.clear();
4931 BackedgeTakenCounts.clear();
4932 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004933 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00004934 UniqueSCEVs.clear();
4935 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00004936}
4937
4938void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4939 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004940 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004941}
4942
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004943bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004944 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004945}
4946
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004947static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004948 const Loop *L) {
4949 // Print all inner loops first
4950 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4951 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004952
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004953 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004954
Devang Patelb7211a22007-08-21 00:31:24 +00004955 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004956 L->getExitBlocks(ExitBlocks);
4957 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004958 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004959
Dan Gohman46bdfb02009-02-24 18:55:53 +00004960 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4961 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004962 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004963 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004964 }
4965
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004966 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00004967 OS << "Loop " << L->getHeader()->getName() << ": ";
4968
4969 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4970 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4971 } else {
4972 OS << "Unpredictable max backedge-taken count. ";
4973 }
4974
4975 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004976}
4977
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004978void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004979 // ScalarEvolution's implementaiton of the print method is to print
4980 // out SCEV values of all instructions that are interesting. Doing
4981 // this potentially causes it to create new SCEV objects though,
4982 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00004983 // observable from outside the class though, so casting away the
4984 // const isn't dangerous.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004985 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004986
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004987 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004988 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004989 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00004990 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00004991 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00004992 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004993 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004994
Dan Gohman0c689c52009-06-19 17:49:54 +00004995 const Loop *L = LI->getLoopFor((*I).getParent());
4996
Dan Gohman0bba49c2009-07-07 17:06:11 +00004997 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00004998 if (AtUse != SV) {
4999 OS << " --> ";
5000 AtUse->print(OS);
5001 }
5002
5003 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005004 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005005 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005006 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005007 OS << "<<Unknown>>";
5008 } else {
5009 OS << *ExitValue;
5010 }
5011 }
5012
Chris Lattner53e677a2004-04-02 20:23:17 +00005013 OS << "\n";
5014 }
5015
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005016 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5017 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5018 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005019}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005020
5021void ScalarEvolution::print(std::ostream &o, const Module *M) const {
5022 raw_os_ostream OS(o);
5023 print(OS, M);
5024}