blob: 0152a9ff061230ed9ebea666b40459f9be84bf87 [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 Edwinc25e7582009-07-11 20:10:48 +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 Edwinc25e7582009-07-11 20:10:48 +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 Edwinc25e7582009-07-11 20:10:48 +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) {
199 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
200}
201
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000202const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000203
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000204void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205 WriteAsOperand(OS, V, false);
206}
Chris Lattner53e677a2004-04-02 20:23:17 +0000207
Dan Gohmanc050fd92009-07-13 20:50:19 +0000208SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
209 unsigned SCEVTy, const SCEV *op, const Type *ty)
210 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000211
Dan Gohman84923602009-04-21 01:25:57 +0000212bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
213 return Op->dominates(BB, DT);
214}
215
Dan Gohmanc050fd92009-07-13 20:50:19 +0000216SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
217 const SCEV *op, const Type *ty)
218 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000219 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
220 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000222}
Chris Lattner53e677a2004-04-02 20:23:17 +0000223
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000224void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000225 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000226}
227
Dan Gohmanc050fd92009-07-13 20:50:19 +0000228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
229 const SCEV *op, const Type *ty)
230 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000231 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
232 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234}
235
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000236void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000237 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000238}
239
Dan Gohmanc050fd92009-07-13 20:50:19 +0000240SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
241 const SCEV *op, const Type *ty)
242 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000243 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
244 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000245 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000246}
247
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000248void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000249 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000250}
251
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000252void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000253 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
254 const char *OpStr = getOperationStr();
255 OS << "(" << *Operands[0];
256 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
257 OS << OpStr << *Operands[i];
258 OS << ")";
259}
260
Dan Gohman64a845e2009-06-24 04:48:43 +0000261const SCEV *
262SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
263 const SCEV *Sym,
264 const SCEV *Conc,
265 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000266 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000267 const SCEV *H =
Dan Gohman246b2562007-10-22 18:31:58 +0000268 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000269 if (H != getOperand(i)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000270 SmallVector<const SCEV *, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000271 NewOps.reserve(getNumOperands());
272 for (unsigned j = 0; j != i; ++j)
273 NewOps.push_back(getOperand(j));
274 NewOps.push_back(H);
275 for (++i; i != e; ++i)
276 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000277 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000278
279 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000280 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000281 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000282 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000283 else if (isa<SCEVSMaxExpr>(this))
284 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000285 else if (isa<SCEVUMaxExpr>(this))
286 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000287 else
Torok Edwinc25e7582009-07-11 20:10:48 +0000288 LLVM_UNREACHABLE("Unknown commutative expr!");
Chris Lattner4dc534c2005-02-13 04:37:18 +0000289 }
290 }
291 return this;
292}
293
Dan Gohmanecb403a2009-05-07 14:00:19 +0000294bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000295 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
296 if (!getOperand(i)->dominates(BB, DT))
297 return false;
298 }
299 return true;
300}
301
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000302bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
303 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
304}
305
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000306void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000307 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000308}
309
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000310const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000311 // In most cases the types of LHS and RHS will be the same, but in some
312 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
313 // depend on the type for correctness, but handling types carefully can
314 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
315 // a pointer type than the RHS, so use the RHS' type here.
316 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000317}
318
Dan Gohman64a845e2009-06-24 04:48:43 +0000319const SCEV *
320SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
321 const SCEV *Conc,
322 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000323 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000324 const SCEV *H =
Dan Gohman246b2562007-10-22 18:31:58 +0000325 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000326 if (H != getOperand(i)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000327 SmallVector<const SCEV *, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000328 NewOps.reserve(getNumOperands());
329 for (unsigned j = 0; j != i; ++j)
330 NewOps.push_back(getOperand(j));
331 NewOps.push_back(H);
332 for (++i; i != e; ++i)
333 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000334 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000335
Dan Gohman246b2562007-10-22 18:31:58 +0000336 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000337 }
338 }
339 return this;
340}
341
342
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000343bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000344 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000345 if (!QueryLoop)
346 return false;
347
348 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
349 if (QueryLoop->contains(L->getHeader()))
350 return false;
351
352 // This recurrence is variant w.r.t. QueryLoop if any of its operands
353 // are variant.
354 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
355 if (!getOperand(i)->isLoopInvariant(QueryLoop))
356 return false;
357
358 // Otherwise it's loop-invariant.
359 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000360}
361
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000362void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363 OS << "{" << *Operands[0];
364 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
365 OS << ",+," << *Operands[i];
366 OS << "}<" << L->getHeader()->getName() + ">";
367}
Chris Lattner53e677a2004-04-02 20:23:17 +0000368
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000369bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
370 // All non-instruction values are loop invariant. All instructions are loop
371 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000372 // Instructions are never considered invariant in the function body
373 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000374 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000375 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000376 return true;
377}
Chris Lattner53e677a2004-04-02 20:23:17 +0000378
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000379bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
380 if (Instruction *I = dyn_cast<Instruction>(getValue()))
381 return DT->dominates(I->getParent(), BB);
382 return true;
383}
384
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385const Type *SCEVUnknown::getType() const {
386 return V->getType();
387}
Chris Lattner53e677a2004-04-02 20:23:17 +0000388
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000389void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000390 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000391}
392
Chris Lattner8d741b82004-06-20 06:23:15 +0000393//===----------------------------------------------------------------------===//
394// SCEV Utilities
395//===----------------------------------------------------------------------===//
396
397namespace {
398 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
399 /// than the complexity of the RHS. This comparator is used to canonicalize
400 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000401 class VISIBILITY_HIDDEN SCEVComplexityCompare {
402 LoopInfo *LI;
403 public:
404 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
405
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000406 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000407 // Primarily, sort the SCEVs by their getSCEVType().
408 if (LHS->getSCEVType() != RHS->getSCEVType())
409 return LHS->getSCEVType() < RHS->getSCEVType();
410
411 // Aside from the getSCEVType() ordering, the particular ordering
412 // isn't very important except that it's beneficial to be consistent,
413 // so that (a + b) and (b + a) don't end up as different expressions.
414
415 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
416 // not as complete as it could be.
417 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
418 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
419
Dan Gohman5be18e82009-05-19 02:15:55 +0000420 // Order pointer values after integer values. This helps SCEVExpander
421 // form GEPs.
422 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
423 return false;
424 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
425 return true;
426
Dan Gohman72861302009-05-07 14:39:04 +0000427 // Compare getValueID values.
428 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
429 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
430
431 // Sort arguments by their position.
432 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
433 const Argument *RA = cast<Argument>(RU->getValue());
434 return LA->getArgNo() < RA->getArgNo();
435 }
436
437 // For instructions, compare their loop depth, and their opcode.
438 // This is pretty loose.
439 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
440 Instruction *RV = cast<Instruction>(RU->getValue());
441
442 // Compare loop depths.
443 if (LI->getLoopDepth(LV->getParent()) !=
444 LI->getLoopDepth(RV->getParent()))
445 return LI->getLoopDepth(LV->getParent()) <
446 LI->getLoopDepth(RV->getParent());
447
448 // Compare opcodes.
449 if (LV->getOpcode() != RV->getOpcode())
450 return LV->getOpcode() < RV->getOpcode();
451
452 // Compare the number of operands.
453 if (LV->getNumOperands() != RV->getNumOperands())
454 return LV->getNumOperands() < RV->getNumOperands();
455 }
456
457 return false;
458 }
459
Dan Gohman4dfad292009-06-14 22:51:25 +0000460 // Compare constant values.
461 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
462 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000463 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
464 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000465 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
466 }
467
468 // Compare addrec loop depths.
469 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
470 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
471 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
472 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
473 }
Dan Gohman72861302009-05-07 14:39:04 +0000474
475 // Lexicographically compare n-ary expressions.
476 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
477 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
478 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
479 if (i >= RC->getNumOperands())
480 return false;
481 if (operator()(LC->getOperand(i), RC->getOperand(i)))
482 return true;
483 if (operator()(RC->getOperand(i), LC->getOperand(i)))
484 return false;
485 }
486 return LC->getNumOperands() < RC->getNumOperands();
487 }
488
Dan Gohmana6b35e22009-05-07 19:23:21 +0000489 // Lexicographically compare udiv expressions.
490 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
491 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
492 if (operator()(LC->getLHS(), RC->getLHS()))
493 return true;
494 if (operator()(RC->getLHS(), LC->getLHS()))
495 return false;
496 if (operator()(LC->getRHS(), RC->getRHS()))
497 return true;
498 if (operator()(RC->getRHS(), LC->getRHS()))
499 return false;
500 return false;
501 }
502
Dan Gohman72861302009-05-07 14:39:04 +0000503 // Compare cast expressions by operand.
504 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
505 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
506 return operator()(LC->getOperand(), RC->getOperand());
507 }
508
Torok Edwinc25e7582009-07-11 20:10:48 +0000509 LLVM_UNREACHABLE("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000510 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000511 }
512 };
513}
514
515/// GroupByComplexity - Given a list of SCEV objects, order them by their
516/// complexity, and group objects of the same complexity together by value.
517/// When this routine is finished, we know that any duplicates in the vector are
518/// consecutive and that complexity is monotonically increasing.
519///
520/// Note that we go take special precautions to ensure that we get determinstic
521/// results from this routine. In other words, we don't want the results of
522/// this to depend on where the addresses of various SCEV objects happened to
523/// land in memory.
524///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000525static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000526 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000527 if (Ops.size() < 2) return; // Noop
528 if (Ops.size() == 2) {
529 // This is the common case, which also happens to be trivially simple.
530 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000531 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000532 std::swap(Ops[0], Ops[1]);
533 return;
534 }
535
536 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000537 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000538
539 // Now that we are sorted by complexity, group elements of the same
540 // complexity. Note that this is, at worst, N^2, but the vector is likely to
541 // be extremely short in practice. Note that we take this approach because we
542 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000543 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000544 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000545 unsigned Complexity = S->getSCEVType();
546
547 // If there are any objects of the same complexity and same value as this
548 // one, group them.
549 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
550 if (Ops[j] == S) { // Found a duplicate.
551 // Move it to immediately after i'th element.
552 std::swap(Ops[i+1], Ops[j]);
553 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000554 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000555 }
556 }
557 }
558}
559
Chris Lattner53e677a2004-04-02 20:23:17 +0000560
Chris Lattner53e677a2004-04-02 20:23:17 +0000561
562//===----------------------------------------------------------------------===//
563// Simple SCEV method implementations
564//===----------------------------------------------------------------------===//
565
Eli Friedmanb42a6262008-08-04 23:49:06 +0000566/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000567/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000568static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000569 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000570 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000571 // Handle the simplest case efficiently.
572 if (K == 1)
573 return SE.getTruncateOrZeroExtend(It, ResultTy);
574
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000575 // We are using the following formula for BC(It, K):
576 //
577 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
578 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000579 // Suppose, W is the bitwidth of the return value. We must be prepared for
580 // overflow. Hence, we must assure that the result of our computation is
581 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
582 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000583 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000584 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000585 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000586 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
587 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000588 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000589 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000590 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000591 // This formula is trivially equivalent to the previous formula. However,
592 // this formula can be implemented much more efficiently. The trick is that
593 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
594 // arithmetic. To do exact division in modular arithmetic, all we have
595 // to do is multiply by the inverse. Therefore, this step can be done at
596 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000597 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000598 // The next issue is how to safely do the division by 2^T. The way this
599 // is done is by doing the multiplication step at a width of at least W + T
600 // bits. This way, the bottom W+T bits of the product are accurate. Then,
601 // when we perform the division by 2^T (which is equivalent to a right shift
602 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
603 // truncated out after the division by 2^T.
604 //
605 // In comparison to just directly using the first formula, this technique
606 // is much more efficient; using the first formula requires W * K bits,
607 // but this formula less than W + K bits. Also, the first formula requires
608 // a division step, whereas this formula only requires multiplies and shifts.
609 //
610 // It doesn't matter whether the subtraction step is done in the calculation
611 // width or the input iteration count's width; if the subtraction overflows,
612 // the result must be zero anyway. We prefer here to do it in the width of
613 // the induction variable because it helps a lot for certain cases; CodeGen
614 // isn't smart enough to ignore the overflow, which leads to much less
615 // efficient code if the width of the subtraction is wider than the native
616 // register width.
617 //
618 // (It's possible to not widen at all by pulling out factors of 2 before
619 // the multiplication; for example, K=2 can be calculated as
620 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
621 // extra arithmetic, so it's not an obvious win, and it gets
622 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000623
Eli Friedmanb42a6262008-08-04 23:49:06 +0000624 // Protection from insane SCEVs; this bound is conservative,
625 // but it probably doesn't matter.
626 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000627 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000628
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000629 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000630
Eli Friedmanb42a6262008-08-04 23:49:06 +0000631 // Calculate K! / 2^T and T; we divide out the factors of two before
632 // multiplying for calculating K! / 2^T to avoid overflow.
633 // Other overflow doesn't matter because we only care about the bottom
634 // W bits of the result.
635 APInt OddFactorial(W, 1);
636 unsigned T = 1;
637 for (unsigned i = 3; i <= K; ++i) {
638 APInt Mult(W, i);
639 unsigned TwoFactors = Mult.countTrailingZeros();
640 T += TwoFactors;
641 Mult = Mult.lshr(TwoFactors);
642 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000643 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000644
Eli Friedmanb42a6262008-08-04 23:49:06 +0000645 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000646 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000647
648 // Calcuate 2^T, at width T+W.
649 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
650
651 // Calculate the multiplicative inverse of K! / 2^T;
652 // this multiplication factor will perform the exact division by
653 // K! / 2^T.
654 APInt Mod = APInt::getSignedMinValue(W+1);
655 APInt MultiplyFactor = OddFactorial.zext(W+1);
656 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
657 MultiplyFactor = MultiplyFactor.trunc(W);
658
659 // Calculate the product, at width T+W
660 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000661 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000662 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000663 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000664 Dividend = SE.getMulExpr(Dividend,
665 SE.getTruncateOrZeroExtend(S, CalculationTy));
666 }
667
668 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000669 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000670
671 // Truncate the result, and divide by K! / 2^T.
672
673 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
674 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000675}
676
Chris Lattner53e677a2004-04-02 20:23:17 +0000677/// evaluateAtIteration - Return the value of this chain of recurrences at
678/// the specified iteration number. We can evaluate this recurrence by
679/// multiplying each element in the chain by the binomial coefficient
680/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
681///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000682/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000683///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000684/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000685///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000686const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman246b2562007-10-22 18:31:58 +0000687 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000688 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000689 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000690 // The computation is correct in the face of overflow provided that the
691 // multiplication is performed _after_ the evaluation of the binomial
692 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000693 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000694 if (isa<SCEVCouldNotCompute>(Coeff))
695 return Coeff;
696
697 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000698 }
699 return Result;
700}
701
Chris Lattner53e677a2004-04-02 20:23:17 +0000702//===----------------------------------------------------------------------===//
703// SCEV Expression folder implementations
704//===----------------------------------------------------------------------===//
705
Dan Gohman0bba49c2009-07-07 17:06:11 +0000706const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000707 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000708 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000709 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000710 assert(isSCEVable(Ty) &&
711 "This is not a conversion to a SCEVable type!");
712 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000713
Dan Gohmanc050fd92009-07-13 20:50:19 +0000714 FoldingSetNodeID ID;
715 ID.AddInteger(scTruncate);
716 ID.AddPointer(Op);
717 ID.AddPointer(Ty);
718 void *IP = 0;
719 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
720
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000721 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000722 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000723 return getConstant(
724 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000725
Dan Gohman20900ca2009-04-22 16:20:48 +0000726 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000727 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000728 return getTruncateExpr(ST->getOperand(), Ty);
729
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000730 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000731 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000732 return getTruncateOrSignExtend(SS->getOperand(), Ty);
733
734 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000735 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000736 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
737
Dan Gohman6864db62009-06-18 16:24:47 +0000738 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000739 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000740 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000741 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000742 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
743 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000744 }
745
Dan Gohmanc050fd92009-07-13 20:50:19 +0000746 // The cast wasn't folded; create an explicit cast node.
747 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000748 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
749 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000750 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000751 UniqueSCEVs.InsertNode(S, IP);
752 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000753}
754
Dan Gohman0bba49c2009-07-07 17:06:11 +0000755const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000756 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000757 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000758 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000759 assert(isSCEVable(Ty) &&
760 "This is not a conversion to a SCEVable type!");
761 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000762
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000763 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000764 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000765 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000766 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
767 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000768 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000769 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000770
Dan Gohman20900ca2009-04-22 16:20:48 +0000771 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000772 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000773 return getZeroExtendExpr(SZ->getOperand(), Ty);
774
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000775 // Before doing any expensive analysis, check to see if we've already
776 // computed a SCEV for this Op and Ty.
777 FoldingSetNodeID ID;
778 ID.AddInteger(scZeroExtend);
779 ID.AddPointer(Op);
780 ID.AddPointer(Ty);
781 void *IP = 0;
782 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
783
Dan Gohman01ecca22009-04-27 20:16:15 +0000784 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000785 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000786 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000787 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000788 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000789 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000790 const SCEV *Start = AR->getStart();
791 const SCEV *Step = AR->getStepRecurrence(*this);
792 unsigned BitWidth = getTypeSizeInBits(AR->getType());
793 const Loop *L = AR->getLoop();
794
Dan Gohman01ecca22009-04-27 20:16:15 +0000795 // Check whether the backedge-taken count is SCEVCouldNotCompute.
796 // Note that this serves two purposes: It filters out loops that are
797 // simply not analyzable, and it covers the case where this code is
798 // being called from within backedge-taken count analysis, such that
799 // attempting to ask for the backedge-taken count would likely result
800 // in infinite recursion. In the later case, the analysis code will
801 // cope with a conservative value, and it will take care to purge
802 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000803 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000804 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000805 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000806 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000807
808 // Check whether the backedge-taken count can be losslessly casted to
809 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000810 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000811 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000812 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000813 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
814 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000815 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000816 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000817 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000818 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000819 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000820 const SCEV *Add = getAddExpr(Start, ZMul);
821 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000822 getAddExpr(getZeroExtendExpr(Start, WideTy),
823 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
824 getZeroExtendExpr(Step, WideTy)));
825 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000826 // Return the expression with the addrec on the outside.
827 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
828 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000829 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000830
831 // Similar to above, only this time treat the step value as signed.
832 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000833 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000834 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000835 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000836 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000837 OperandExtendedAdd =
838 getAddExpr(getZeroExtendExpr(Start, WideTy),
839 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
840 getSignExtendExpr(Step, WideTy)));
841 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000842 // Return the expression with the addrec on the outside.
843 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
844 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000845 L);
846 }
847
848 // If the backedge is guarded by a comparison with the pre-inc value
849 // the addrec is safe. Also, if the entry is guarded by a comparison
850 // with the start value and the backedge is guarded by a comparison
851 // with the post-inc value, the addrec is safe.
852 if (isKnownPositive(Step)) {
853 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
854 getUnsignedRange(Step).getUnsignedMax());
855 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
856 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
857 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
858 AR->getPostIncExpr(*this), N)))
859 // Return the expression with the addrec on the outside.
860 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
861 getZeroExtendExpr(Step, Ty),
862 L);
863 } else if (isKnownNegative(Step)) {
864 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
865 getSignedRange(Step).getSignedMin());
866 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
867 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
868 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
869 AR->getPostIncExpr(*this), N)))
870 // Return the expression with the addrec on the outside.
871 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
872 getSignExtendExpr(Step, Ty),
873 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000874 }
875 }
876 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000877
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000878 // The cast wasn't folded; create an explicit cast node.
879 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000880 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
881 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000882 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000883 UniqueSCEVs.InsertNode(S, IP);
884 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000885}
886
Dan Gohman0bba49c2009-07-07 17:06:11 +0000887const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000888 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000889 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000890 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000891 assert(isSCEVable(Ty) &&
892 "This is not a conversion to a SCEVable type!");
893 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000894
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000895 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000896 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000897 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000898 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
899 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000900 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000901 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000902
Dan Gohman20900ca2009-04-22 16:20:48 +0000903 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000904 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000905 return getSignExtendExpr(SS->getOperand(), Ty);
906
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000907 // Before doing any expensive analysis, check to see if we've already
908 // computed a SCEV for this Op and Ty.
909 FoldingSetNodeID ID;
910 ID.AddInteger(scSignExtend);
911 ID.AddPointer(Op);
912 ID.AddPointer(Ty);
913 void *IP = 0;
914 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
915
Dan Gohman01ecca22009-04-27 20:16:15 +0000916 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000917 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000918 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000919 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000920 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000921 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000922 const SCEV *Start = AR->getStart();
923 const SCEV *Step = AR->getStepRecurrence(*this);
924 unsigned BitWidth = getTypeSizeInBits(AR->getType());
925 const Loop *L = AR->getLoop();
926
Dan Gohman01ecca22009-04-27 20:16:15 +0000927 // Check whether the backedge-taken count is SCEVCouldNotCompute.
928 // Note that this serves two purposes: It filters out loops that are
929 // simply not analyzable, and it covers the case where this code is
930 // being called from within backedge-taken count analysis, such that
931 // attempting to ask for the backedge-taken count would likely result
932 // in infinite recursion. In the later case, the analysis code will
933 // cope with a conservative value, and it will take care to purge
934 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000935 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000936 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000937 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000938 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000939
940 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000941 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000942 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000943 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000944 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000945 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
946 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000947 const Type *WideTy = IntegerType::get(BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000948 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000949 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000950 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000951 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000952 const SCEV *Add = getAddExpr(Start, SMul);
953 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000954 getAddExpr(getSignExtendExpr(Start, WideTy),
955 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
956 getSignExtendExpr(Step, WideTy)));
957 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000958 // Return the expression with the addrec on the outside.
959 return getAddRecExpr(getSignExtendExpr(Start, Ty),
960 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000961 L);
962 }
963
964 // If the backedge is guarded by a comparison with the pre-inc value
965 // the addrec is safe. Also, if the entry is guarded by a comparison
966 // with the start value and the backedge is guarded by a comparison
967 // with the post-inc value, the addrec is safe.
968 if (isKnownPositive(Step)) {
969 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
970 getSignedRange(Step).getSignedMax());
971 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
972 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
973 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
974 AR->getPostIncExpr(*this), N)))
975 // Return the expression with the addrec on the outside.
976 return getAddRecExpr(getSignExtendExpr(Start, Ty),
977 getSignExtendExpr(Step, Ty),
978 L);
979 } else if (isKnownNegative(Step)) {
980 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
981 getSignedRange(Step).getSignedMin());
982 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
983 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
984 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
985 AR->getPostIncExpr(*this), N)))
986 // Return the expression with the addrec on the outside.
987 return getAddRecExpr(getSignExtendExpr(Start, Ty),
988 getSignExtendExpr(Step, Ty),
989 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000990 }
991 }
992 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000993
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000994 // The cast wasn't folded; create an explicit cast node.
995 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000996 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
997 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000998 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000999 UniqueSCEVs.InsertNode(S, IP);
1000 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001001}
1002
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001003/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1004/// unspecified bits out to the given type.
1005///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001006const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001007 const Type *Ty) {
1008 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1009 "This is not an extending conversion!");
1010 assert(isSCEVable(Ty) &&
1011 "This is not a conversion to a SCEVable type!");
1012 Ty = getEffectiveSCEVType(Ty);
1013
1014 // Sign-extend negative constants.
1015 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1016 if (SC->getValue()->getValue().isNegative())
1017 return getSignExtendExpr(Op, Ty);
1018
1019 // Peel off a truncate cast.
1020 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001021 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001022 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1023 return getAnyExtendExpr(NewOp, Ty);
1024 return getTruncateOrNoop(NewOp, Ty);
1025 }
1026
1027 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001028 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001029 if (!isa<SCEVZeroExtendExpr>(ZExt))
1030 return ZExt;
1031
1032 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001033 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001034 if (!isa<SCEVSignExtendExpr>(SExt))
1035 return SExt;
1036
1037 // If the expression is obviously signed, use the sext cast value.
1038 if (isa<SCEVSMaxExpr>(Op))
1039 return SExt;
1040
1041 // Absent any other information, use the zext cast value.
1042 return ZExt;
1043}
1044
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001045/// CollectAddOperandsWithScales - Process the given Ops list, which is
1046/// a list of operands to be added under the given scale, update the given
1047/// map. This is a helper function for getAddRecExpr. As an example of
1048/// what it does, given a sequence of operands that would form an add
1049/// expression like this:
1050///
1051/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1052///
1053/// where A and B are constants, update the map with these values:
1054///
1055/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1056///
1057/// and add 13 + A*B*29 to AccumulatedConstant.
1058/// This will allow getAddRecExpr to produce this:
1059///
1060/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1061///
1062/// This form often exposes folding opportunities that are hidden in
1063/// the original operand list.
1064///
1065/// Return true iff it appears that any interesting folding opportunities
1066/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1067/// the common case where no interesting opportunities are present, and
1068/// is also used as a check to avoid infinite recursion.
1069///
1070static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001071CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1072 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001073 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001074 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001075 const APInt &Scale,
1076 ScalarEvolution &SE) {
1077 bool Interesting = false;
1078
1079 // Iterate over the add operands.
1080 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1081 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1082 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1083 APInt NewScale =
1084 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1085 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1086 // A multiplication of a constant with another add; recurse.
1087 Interesting |=
1088 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1089 cast<SCEVAddExpr>(Mul->getOperand(1))
1090 ->getOperands(),
1091 NewScale, SE);
1092 } else {
1093 // A multiplication of a constant with some other value. Update
1094 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001095 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1096 const SCEV *Key = SE.getMulExpr(MulOps);
1097 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001098 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001099 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001100 NewOps.push_back(Pair.first->first);
1101 } else {
1102 Pair.first->second += NewScale;
1103 // The map already had an entry for this value, which may indicate
1104 // a folding opportunity.
1105 Interesting = true;
1106 }
1107 }
1108 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1109 // Pull a buried constant out to the outside.
1110 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1111 Interesting = true;
1112 AccumulatedConstant += Scale * C->getValue()->getValue();
1113 } else {
1114 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001115 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001116 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001117 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001118 NewOps.push_back(Pair.first->first);
1119 } else {
1120 Pair.first->second += Scale;
1121 // The map already had an entry for this value, which may indicate
1122 // a folding opportunity.
1123 Interesting = true;
1124 }
1125 }
1126 }
1127
1128 return Interesting;
1129}
1130
1131namespace {
1132 struct APIntCompare {
1133 bool operator()(const APInt &LHS, const APInt &RHS) const {
1134 return LHS.ult(RHS);
1135 }
1136 };
1137}
1138
Dan Gohman6c0866c2009-05-24 23:45:28 +00001139/// getAddExpr - Get a canonical add expression, or something simpler if
1140/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001141const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001142 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001143 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001144#ifndef NDEBUG
1145 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1146 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1147 getEffectiveSCEVType(Ops[0]->getType()) &&
1148 "SCEVAddExpr operand types don't match!");
1149#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001150
1151 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001152 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001153
1154 // If there are any constants, fold them together.
1155 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001156 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001157 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001158 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001159 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001160 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001161 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1162 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001163 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001164 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001165 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001166 }
1167
1168 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001169 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001170 Ops.erase(Ops.begin());
1171 --Idx;
1172 }
1173 }
1174
Chris Lattner627018b2004-04-07 16:16:11 +00001175 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001176
Chris Lattner53e677a2004-04-02 20:23:17 +00001177 // Okay, check to see if the same value occurs in the operand list twice. If
1178 // so, merge them together into an multiply expression. Since we sorted the
1179 // list, these values are required to be adjacent.
1180 const Type *Ty = Ops[0]->getType();
1181 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1182 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1183 // Found a match, merge the two values into a multiply, and add any
1184 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001185 const SCEV *Two = getIntegerSCEV(2, Ty);
1186 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001187 if (Ops.size() == 2)
1188 return Mul;
1189 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1190 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001191 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001192 }
1193
Dan Gohman728c7f32009-05-08 21:03:19 +00001194 // Check for truncates. If all the operands are truncated from the same
1195 // type, see if factoring out the truncate would permit the result to be
1196 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1197 // if the contents of the resulting outer trunc fold to something simple.
1198 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1199 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1200 const Type *DstType = Trunc->getType();
1201 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001202 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001203 bool Ok = true;
1204 // Check all the operands to see if they can be represented in the
1205 // source type of the truncate.
1206 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1207 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1208 if (T->getOperand()->getType() != SrcType) {
1209 Ok = false;
1210 break;
1211 }
1212 LargeOps.push_back(T->getOperand());
1213 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1214 // This could be either sign or zero extension, but sign extension
1215 // is much more likely to be foldable here.
1216 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1217 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001218 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001219 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1220 if (const SCEVTruncateExpr *T =
1221 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1222 if (T->getOperand()->getType() != SrcType) {
1223 Ok = false;
1224 break;
1225 }
1226 LargeMulOps.push_back(T->getOperand());
1227 } else if (const SCEVConstant *C =
1228 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1229 // This could be either sign or zero extension, but sign extension
1230 // is much more likely to be foldable here.
1231 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1232 } else {
1233 Ok = false;
1234 break;
1235 }
1236 }
1237 if (Ok)
1238 LargeOps.push_back(getMulExpr(LargeMulOps));
1239 } else {
1240 Ok = false;
1241 break;
1242 }
1243 }
1244 if (Ok) {
1245 // Evaluate the expression in the larger type.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001246 const SCEV *Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001247 // If it folds to something simple, use it. Otherwise, don't.
1248 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1249 return getTruncateExpr(Fold, DstType);
1250 }
1251 }
1252
1253 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001254 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1255 ++Idx;
1256
1257 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001258 if (Idx < Ops.size()) {
1259 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001260 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001261 // If we have an add, expand the add operands onto the end of the operands
1262 // list.
1263 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1264 Ops.erase(Ops.begin()+Idx);
1265 DeletedAdd = true;
1266 }
1267
1268 // If we deleted at least one add, we added operands to the end of the list,
1269 // and they are not necessarily sorted. Recurse to resort and resimplify
1270 // any operands we just aquired.
1271 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001272 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001273 }
1274
1275 // Skip over the add expression until we get to a multiply.
1276 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1277 ++Idx;
1278
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001279 // Check to see if there are any folding opportunities present with
1280 // operands multiplied by constant values.
1281 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1282 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001283 DenseMap<const SCEV *, APInt> M;
1284 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001285 APInt AccumulatedConstant(BitWidth, 0);
1286 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1287 Ops, APInt(BitWidth, 1), *this)) {
1288 // Some interesting folding opportunity is present, so its worthwhile to
1289 // re-generate the operands list. Group the operands by constant scale,
1290 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001291 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1292 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001293 E = NewOps.end(); I != E; ++I)
1294 MulOpLists[M.find(*I)->second].push_back(*I);
1295 // Re-generate the operands list.
1296 Ops.clear();
1297 if (AccumulatedConstant != 0)
1298 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001299 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1300 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001301 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001302 Ops.push_back(getMulExpr(getConstant(I->first),
1303 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001304 if (Ops.empty())
1305 return getIntegerSCEV(0, Ty);
1306 if (Ops.size() == 1)
1307 return Ops[0];
1308 return getAddExpr(Ops);
1309 }
1310 }
1311
Chris Lattner53e677a2004-04-02 20:23:17 +00001312 // If we are adding something to a multiply expression, make sure the
1313 // something is not already an operand of the multiply. If so, merge it into
1314 // the multiply.
1315 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001316 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001317 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001318 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001319 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001320 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001321 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001322 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001323 if (Mul->getNumOperands() != 2) {
1324 // If the multiply has more than two operands, we must get the
1325 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001326 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001327 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001328 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001329 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001330 const SCEV *One = getIntegerSCEV(1, Ty);
1331 const SCEV *AddOne = getAddExpr(InnerMul, One);
1332 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001333 if (Ops.size() == 2) return OuterMul;
1334 if (AddOp < Idx) {
1335 Ops.erase(Ops.begin()+AddOp);
1336 Ops.erase(Ops.begin()+Idx-1);
1337 } else {
1338 Ops.erase(Ops.begin()+Idx);
1339 Ops.erase(Ops.begin()+AddOp-1);
1340 }
1341 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001342 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001343 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001344
Chris Lattner53e677a2004-04-02 20:23:17 +00001345 // Check this multiply against other multiplies being added together.
1346 for (unsigned OtherMulIdx = Idx+1;
1347 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1348 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001349 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001350 // If MulOp occurs in OtherMul, we can fold the two multiplies
1351 // together.
1352 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1353 OMulOp != e; ++OMulOp)
1354 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1355 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001356 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001357 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001358 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1359 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001360 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001361 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001362 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001363 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001364 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001365 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1366 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001367 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001368 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001369 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001370 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1371 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001372 if (Ops.size() == 2) return OuterMul;
1373 Ops.erase(Ops.begin()+Idx);
1374 Ops.erase(Ops.begin()+OtherMulIdx-1);
1375 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001376 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001377 }
1378 }
1379 }
1380 }
1381
1382 // If there are any add recurrences in the operands list, see if any other
1383 // added values are loop invariant. If so, we can fold them into the
1384 // recurrence.
1385 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1386 ++Idx;
1387
1388 // Scan over all recurrences, trying to fold loop invariants into them.
1389 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1390 // Scan all of the other operands to this add and add them to the vector if
1391 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001392 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001393 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001394 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1395 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1396 LIOps.push_back(Ops[i]);
1397 Ops.erase(Ops.begin()+i);
1398 --i; --e;
1399 }
1400
1401 // If we found some loop invariants, fold them into the recurrence.
1402 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001403 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 LIOps.push_back(AddRec->getStart());
1405
Dan Gohman0bba49c2009-07-07 17:06:11 +00001406 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001407 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001408 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001409
Dan Gohman0bba49c2009-07-07 17:06:11 +00001410 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001411 // If all of the other operands were loop invariant, we are done.
1412 if (Ops.size() == 1) return NewRec;
1413
1414 // Otherwise, add the folded AddRec by the non-liv parts.
1415 for (unsigned i = 0;; ++i)
1416 if (Ops[i] == AddRec) {
1417 Ops[i] = NewRec;
1418 break;
1419 }
Dan Gohman246b2562007-10-22 18:31:58 +00001420 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001421 }
1422
1423 // Okay, if there weren't any loop invariants to be folded, check to see if
1424 // there are multiple AddRec's with the same loop induction variable being
1425 // added together. If so, we can fold them.
1426 for (unsigned OtherIdx = Idx+1;
1427 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1428 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001429 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001430 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1431 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001432 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1433 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001434 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1435 if (i >= NewOps.size()) {
1436 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1437 OtherAddRec->op_end());
1438 break;
1439 }
Dan Gohman246b2562007-10-22 18:31:58 +00001440 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001441 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001442 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001443
1444 if (Ops.size() == 2) return NewAddRec;
1445
1446 Ops.erase(Ops.begin()+Idx);
1447 Ops.erase(Ops.begin()+OtherIdx-1);
1448 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001449 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001450 }
1451 }
1452
1453 // Otherwise couldn't fold anything into this recurrence. Move onto the
1454 // next one.
1455 }
1456
1457 // Okay, it looks like we really DO need an add expr. Check to see if we
1458 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001459 FoldingSetNodeID ID;
1460 ID.AddInteger(scAddExpr);
1461 ID.AddInteger(Ops.size());
1462 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1463 ID.AddPointer(Ops[i]);
1464 void *IP = 0;
1465 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1466 SCEV *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001467 new (S) SCEVAddExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001468 UniqueSCEVs.InsertNode(S, IP);
1469 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001470}
1471
1472
Dan Gohman6c0866c2009-05-24 23:45:28 +00001473/// getMulExpr - Get a canonical multiply expression, or something simpler if
1474/// possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001475const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001477#ifndef NDEBUG
1478 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1479 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1480 getEffectiveSCEVType(Ops[0]->getType()) &&
1481 "SCEVMulExpr operand types don't match!");
1482#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001483
1484 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001485 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001486
1487 // If there are any constants, fold them together.
1488 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001489 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001490
1491 // C1*(C2+V) -> C1*C2 + C1*V
1492 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001493 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001494 if (Add->getNumOperands() == 2 &&
1495 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001496 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1497 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001498
1499
1500 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001501 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001502 // We found two constants, fold them together!
Dan Gohman64a845e2009-06-24 04:48:43 +00001503 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001504 RHSC->getValue()->getValue());
1505 Ops[0] = getConstant(Fold);
1506 Ops.erase(Ops.begin()+1); // Erase the folded element
1507 if (Ops.size() == 1) return Ops[0];
1508 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001509 }
1510
1511 // If we are left with a constant one being multiplied, strip it off.
1512 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1513 Ops.erase(Ops.begin());
1514 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001515 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001516 // If we have a multiply of zero, it will always be zero.
1517 return Ops[0];
1518 }
1519 }
1520
1521 // Skip over the add expression until we get to a multiply.
1522 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1523 ++Idx;
1524
1525 if (Ops.size() == 1)
1526 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001527
Chris Lattner53e677a2004-04-02 20:23:17 +00001528 // If there are mul operands inline them all into this expression.
1529 if (Idx < Ops.size()) {
1530 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001531 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001532 // If we have an mul, expand the mul operands onto the end of the operands
1533 // list.
1534 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1535 Ops.erase(Ops.begin()+Idx);
1536 DeletedMul = true;
1537 }
1538
1539 // If we deleted at least one mul, we added operands to the end of the list,
1540 // and they are not necessarily sorted. Recurse to resort and resimplify
1541 // any operands we just aquired.
1542 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001543 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001544 }
1545
1546 // If there are any add recurrences in the operands list, see if any other
1547 // added values are loop invariant. If so, we can fold them into the
1548 // recurrence.
1549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1550 ++Idx;
1551
1552 // Scan over all recurrences, trying to fold loop invariants into them.
1553 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1554 // Scan all of the other operands to this mul and add them to the vector if
1555 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001556 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001557 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001558 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1559 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1560 LIOps.push_back(Ops[i]);
1561 Ops.erase(Ops.begin()+i);
1562 --i; --e;
1563 }
1564
1565 // If we found some loop invariants, fold them into the recurrence.
1566 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001567 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001568 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001569 NewOps.reserve(AddRec->getNumOperands());
1570 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001571 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001572 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001573 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001574 } else {
1575 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001576 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001577 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001578 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001579 }
1580 }
1581
Dan Gohman0bba49c2009-07-07 17:06:11 +00001582 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001583
1584 // If all of the other operands were loop invariant, we are done.
1585 if (Ops.size() == 1) return NewRec;
1586
1587 // Otherwise, multiply the folded AddRec by the non-liv parts.
1588 for (unsigned i = 0;; ++i)
1589 if (Ops[i] == AddRec) {
1590 Ops[i] = NewRec;
1591 break;
1592 }
Dan Gohman246b2562007-10-22 18:31:58 +00001593 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001594 }
1595
1596 // Okay, if there weren't any loop invariants to be folded, check to see if
1597 // there are multiple AddRec's with the same loop induction variable being
1598 // multiplied together. If so, we can fold them.
1599 for (unsigned OtherIdx = Idx+1;
1600 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1601 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001602 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001603 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1604 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001605 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001606 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001607 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001608 const SCEV *B = F->getStepRecurrence(*this);
1609 const SCEV *D = G->getStepRecurrence(*this);
1610 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001611 getMulExpr(G, B),
1612 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001613 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001614 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001615 if (Ops.size() == 2) return NewAddRec;
1616
1617 Ops.erase(Ops.begin()+Idx);
1618 Ops.erase(Ops.begin()+OtherIdx-1);
1619 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001620 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001621 }
1622 }
1623
1624 // Otherwise couldn't fold anything into this recurrence. Move onto the
1625 // next one.
1626 }
1627
1628 // Okay, it looks like we really DO need an mul expr. Check to see if we
1629 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001630 FoldingSetNodeID ID;
1631 ID.AddInteger(scMulExpr);
1632 ID.AddInteger(Ops.size());
1633 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1634 ID.AddPointer(Ops[i]);
1635 void *IP = 0;
1636 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1637 SCEV *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001638 new (S) SCEVMulExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001639 UniqueSCEVs.InsertNode(S, IP);
1640 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001641}
1642
Dan Gohman6c0866c2009-05-24 23:45:28 +00001643/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1644/// possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001645const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1646 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001647 assert(getEffectiveSCEVType(LHS->getType()) ==
1648 getEffectiveSCEVType(RHS->getType()) &&
1649 "SCEVUDivExpr operand types don't match!");
1650
Dan Gohman622ed672009-05-04 22:02:23 +00001651 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001652 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001653 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001654 if (RHSC->isZero())
1655 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001656
Dan Gohman185cf032009-05-08 20:18:49 +00001657 // Determine if the division can be folded into the operands of
1658 // its operands.
1659 // TODO: Generalize this to non-constants by using known-bits information.
1660 const Type *Ty = LHS->getType();
1661 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1662 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1663 // For non-power-of-two values, effectively round the value up to the
1664 // nearest power of two.
1665 if (!RHSC->getValue()->getValue().isPowerOf2())
1666 ++MaxShiftAmt;
1667 const IntegerType *ExtTy =
1668 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1669 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1670 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1671 if (const SCEVConstant *Step =
1672 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1673 if (!Step->getValue()->getValue()
1674 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001675 getZeroExtendExpr(AR, ExtTy) ==
1676 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1677 getZeroExtendExpr(Step, ExtTy),
1678 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001679 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001680 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1681 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1682 return getAddRecExpr(Operands, AR->getLoop());
1683 }
1684 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001685 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001686 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001687 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1688 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1689 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001690 // Find an operand that's safely divisible.
1691 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001692 const SCEV *Op = M->getOperand(i);
1693 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001694 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001695 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1696 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001697 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001698 Operands[i] = Div;
1699 return getMulExpr(Operands);
1700 }
1701 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001702 }
Dan Gohman185cf032009-05-08 20:18:49 +00001703 // (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 +00001704 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001705 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001706 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1707 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1708 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1709 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001710 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001711 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001712 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1713 break;
1714 Operands.push_back(Op);
1715 }
1716 if (Operands.size() == A->getNumOperands())
1717 return getAddExpr(Operands);
1718 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001719 }
Dan Gohman185cf032009-05-08 20:18:49 +00001720
1721 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001722 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001723 Constant *LHSCV = LHSC->getValue();
1724 Constant *RHSCV = RHSC->getValue();
Owen Anderson385396222009-07-13 23:50:59 +00001725 return getConstant(cast<ConstantInt>(Context->getConstantExprUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001726 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001727 }
1728 }
1729
Dan Gohman1c343752009-06-27 21:21:31 +00001730 FoldingSetNodeID ID;
1731 ID.AddInteger(scUDivExpr);
1732 ID.AddPointer(LHS);
1733 ID.AddPointer(RHS);
1734 void *IP = 0;
1735 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1736 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001737 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001738 UniqueSCEVs.InsertNode(S, IP);
1739 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001740}
1741
1742
Dan Gohman6c0866c2009-05-24 23:45:28 +00001743/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1744/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001745const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
1746 const SCEV *Step, const Loop *L) {
1747 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001748 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001749 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001750 if (StepChrec->getLoop() == L) {
1751 Operands.insert(Operands.end(), StepChrec->op_begin(),
1752 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001753 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001754 }
1755
1756 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001757 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001758}
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 Gohman64a845e2009-06-24 04:48:43 +00001762const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001763ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman64a845e2009-06-24 04:48:43 +00001764 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001765 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001766#ifndef NDEBUG
1767 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1768 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1769 getEffectiveSCEVType(Operands[0]->getType()) &&
1770 "SCEVAddRecExpr operand types don't match!");
1771#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001772
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001773 if (Operands.back()->isZero()) {
1774 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001775 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001776 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001777
Dan Gohmand9cc7492008-08-08 18:33:12 +00001778 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001779 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001780 const Loop* NestedLoop = NestedAR->getLoop();
1781 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001782 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001783 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001784 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001785 // AddRecs require their operands be loop-invariant with respect to their
1786 // loops. Don't perform this transformation if it would break this
1787 // requirement.
1788 bool AllInvariant = true;
1789 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1790 if (!Operands[i]->isLoopInvariant(L)) {
1791 AllInvariant = false;
1792 break;
1793 }
1794 if (AllInvariant) {
1795 NestedOperands[0] = getAddRecExpr(Operands, L);
1796 AllInvariant = true;
1797 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1798 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1799 AllInvariant = false;
1800 break;
1801 }
1802 if (AllInvariant)
1803 // Ok, both add recurrences are valid after the transformation.
1804 return getAddRecExpr(NestedOperands, NestedLoop);
1805 }
1806 // Reset Operands to its original state.
1807 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001808 }
1809 }
1810
Dan Gohman1c343752009-06-27 21:21:31 +00001811 FoldingSetNodeID ID;
1812 ID.AddInteger(scAddRecExpr);
1813 ID.AddInteger(Operands.size());
1814 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1815 ID.AddPointer(Operands[i]);
1816 ID.AddPointer(L);
1817 void *IP = 0;
1818 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1819 SCEV *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001820 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohman1c343752009-06-27 21:21:31 +00001821 UniqueSCEVs.InsertNode(S, IP);
1822 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001823}
1824
Dan Gohman9311ef62009-06-24 14:49:00 +00001825const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1826 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001827 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001828 Ops.push_back(LHS);
1829 Ops.push_back(RHS);
1830 return getSMaxExpr(Ops);
1831}
1832
Dan Gohman0bba49c2009-07-07 17:06:11 +00001833const SCEV *
1834ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001835 assert(!Ops.empty() && "Cannot get empty smax!");
1836 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001837#ifndef NDEBUG
1838 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1839 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1840 getEffectiveSCEVType(Ops[0]->getType()) &&
1841 "SCEVSMaxExpr operand types don't match!");
1842#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001843
1844 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001845 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001846
1847 // If there are any constants, fold them together.
1848 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001849 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001850 ++Idx;
1851 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001852 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001853 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001854 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001855 APIntOps::smax(LHSC->getValue()->getValue(),
1856 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001857 Ops[0] = getConstant(Fold);
1858 Ops.erase(Ops.begin()+1); // Erase the folded element
1859 if (Ops.size() == 1) return Ops[0];
1860 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001861 }
1862
Dan Gohmane5aceed2009-06-24 14:46:22 +00001863 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001864 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1865 Ops.erase(Ops.begin());
1866 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001867 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1868 // If we have an smax with a constant maximum-int, it will always be
1869 // maximum-int.
1870 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001871 }
1872 }
1873
1874 if (Ops.size() == 1) return Ops[0];
1875
1876 // Find the first SMax
1877 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1878 ++Idx;
1879
1880 // Check to see if one of the operands is an SMax. If so, expand its operands
1881 // onto our operand list, and recurse to simplify.
1882 if (Idx < Ops.size()) {
1883 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001884 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001885 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1886 Ops.erase(Ops.begin()+Idx);
1887 DeletedSMax = true;
1888 }
1889
1890 if (DeletedSMax)
1891 return getSMaxExpr(Ops);
1892 }
1893
1894 // Okay, check to see if the same value occurs in the operand list twice. If
1895 // so, delete one. Since we sorted the list, these values are required to
1896 // be adjacent.
1897 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1898 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1899 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1900 --i; --e;
1901 }
1902
1903 if (Ops.size() == 1) return Ops[0];
1904
1905 assert(!Ops.empty() && "Reduced smax down to nothing!");
1906
Nick Lewycky3e630762008-02-20 06:48:22 +00001907 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001908 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001909 FoldingSetNodeID ID;
1910 ID.AddInteger(scSMaxExpr);
1911 ID.AddInteger(Ops.size());
1912 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1913 ID.AddPointer(Ops[i]);
1914 void *IP = 0;
1915 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1916 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001917 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001918 UniqueSCEVs.InsertNode(S, IP);
1919 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001920}
1921
Dan Gohman9311ef62009-06-24 14:49:00 +00001922const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1923 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001924 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001925 Ops.push_back(LHS);
1926 Ops.push_back(RHS);
1927 return getUMaxExpr(Ops);
1928}
1929
Dan Gohman0bba49c2009-07-07 17:06:11 +00001930const SCEV *
1931ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001932 assert(!Ops.empty() && "Cannot get empty umax!");
1933 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001934#ifndef NDEBUG
1935 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1936 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1937 getEffectiveSCEVType(Ops[0]->getType()) &&
1938 "SCEVUMaxExpr operand types don't match!");
1939#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001940
1941 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001942 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001943
1944 // If there are any constants, fold them together.
1945 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001946 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001947 ++Idx;
1948 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001949 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001950 // We found two constants, fold them together!
1951 ConstantInt *Fold = ConstantInt::get(
1952 APIntOps::umax(LHSC->getValue()->getValue(),
1953 RHSC->getValue()->getValue()));
1954 Ops[0] = getConstant(Fold);
1955 Ops.erase(Ops.begin()+1); // Erase the folded element
1956 if (Ops.size() == 1) return Ops[0];
1957 LHSC = cast<SCEVConstant>(Ops[0]);
1958 }
1959
Dan Gohmane5aceed2009-06-24 14:46:22 +00001960 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00001961 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1962 Ops.erase(Ops.begin());
1963 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001964 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1965 // If we have an umax with a constant maximum-int, it will always be
1966 // maximum-int.
1967 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001968 }
1969 }
1970
1971 if (Ops.size() == 1) return Ops[0];
1972
1973 // Find the first UMax
1974 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1975 ++Idx;
1976
1977 // Check to see if one of the operands is a UMax. If so, expand its operands
1978 // onto our operand list, and recurse to simplify.
1979 if (Idx < Ops.size()) {
1980 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001981 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001982 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1983 Ops.erase(Ops.begin()+Idx);
1984 DeletedUMax = true;
1985 }
1986
1987 if (DeletedUMax)
1988 return getUMaxExpr(Ops);
1989 }
1990
1991 // Okay, check to see if the same value occurs in the operand list twice. If
1992 // so, delete one. Since we sorted the list, these values are required to
1993 // be adjacent.
1994 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1995 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1996 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1997 --i; --e;
1998 }
1999
2000 if (Ops.size() == 1) return Ops[0];
2001
2002 assert(!Ops.empty() && "Reduced umax down to nothing!");
2003
2004 // Okay, it looks like we really DO need a umax expr. Check to see if we
2005 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002006 FoldingSetNodeID ID;
2007 ID.AddInteger(scUMaxExpr);
2008 ID.AddInteger(Ops.size());
2009 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2010 ID.AddPointer(Ops[i]);
2011 void *IP = 0;
2012 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2013 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002014 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002015 UniqueSCEVs.InsertNode(S, IP);
2016 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002017}
2018
Dan Gohman9311ef62009-06-24 14:49:00 +00002019const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2020 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002021 // ~smax(~x, ~y) == smin(x, y).
2022 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2023}
2024
Dan Gohman9311ef62009-06-24 14:49:00 +00002025const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2026 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002027 // ~umax(~x, ~y) == umin(x, y)
2028 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2029}
2030
Dan Gohman0bba49c2009-07-07 17:06:11 +00002031const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002032 // Don't attempt to do anything other than create a SCEVUnknown object
2033 // here. createSCEV only calls getUnknown after checking for all other
2034 // interesting possibilities, and any other code that calls getUnknown
2035 // is doing so in order to hide a value from SCEV canonicalization.
2036
Dan Gohman1c343752009-06-27 21:21:31 +00002037 FoldingSetNodeID ID;
2038 ID.AddInteger(scUnknown);
2039 ID.AddPointer(V);
2040 void *IP = 0;
2041 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2042 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002043 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002044 UniqueSCEVs.InsertNode(S, IP);
2045 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002046}
2047
Chris Lattner53e677a2004-04-02 20:23:17 +00002048//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002049// Basic SCEV Analysis and PHI Idiom Recognition Code
2050//
2051
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002052/// isSCEVable - Test if values of the given type are analyzable within
2053/// the SCEV framework. This primarily includes integer types, and it
2054/// can optionally include pointer types if the ScalarEvolution class
2055/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002056bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002057 // Integers are always SCEVable.
2058 if (Ty->isInteger())
2059 return true;
2060
2061 // Pointers are SCEVable if TargetData information is available
2062 // to provide pointer size information.
2063 if (isa<PointerType>(Ty))
2064 return TD != NULL;
2065
2066 // Otherwise it's not SCEVable.
2067 return false;
2068}
2069
2070/// getTypeSizeInBits - Return the size in bits of the specified type,
2071/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002072uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002073 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2074
2075 // If we have a TargetData, use it!
2076 if (TD)
2077 return TD->getTypeSizeInBits(Ty);
2078
2079 // Otherwise, we support only integer types.
2080 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
2081 return Ty->getPrimitiveSizeInBits();
2082}
2083
2084/// getEffectiveSCEVType - Return a type with the same bitwidth as
2085/// the given type and which represents how SCEV will treat the given
2086/// type, for which isSCEVable must return true. For pointer types,
2087/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002088const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002089 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2090
2091 if (Ty->isInteger())
2092 return Ty;
2093
2094 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
2095 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00002096}
Chris Lattner53e677a2004-04-02 20:23:17 +00002097
Dan Gohman0bba49c2009-07-07 17:06:11 +00002098const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002099 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002100}
2101
Chris Lattner53e677a2004-04-02 20:23:17 +00002102/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2103/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002104const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002105 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002106
Dan Gohman0bba49c2009-07-07 17:06:11 +00002107 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002108 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002109 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002110 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002111 return S;
2112}
2113
Dan Gohman6bbcba12009-06-24 00:54:57 +00002114/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002115/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002116const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002117 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
2118 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002119}
2120
2121/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2122///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002123const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002124 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002125 return getConstant(
2126 cast<ConstantInt>(Context->getConstantExprNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002127
2128 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002129 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002130 return getMulExpr(V,
2131 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002132}
2133
2134/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002135const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002136 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002137 return getConstant(
2138 cast<ConstantInt>(Context->getConstantExprNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002139
2140 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002141 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002142 const SCEV *AllOnes =
2143 getConstant(cast<ConstantInt>(Context->getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002144 return getMinusSCEV(AllOnes, V);
2145}
2146
2147/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2148///
Dan Gohman9311ef62009-06-24 14:49:00 +00002149const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2150 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002151 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002152 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002153}
2154
2155/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2156/// input value to the specified type. If the type must be extended, it is zero
2157/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002158const SCEV *
2159ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002160 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002161 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002162 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2163 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002164 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002165 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002166 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002167 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002168 return getTruncateExpr(V, Ty);
2169 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002170}
2171
2172/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2173/// input value to the specified type. If the type must be extended, it is sign
2174/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002175const SCEV *
2176ScalarEvolution::getTruncateOrSignExtend(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 getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002187}
2188
Dan Gohman467c4302009-05-13 03:46:30 +00002189/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2190/// input value to the specified type. If the type must be extended, it is zero
2191/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002192const SCEV *
2193ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002194 const Type *SrcTy = V->getType();
2195 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2196 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2197 "Cannot noop or zero extend with non-integer arguments!");
2198 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2199 "getNoopOrZeroExtend cannot truncate!");
2200 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2201 return V; // No conversion
2202 return getZeroExtendExpr(V, Ty);
2203}
2204
2205/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2206/// input value to the specified type. If the type must be extended, it is sign
2207/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002208const SCEV *
2209ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002210 const Type *SrcTy = V->getType();
2211 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2212 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2213 "Cannot noop or sign extend with non-integer arguments!");
2214 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2215 "getNoopOrSignExtend cannot truncate!");
2216 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2217 return V; // No conversion
2218 return getSignExtendExpr(V, Ty);
2219}
2220
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002221/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2222/// the input value to the specified type. If the type must be extended,
2223/// it is extended with unspecified bits. The conversion must not be
2224/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002225const SCEV *
2226ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +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 any extend with non-integer arguments!");
2231 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2232 "getNoopOrAnyExtend cannot truncate!");
2233 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2234 return V; // No conversion
2235 return getAnyExtendExpr(V, Ty);
2236}
2237
Dan Gohman467c4302009-05-13 03:46:30 +00002238/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2239/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002240const SCEV *
2241ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002242 const Type *SrcTy = V->getType();
2243 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2244 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2245 "Cannot truncate or noop with non-integer arguments!");
2246 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2247 "getTruncateOrNoop cannot extend!");
2248 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2249 return V; // No conversion
2250 return getTruncateExpr(V, Ty);
2251}
2252
Dan Gohmana334aa72009-06-22 00:31:57 +00002253/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2254/// the types using zero-extension, and then perform a umax operation
2255/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002256const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2257 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002258 const SCEV *PromotedLHS = LHS;
2259 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002260
2261 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2262 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2263 else
2264 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2265
2266 return getUMaxExpr(PromotedLHS, PromotedRHS);
2267}
2268
Dan Gohmanc9759e82009-06-22 15:03:27 +00002269/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2270/// the types using zero-extension, and then perform a umin operation
2271/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002272const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2273 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002274 const SCEV *PromotedLHS = LHS;
2275 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002276
2277 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2278 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2279 else
2280 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2281
2282 return getUMinExpr(PromotedLHS, PromotedRHS);
2283}
2284
Chris Lattner4dc534c2005-02-13 04:37:18 +00002285/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2286/// the specified instruction and replaces any references to the symbolic value
2287/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002288void
2289ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2290 const SCEV *SymName,
2291 const SCEV *NewVal) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002292 std::map<SCEVCallbackVH, const SCEV *>::iterator SI =
Dan Gohman35738ac2009-05-04 22:30:44 +00002293 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002294 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002295
Dan Gohman0bba49c2009-07-07 17:06:11 +00002296 const SCEV *NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002297 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002298 if (NV == SI->second) return; // No change.
2299
2300 SI->second = NV; // Update the scalars map!
2301
2302 // Any instruction values that use this instruction might also need to be
2303 // updated!
2304 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2305 UI != E; ++UI)
2306 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2307}
Chris Lattner53e677a2004-04-02 20:23:17 +00002308
2309/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2310/// a loop header, making it a potential recurrence, or it doesn't.
2311///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002312const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002313 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002314 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002315 if (L->getHeader() == PN->getParent()) {
2316 // If it lives in the loop header, it has two incoming values, one
2317 // from outside the loop, and one from inside.
2318 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2319 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002320
Chris Lattner53e677a2004-04-02 20:23:17 +00002321 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002322 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002323 assert(Scalars.find(PN) == Scalars.end() &&
2324 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002325 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002326
2327 // Using this symbolic name for the PHI, analyze the value coming around
2328 // the back-edge.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002329 const SCEV *BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Chris Lattner53e677a2004-04-02 20:23:17 +00002330
2331 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2332 // has a special value for the first iteration of the loop.
2333
2334 // If the value coming around the backedge is an add with the symbolic
2335 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002336 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002337 // If there is a single occurrence of the symbolic value, replace it
2338 // with a recurrence.
2339 unsigned FoundIndex = Add->getNumOperands();
2340 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2341 if (Add->getOperand(i) == SymbolicName)
2342 if (FoundIndex == e) {
2343 FoundIndex = i;
2344 break;
2345 }
2346
2347 if (FoundIndex != Add->getNumOperands()) {
2348 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002349 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002350 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2351 if (i != FoundIndex)
2352 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002353 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002354
2355 // This is not a valid addrec if the step amount is varying each
2356 // loop iteration, but is not itself an addrec in this loop.
2357 if (Accum->isLoopInvariant(L) ||
2358 (isa<SCEVAddRecExpr>(Accum) &&
2359 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002360 const SCEV *StartVal =
2361 getSCEV(PN->getIncomingValue(IncomingEdge));
2362 const SCEV *PHISCEV =
2363 getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002364
2365 // Okay, for the entire analysis of this edge we assumed the PHI
2366 // to be symbolic. We now need to go back and update all of the
2367 // entries for the scalars that use the PHI (except for the PHI
2368 // itself) to use the new analyzed value instead of the "symbolic"
2369 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002370 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002371 return PHISCEV;
2372 }
2373 }
Dan Gohman622ed672009-05-04 22:02:23 +00002374 } else if (const SCEVAddRecExpr *AddRec =
2375 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002376 // Otherwise, this could be a loop like this:
2377 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2378 // In this case, j = {1,+,1} and BEValue is j.
2379 // Because the other in-value of i (0) fits the evolution of BEValue
2380 // i really is an addrec evolution.
2381 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002382 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002383
2384 // If StartVal = j.start - j.stride, we can use StartVal as the
2385 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002386 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002387 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002388 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002389 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002390
2391 // Okay, for the entire analysis of this edge we assumed the PHI
2392 // to be symbolic. We now need to go back and update all of the
2393 // entries for the scalars that use the PHI (except for the PHI
2394 // itself) to use the new analyzed value instead of the "symbolic"
2395 // value.
2396 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2397 return PHISCEV;
2398 }
2399 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002400 }
2401
2402 return SymbolicName;
2403 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002404
Chris Lattner53e677a2004-04-02 20:23:17 +00002405 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002406 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002407}
2408
Dan Gohman26466c02009-05-08 20:26:55 +00002409/// createNodeForGEP - Expand GEP instructions into add and multiply
2410/// operations. This allows them to be analyzed by regular SCEV code.
2411///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002412const SCEV *ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002413
2414 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002415 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002416 // Don't attempt to analyze GEPs over unsized objects.
2417 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2418 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002419 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002420 gep_type_iterator GTI = gep_type_begin(GEP);
2421 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2422 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002423 I != E; ++I) {
2424 Value *Index = *I;
2425 // Compute the (potentially symbolic) offset in bytes for this index.
2426 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2427 // For a struct, add the member offset.
2428 const StructLayout &SL = *TD->getStructLayout(STy);
2429 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2430 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohman85b05a22009-07-13 21:35:55 +00002431 TotalOffset = getAddExpr(TotalOffset, getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman26466c02009-05-08 20:26:55 +00002432 } else {
2433 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002434 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002435 if (!isa<PointerType>(LocalOffset->getType()))
2436 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002437 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohman26466c02009-05-08 20:26:55 +00002438 LocalOffset =
2439 getMulExpr(LocalOffset,
Dan Gohman85b05a22009-07-13 21:35:55 +00002440 getIntegerSCEV(TD->getTypeAllocSize(*GTI), IntPtrTy));
Dan Gohman26466c02009-05-08 20:26:55 +00002441 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2442 }
2443 }
2444 return getAddExpr(getSCEV(Base), TotalOffset);
2445}
2446
Nick Lewycky83bb0052007-11-22 07:59:40 +00002447/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2448/// guaranteed to end in (at every loop iteration). It is, at the same time,
2449/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2450/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002451uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002452ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002453 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002454 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002455
Dan Gohman622ed672009-05-04 22:02:23 +00002456 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002457 return std::min(GetMinTrailingZeros(T->getOperand()),
2458 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002459
Dan Gohman622ed672009-05-04 22:02:23 +00002460 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002461 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2462 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2463 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002464 }
2465
Dan Gohman622ed672009-05-04 22:02:23 +00002466 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002467 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2468 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2469 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002470 }
2471
Dan Gohman622ed672009-05-04 22:02:23 +00002472 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002473 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002474 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002475 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002476 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002477 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002478 }
2479
Dan Gohman622ed672009-05-04 22:02:23 +00002480 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002481 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002482 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2483 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002484 for (unsigned i = 1, e = M->getNumOperands();
2485 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002486 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002487 BitWidth);
2488 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002489 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002490
Dan Gohman622ed672009-05-04 22:02:23 +00002491 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002492 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002493 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002494 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002495 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002496 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002497 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002498
Dan Gohman622ed672009-05-04 22:02:23 +00002499 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002500 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002501 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002502 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002503 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002504 return MinOpRes;
2505 }
2506
Dan Gohman622ed672009-05-04 22:02:23 +00002507 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002508 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002509 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002510 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002511 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002512 return MinOpRes;
2513 }
2514
Dan Gohman2c364ad2009-06-19 23:29:04 +00002515 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2516 // For a SCEVUnknown, ask ValueTracking.
2517 unsigned BitWidth = getTypeSizeInBits(U->getType());
2518 APInt Mask = APInt::getAllOnesValue(BitWidth);
2519 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2520 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2521 return Zeros.countTrailingOnes();
2522 }
2523
2524 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002525 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002526}
Chris Lattner53e677a2004-04-02 20:23:17 +00002527
Dan Gohman85b05a22009-07-13 21:35:55 +00002528/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2529///
2530ConstantRange
2531ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002532
2533 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002534 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002535
Dan Gohman85b05a22009-07-13 21:35:55 +00002536 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2537 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2538 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2539 X = X.add(getUnsignedRange(Add->getOperand(i)));
2540 return X;
2541 }
2542
2543 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2544 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2545 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2546 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2547 return X;
2548 }
2549
2550 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2551 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2552 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2553 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2554 return X;
2555 }
2556
2557 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2558 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2559 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2560 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2561 return X;
2562 }
2563
2564 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2565 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2566 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2567 return X.udiv(Y);
2568 }
2569
2570 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2571 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2572 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2573 }
2574
2575 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2576 ConstantRange X = getUnsignedRange(SExt->getOperand());
2577 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2578 }
2579
2580 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2581 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2582 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2583 }
2584
2585 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2586
2587 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2588 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2589 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2590 if (!Trip) return FullSet;
2591
2592 // TODO: non-affine addrec
2593 if (AddRec->isAffine()) {
2594 const Type *Ty = AddRec->getType();
2595 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2596 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2597 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2598
2599 const SCEV *Start = AddRec->getStart();
2600 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2601
2602 // Check for overflow.
2603 if (!isKnownPredicate(ICmpInst::ICMP_ULE, Start, End))
2604 return FullSet;
2605
2606 ConstantRange StartRange = getUnsignedRange(Start);
2607 ConstantRange EndRange = getUnsignedRange(End);
2608 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2609 EndRange.getUnsignedMin());
2610 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2611 EndRange.getUnsignedMax());
2612 if (Min.isMinValue() && Max.isMaxValue())
2613 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2614 return ConstantRange(Min, Max+1);
2615 }
2616 }
Dan Gohman2c364ad2009-06-19 23:29:04 +00002617 }
2618
2619 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2620 // For a SCEVUnknown, ask ValueTracking.
2621 unsigned BitWidth = getTypeSizeInBits(U->getType());
2622 APInt Mask = APInt::getAllOnesValue(BitWidth);
2623 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2624 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman85b05a22009-07-13 21:35:55 +00002625 return ConstantRange(Ones, ~Zeros);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002626 }
2627
Dan Gohman85b05a22009-07-13 21:35:55 +00002628 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002629}
2630
Dan Gohman85b05a22009-07-13 21:35:55 +00002631/// getSignedRange - Determine the signed range for a particular SCEV.
2632///
2633ConstantRange
2634ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002635
Dan Gohman85b05a22009-07-13 21:35:55 +00002636 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2637 return ConstantRange(C->getValue()->getValue());
2638
2639 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2640 ConstantRange X = getSignedRange(Add->getOperand(0));
2641 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2642 X = X.add(getSignedRange(Add->getOperand(i)));
2643 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002644 }
2645
Dan Gohman85b05a22009-07-13 21:35:55 +00002646 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2647 ConstantRange X = getSignedRange(Mul->getOperand(0));
2648 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2649 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2650 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002651 }
2652
Dan Gohman85b05a22009-07-13 21:35:55 +00002653 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2654 ConstantRange X = getSignedRange(SMax->getOperand(0));
2655 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2656 X = X.smax(getSignedRange(SMax->getOperand(i)));
2657 return X;
2658 }
Dan Gohman62849c02009-06-24 01:05:09 +00002659
Dan Gohman85b05a22009-07-13 21:35:55 +00002660 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2661 ConstantRange X = getSignedRange(UMax->getOperand(0));
2662 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2663 X = X.umax(getSignedRange(UMax->getOperand(i)));
2664 return X;
2665 }
Dan Gohman62849c02009-06-24 01:05:09 +00002666
Dan Gohman85b05a22009-07-13 21:35:55 +00002667 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2668 ConstantRange X = getSignedRange(UDiv->getLHS());
2669 ConstantRange Y = getSignedRange(UDiv->getRHS());
2670 return X.udiv(Y);
2671 }
Dan Gohman62849c02009-06-24 01:05:09 +00002672
Dan Gohman85b05a22009-07-13 21:35:55 +00002673 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2674 ConstantRange X = getSignedRange(ZExt->getOperand());
2675 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2676 }
2677
2678 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2679 ConstantRange X = getSignedRange(SExt->getOperand());
2680 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2681 }
2682
2683 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2684 ConstantRange X = getSignedRange(Trunc->getOperand());
2685 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2686 }
2687
2688 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2689
2690 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2691 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2692 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2693 if (!Trip) return FullSet;
2694
2695 // TODO: non-affine addrec
2696 if (AddRec->isAffine()) {
2697 const Type *Ty = AddRec->getType();
2698 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2699 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2700 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2701
2702 const SCEV *Start = AddRec->getStart();
2703 const SCEV *Step = AddRec->getStepRecurrence(*this);
2704 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2705
2706 // Check for overflow.
2707 if (!(isKnownPositive(Step) &&
2708 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
2709 !(isKnownNegative(Step) &&
2710 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2711 return FullSet;
2712
2713 ConstantRange StartRange = getSignedRange(Start);
2714 ConstantRange EndRange = getSignedRange(End);
2715 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2716 EndRange.getSignedMin());
2717 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2718 EndRange.getSignedMax());
2719 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
2720 return ConstantRange(Min.getBitWidth(), /*isFullSet=*/true);
2721 return ConstantRange(Min, Max+1);
Dan Gohman62849c02009-06-24 01:05:09 +00002722 }
Dan Gohman62849c02009-06-24 01:05:09 +00002723 }
Dan Gohman62849c02009-06-24 01:05:09 +00002724 }
2725
Dan Gohman2c364ad2009-06-19 23:29:04 +00002726 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2727 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman85b05a22009-07-13 21:35:55 +00002728 unsigned BitWidth = getTypeSizeInBits(U->getType());
2729 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2730 if (NS == 1)
2731 return FullSet;
2732 return
2733 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2734 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002735 }
2736
Dan Gohman85b05a22009-07-13 21:35:55 +00002737 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002738}
2739
Chris Lattner53e677a2004-04-02 20:23:17 +00002740/// createSCEV - We know that there is no SCEV for the specified value.
2741/// Analyze the expression.
2742///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002743const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002744 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002745 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002746
Dan Gohman6c459a22008-06-22 19:56:46 +00002747 unsigned Opcode = Instruction::UserOp1;
2748 if (Instruction *I = dyn_cast<Instruction>(V))
2749 Opcode = I->getOpcode();
2750 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2751 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002752 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2753 return getConstant(CI);
2754 else if (isa<ConstantPointerNull>(V))
2755 return getIntegerSCEV(0, V->getType());
2756 else if (isa<UndefValue>(V))
2757 return getIntegerSCEV(0, V->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002758 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002759 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002760
Dan Gohman6c459a22008-06-22 19:56:46 +00002761 User *U = cast<User>(V);
2762 switch (Opcode) {
2763 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002764 return getAddExpr(getSCEV(U->getOperand(0)),
2765 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002766 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002767 return getMulExpr(getSCEV(U->getOperand(0)),
2768 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002769 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002770 return getUDivExpr(getSCEV(U->getOperand(0)),
2771 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002772 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002773 return getMinusSCEV(getSCEV(U->getOperand(0)),
2774 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002775 case Instruction::And:
2776 // For an expression like x&255 that merely masks off the high bits,
2777 // use zext(trunc(x)) as the SCEV expression.
2778 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002779 if (CI->isNullValue())
2780 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002781 if (CI->isAllOnesValue())
2782 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002783 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002784
2785 // Instcombine's ShrinkDemandedConstant may strip bits out of
2786 // constants, obscuring what would otherwise be a low-bits mask.
2787 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2788 // knew about to reconstruct a low-bits mask value.
2789 unsigned LZ = A.countLeadingZeros();
2790 unsigned BitWidth = A.getBitWidth();
2791 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2792 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2793 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2794
2795 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2796
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002797 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002798 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002799 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002800 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002801 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002802 }
2803 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002804
Dan Gohman6c459a22008-06-22 19:56:46 +00002805 case Instruction::Or:
2806 // If the RHS of the Or is a constant, we may have something like:
2807 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2808 // optimizations will transparently handle this case.
2809 //
2810 // In order for this transformation to be safe, the LHS must be of the
2811 // form X*(2^n) and the Or constant must be less than 2^n.
2812 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002813 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002814 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002815 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002816 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002817 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002818 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002819 break;
2820 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002821 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002822 // If the RHS of the xor is a signbit, then this is just an add.
2823 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002824 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002825 return getAddExpr(getSCEV(U->getOperand(0)),
2826 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002827
2828 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002829 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002830 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002831
2832 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2833 // This is a variant of the check for xor with -1, and it handles
2834 // the case where instcombine has trimmed non-demanded bits out
2835 // of an xor with -1.
2836 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2837 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2838 if (BO->getOpcode() == Instruction::And &&
2839 LCI->getValue() == CI->getValue())
2840 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002841 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002842 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00002843 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002844 const Type *Z0Ty = Z0->getType();
2845 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2846
2847 // If C is a low-bits mask, the zero extend is zerving to
2848 // mask off the high bits. Complement the operand and
2849 // re-apply the zext.
2850 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2851 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2852
2853 // If C is a single bit, it may be in the sign-bit position
2854 // before the zero-extend. In this case, represent the xor
2855 // using an add, which is equivalent, and re-apply the zext.
2856 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2857 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2858 Trunc.isSignBit())
2859 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2860 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002861 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002862 }
2863 break;
2864
2865 case Instruction::Shl:
2866 // Turn shift left of a constant amount into a multiply.
2867 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2868 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2869 Constant *X = ConstantInt::get(
2870 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002871 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002872 }
2873 break;
2874
Nick Lewycky01eaf802008-07-07 06:15:49 +00002875 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002876 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002877 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2878 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2879 Constant *X = ConstantInt::get(
2880 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002881 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002882 }
2883 break;
2884
Dan Gohman4ee29af2009-04-21 02:26:00 +00002885 case Instruction::AShr:
2886 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2887 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2888 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2889 if (L->getOpcode() == Instruction::Shl &&
2890 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002891 unsigned BitWidth = getTypeSizeInBits(U->getType());
2892 uint64_t Amt = BitWidth - CI->getZExtValue();
2893 if (Amt == BitWidth)
2894 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2895 if (Amt > BitWidth)
2896 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002897 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002898 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002899 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002900 U->getType());
2901 }
2902 break;
2903
Dan Gohman6c459a22008-06-22 19:56:46 +00002904 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002905 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002906
2907 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002908 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002909
2910 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002911 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002912
2913 case Instruction::BitCast:
2914 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002915 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002916 return getSCEV(U->getOperand(0));
2917 break;
2918
Dan Gohman2d1be872009-04-16 03:18:22 +00002919 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002920 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002921 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002922 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002923
2924 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002925 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002926 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2927 U->getType());
2928
Dan Gohman26466c02009-05-08 20:26:55 +00002929 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002930 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002931 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002932
Dan Gohman6c459a22008-06-22 19:56:46 +00002933 case Instruction::PHI:
2934 return createNodeForPHI(cast<PHINode>(U));
2935
2936 case Instruction::Select:
2937 // This could be a smax or umax that was lowered earlier.
2938 // Try to recover it.
2939 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2940 Value *LHS = ICI->getOperand(0);
2941 Value *RHS = ICI->getOperand(1);
2942 switch (ICI->getPredicate()) {
2943 case ICmpInst::ICMP_SLT:
2944 case ICmpInst::ICMP_SLE:
2945 std::swap(LHS, RHS);
2946 // fall through
2947 case ICmpInst::ICMP_SGT:
2948 case ICmpInst::ICMP_SGE:
2949 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002950 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002951 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002952 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002953 break;
2954 case ICmpInst::ICMP_ULT:
2955 case ICmpInst::ICMP_ULE:
2956 std::swap(LHS, RHS);
2957 // fall through
2958 case ICmpInst::ICMP_UGT:
2959 case ICmpInst::ICMP_UGE:
2960 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002961 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002962 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002963 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002964 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002965 case ICmpInst::ICMP_NE:
2966 // n != 0 ? n : 1 -> umax(n, 1)
2967 if (LHS == U->getOperand(1) &&
2968 isa<ConstantInt>(U->getOperand(2)) &&
2969 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2970 isa<ConstantInt>(RHS) &&
2971 cast<ConstantInt>(RHS)->isZero())
2972 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2973 break;
2974 case ICmpInst::ICMP_EQ:
2975 // n == 0 ? 1 : n -> umax(n, 1)
2976 if (LHS == U->getOperand(2) &&
2977 isa<ConstantInt>(U->getOperand(1)) &&
2978 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2979 isa<ConstantInt>(RHS) &&
2980 cast<ConstantInt>(RHS)->isZero())
2981 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2982 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002983 default:
2984 break;
2985 }
2986 }
2987
2988 default: // We cannot analyze this expression.
2989 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002990 }
2991
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002992 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002993}
2994
2995
2996
2997//===----------------------------------------------------------------------===//
2998// Iteration Count Computation Code
2999//
3000
Dan Gohman46bdfb02009-02-24 18:55:53 +00003001/// getBackedgeTakenCount - If the specified loop has a predictable
3002/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3003/// object. The backedge-taken count is the number of times the loop header
3004/// will be branched to from within the loop. This is one less than the
3005/// trip count of the loop, since it doesn't count the first iteration,
3006/// when the header is branched to from outside the loop.
3007///
3008/// Note that it is not valid to call this method on a loop without a
3009/// loop-invariant backedge-taken count (see
3010/// hasLoopInvariantBackedgeTakenCount).
3011///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003012const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003013 return getBackedgeTakenInfo(L).Exact;
3014}
3015
3016/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3017/// return the least SCEV value that is known never to be less than the
3018/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003019const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003020 return getBackedgeTakenInfo(L).Max;
3021}
3022
Dan Gohman59ae6b92009-07-08 19:23:34 +00003023/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3024/// onto the given Worklist.
3025static void
3026PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3027 BasicBlock *Header = L->getHeader();
3028
3029 // Push all Loop-header PHIs onto the Worklist stack.
3030 for (BasicBlock::iterator I = Header->begin();
3031 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3032 Worklist.push_back(PN);
3033}
3034
3035/// PushDefUseChildren - Push users of the given Instruction
3036/// onto the given Worklist.
3037static void
3038PushDefUseChildren(Instruction *I,
3039 SmallVectorImpl<Instruction *> &Worklist) {
3040 // Push the def-use children onto the Worklist stack.
3041 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3042 UI != UE; ++UI)
3043 Worklist.push_back(cast<Instruction>(UI));
3044}
3045
Dan Gohmana1af7572009-04-30 20:47:05 +00003046const ScalarEvolution::BackedgeTakenInfo &
3047ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003048 // Initially insert a CouldNotCompute for this loop. If the insertion
3049 // succeeds, procede to actually compute a backedge-taken count and
3050 // update the value. The temporary CouldNotCompute value tells SCEV
3051 // code elsewhere that it shouldn't attempt to request a new
3052 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00003053 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003054 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3055 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003056 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00003057 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003058 assert(ItCount.Exact->isLoopInvariant(L) &&
3059 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003060 "Computed trip count isn't loop invariant for loop!");
3061 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003062
Dan Gohman01ecca22009-04-27 20:16:15 +00003063 // Update the value in the map.
3064 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003065 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00003066 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003067 // Update the value in the map.
3068 Pair.first->second = ItCount;
3069 if (isa<PHINode>(L->getHeader()->begin()))
3070 // Only count loops that have phi nodes as not being computable.
3071 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003072 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003073
3074 // Now that we know more about the trip count for this loop, forget any
3075 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003076 // conservative estimates made without the benefit of trip count
3077 // information. This is similar to the code in
3078 // forgetLoopBackedgeTakenCount, except that it handles SCEVUnknown PHI
3079 // nodes specially.
3080 if (ItCount.hasAnyInfo()) {
3081 SmallVector<Instruction *, 16> Worklist;
3082 PushLoopPHIs(L, Worklist);
3083
3084 SmallPtrSet<Instruction *, 8> Visited;
3085 while (!Worklist.empty()) {
3086 Instruction *I = Worklist.pop_back_val();
3087 if (!Visited.insert(I)) continue;
3088
3089 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3090 Scalars.find(static_cast<Value *>(I));
3091 if (It != Scalars.end()) {
3092 // SCEVUnknown for a PHI either means that it has an unrecognized
3093 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003094 // by createNodeForPHI. In the former case, additional loop trip
3095 // count information isn't going to change anything. In the later
3096 // case, createNodeForPHI will perform the necessary updates on its
3097 // own when it gets to that point.
Dan Gohman59ae6b92009-07-08 19:23:34 +00003098 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second))
3099 Scalars.erase(It);
3100 ValuesAtScopes.erase(I);
3101 if (PHINode *PN = dyn_cast<PHINode>(I))
3102 ConstantEvolutionLoopExitValue.erase(PN);
3103 }
3104
3105 PushDefUseChildren(I, Worklist);
3106 }
3107 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003108 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003109 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003110}
3111
Dan Gohman46bdfb02009-02-24 18:55:53 +00003112/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00003113/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00003114/// ScalarEvolution's ability to compute a trip count, or if the loop
3115/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003116void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003117 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003118
Dan Gohman35738ac2009-05-04 22:30:44 +00003119 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003120 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003121
Dan Gohman59ae6b92009-07-08 19:23:34 +00003122 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003123 while (!Worklist.empty()) {
3124 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003125 if (!Visited.insert(I)) continue;
3126
3127 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
3128 Scalars.find(static_cast<Value *>(I));
3129 if (It != Scalars.end()) {
3130 Scalars.erase(It);
3131 ValuesAtScopes.erase(I);
3132 if (PHINode *PN = dyn_cast<PHINode>(I))
3133 ConstantEvolutionLoopExitValue.erase(PN);
3134 }
3135
3136 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003137 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003138}
3139
Dan Gohman46bdfb02009-02-24 18:55:53 +00003140/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3141/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003142ScalarEvolution::BackedgeTakenInfo
3143ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003144 SmallVector<BasicBlock*, 8> ExitingBlocks;
3145 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003146
Dan Gohmana334aa72009-06-22 00:31:57 +00003147 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003148 const SCEV *BECount = getCouldNotCompute();
3149 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003150 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003151 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3152 BackedgeTakenInfo NewBTI =
3153 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003154
Dan Gohman1c343752009-06-27 21:21:31 +00003155 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003156 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003157 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003158 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003159 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003160 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003161 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003162 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003163 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003164 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003165 }
Dan Gohman1c343752009-06-27 21:21:31 +00003166 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003167 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003168 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003169 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003170 }
3171
3172 return BackedgeTakenInfo(BECount, MaxBECount);
3173}
3174
3175/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3176/// of the specified loop will execute if it exits via the specified block.
3177ScalarEvolution::BackedgeTakenInfo
3178ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3179 BasicBlock *ExitingBlock) {
3180
3181 // Okay, we've chosen an exiting block. See what condition causes us to
3182 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003183 //
3184 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003185 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003186 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003187 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003188
Chris Lattner8b0e3602007-01-07 02:24:26 +00003189 // At this point, we know we have a conditional branch that determines whether
3190 // the loop is exited. However, we don't know if the branch is executed each
3191 // time through the loop. If not, then the execution count of the branch will
3192 // not be equal to the trip count of the loop.
3193 //
3194 // Currently we check for this by checking to see if the Exit branch goes to
3195 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003196 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003197 // loop header. This is common for un-rotated loops.
3198 //
3199 // If both of those tests fail, walk up the unique predecessor chain to the
3200 // header, stopping if there is an edge that doesn't exit the loop. If the
3201 // header is reached, the execution count of the branch will be equal to the
3202 // trip count of the loop.
3203 //
3204 // More extensive analysis could be done to handle more cases here.
3205 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003206 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003207 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003208 ExitBr->getParent() != L->getHeader()) {
3209 // The simple checks failed, try climbing the unique predecessor chain
3210 // up to the header.
3211 bool Ok = false;
3212 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3213 BasicBlock *Pred = BB->getUniquePredecessor();
3214 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003215 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003216 TerminatorInst *PredTerm = Pred->getTerminator();
3217 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3218 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3219 if (PredSucc == BB)
3220 continue;
3221 // If the predecessor has a successor that isn't BB and isn't
3222 // outside the loop, assume the worst.
3223 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003224 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003225 }
3226 if (Pred == L->getHeader()) {
3227 Ok = true;
3228 break;
3229 }
3230 BB = Pred;
3231 }
3232 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003233 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003234 }
3235
3236 // Procede to the next level to examine the exit condition expression.
3237 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3238 ExitBr->getSuccessor(0),
3239 ExitBr->getSuccessor(1));
3240}
3241
3242/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3243/// backedge of the specified loop will execute if its exit condition
3244/// were a conditional branch of ExitCond, TBB, and FBB.
3245ScalarEvolution::BackedgeTakenInfo
3246ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3247 Value *ExitCond,
3248 BasicBlock *TBB,
3249 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003250 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003251 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3252 if (BO->getOpcode() == Instruction::And) {
3253 // Recurse on the operands of the and.
3254 BackedgeTakenInfo BTI0 =
3255 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3256 BackedgeTakenInfo BTI1 =
3257 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003258 const SCEV *BECount = getCouldNotCompute();
3259 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003260 if (L->contains(TBB)) {
3261 // Both conditions must be true for the loop to continue executing.
3262 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003263 if (BTI0.Exact == getCouldNotCompute() ||
3264 BTI1.Exact == getCouldNotCompute())
3265 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003266 else
3267 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003268 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003269 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003270 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003271 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003272 else
3273 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003274 } else {
3275 // Both conditions must be true for the loop to exit.
3276 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003277 if (BTI0.Exact != getCouldNotCompute() &&
3278 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003279 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003280 if (BTI0.Max != getCouldNotCompute() &&
3281 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003282 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3283 }
3284
3285 return BackedgeTakenInfo(BECount, MaxBECount);
3286 }
3287 if (BO->getOpcode() == Instruction::Or) {
3288 // Recurse on the operands of the or.
3289 BackedgeTakenInfo BTI0 =
3290 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3291 BackedgeTakenInfo BTI1 =
3292 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003293 const SCEV *BECount = getCouldNotCompute();
3294 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003295 if (L->contains(FBB)) {
3296 // Both conditions must be false for the loop to continue executing.
3297 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003298 if (BTI0.Exact == getCouldNotCompute() ||
3299 BTI1.Exact == getCouldNotCompute())
3300 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003301 else
3302 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003303 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003304 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003305 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003306 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003307 else
3308 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003309 } else {
3310 // Both conditions must be false for the loop to exit.
3311 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003312 if (BTI0.Exact != getCouldNotCompute() &&
3313 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003314 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003315 if (BTI0.Max != getCouldNotCompute() &&
3316 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003317 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3318 }
3319
3320 return BackedgeTakenInfo(BECount, MaxBECount);
3321 }
3322 }
3323
3324 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3325 // Procede to the next level to examine the icmp.
3326 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3327 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003328
Eli Friedman361e54d2009-05-09 12:32:42 +00003329 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003330 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3331}
3332
3333/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3334/// backedge of the specified loop will execute if its exit condition
3335/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3336ScalarEvolution::BackedgeTakenInfo
3337ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3338 ICmpInst *ExitCond,
3339 BasicBlock *TBB,
3340 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003341
Reid Spencere4d87aa2006-12-23 06:05:41 +00003342 // If the condition was exit on true, convert the condition to exit on false
3343 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003344 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003345 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003346 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003347 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003348
3349 // Handle common loops like: for (X = "string"; *X; ++X)
3350 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3351 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003352 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003353 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003354 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3355 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3356 return BackedgeTakenInfo(ItCnt,
3357 isa<SCEVConstant>(ItCnt) ? ItCnt :
3358 getConstant(APInt::getMaxValue(BitWidth)-1));
3359 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003360 }
3361
Dan Gohman0bba49c2009-07-07 17:06:11 +00003362 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3363 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003364
3365 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003366 LHS = getSCEVAtScope(LHS, L);
3367 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003368
Dan Gohman64a845e2009-06-24 04:48:43 +00003369 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003370 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003371 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3372 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003373 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003374 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003375 }
3376
Chris Lattner53e677a2004-04-02 20:23:17 +00003377 // If we have a comparison of a chrec against a constant, try to use value
3378 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003379 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3380 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003381 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003382 // Form the constant range.
3383 ConstantRange CompRange(
3384 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003385
Dan Gohman0bba49c2009-07-07 17:06:11 +00003386 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003387 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003388 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003389
Chris Lattner53e677a2004-04-02 20:23:17 +00003390 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003392 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003393 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003395 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003396 }
3397 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003398 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003399 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003401 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 }
3403 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003404 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3405 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003406 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003407 }
3408 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003409 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3410 getNotSCEV(RHS), L, true);
3411 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003412 break;
3413 }
3414 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003415 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3416 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003417 break;
3418 }
3419 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003420 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3421 getNotSCEV(RHS), L, false);
3422 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003423 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003424 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003425 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003426#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003427 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003428 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003429 errs() << "[unsigned] ";
3430 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003431 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003432 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003433#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003434 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003435 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003436 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003437 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003438}
3439
Chris Lattner673e02b2004-10-12 01:49:27 +00003440static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003441EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3442 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003443 const SCEV *InVal = SE.getConstant(C);
3444 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003445 assert(isa<SCEVConstant>(Val) &&
3446 "Evaluation of SCEV at constant didn't fold correctly?");
3447 return cast<SCEVConstant>(Val)->getValue();
3448}
3449
3450/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3451/// and a GEP expression (missing the pointer index) indexing into it, return
3452/// the addressed element of the initializer or null if the index expression is
3453/// invalid.
3454static Constant *
Owen Anderson0a5372e2009-07-13 04:09:18 +00003455GetAddressedElementFromGlobal(LLVMContext *Context, GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003456 const std::vector<ConstantInt*> &Indices) {
3457 Constant *Init = GV->getInitializer();
3458 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003459 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003460 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3461 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3462 Init = cast<Constant>(CS->getOperand(Idx));
3463 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3464 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3465 Init = cast<Constant>(CA->getOperand(Idx));
3466 } else if (isa<ConstantAggregateZero>(Init)) {
3467 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3468 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Anderson0a5372e2009-07-13 04:09:18 +00003469 Init = Context->getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003470 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3471 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Anderson0a5372e2009-07-13 04:09:18 +00003472 Init = Context->getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003473 } else {
Torok Edwinc25e7582009-07-11 20:10:48 +00003474 LLVM_UNREACHABLE("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003475 }
3476 return 0;
3477 } else {
3478 return 0; // Unknown initializer type
3479 }
3480 }
3481 return Init;
3482}
3483
Dan Gohman46bdfb02009-02-24 18:55:53 +00003484/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3485/// 'icmp op load X, cst', try to see if we can compute the backedge
3486/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003487const SCEV *
3488ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3489 LoadInst *LI,
3490 Constant *RHS,
3491 const Loop *L,
3492 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003493 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003494
3495 // Check to see if the loaded pointer is a getelementptr of a global.
3496 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003497 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003498
3499 // Make sure that it is really a constant global we are gepping, with an
3500 // initializer, and make sure the first IDX is really 0.
3501 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3502 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3503 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3504 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003505 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003506
3507 // Okay, we allow one non-constant index into the GEP instruction.
3508 Value *VarIdx = 0;
3509 std::vector<ConstantInt*> Indexes;
3510 unsigned VarIdxNum = 0;
3511 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3512 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3513 Indexes.push_back(CI);
3514 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003515 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003516 VarIdx = GEP->getOperand(i);
3517 VarIdxNum = i-2;
3518 Indexes.push_back(0);
3519 }
3520
3521 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3522 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003523 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003524 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003525
3526 // We can only recognize very limited forms of loop index expressions, in
3527 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003528 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003529 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3530 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3531 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003532 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003533
3534 unsigned MaxSteps = MaxBruteForceIterations;
3535 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003536 ConstantInt *ItCst =
Dan Gohman6de29f82009-06-15 22:12:54 +00003537 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003538 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003539
3540 // Form the GEP offset.
3541 Indexes[VarIdxNum] = Val;
3542
Owen Anderson0a5372e2009-07-13 04:09:18 +00003543 Constant *Result = GetAddressedElementFromGlobal(Context, GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003544 if (Result == 0) break; // Cannot compute!
3545
3546 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003547 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003548 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003549 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003550#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003551 errs() << "\n***\n*** Computed loop count " << *ItCst
3552 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3553 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003554#endif
3555 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003556 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003557 }
3558 }
Dan Gohman1c343752009-06-27 21:21:31 +00003559 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003560}
3561
3562
Chris Lattner3221ad02004-04-17 22:58:41 +00003563/// CanConstantFold - Return true if we can constant fold an instruction of the
3564/// specified type, assuming that all operands were constants.
3565static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003566 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003567 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3568 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003569
Chris Lattner3221ad02004-04-17 22:58:41 +00003570 if (const CallInst *CI = dyn_cast<CallInst>(I))
3571 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003572 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003573 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003574}
3575
Chris Lattner3221ad02004-04-17 22:58:41 +00003576/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3577/// in the loop that V is derived from. We allow arbitrary operations along the
3578/// way, but the operands of an operation must either be constants or a value
3579/// derived from a constant PHI. If this expression does not fit with these
3580/// constraints, return null.
3581static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3582 // If this is not an instruction, or if this is an instruction outside of the
3583 // loop, it can't be derived from a loop PHI.
3584 Instruction *I = dyn_cast<Instruction>(V);
3585 if (I == 0 || !L->contains(I->getParent())) return 0;
3586
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003587 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003588 if (L->getHeader() == I->getParent())
3589 return PN;
3590 else
3591 // We don't currently keep track of the control flow needed to evaluate
3592 // PHIs, so we cannot handle PHIs inside of loops.
3593 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003594 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003595
3596 // If we won't be able to constant fold this expression even if the operands
3597 // are constants, return early.
3598 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003599
Chris Lattner3221ad02004-04-17 22:58:41 +00003600 // Otherwise, we can evaluate this instruction if all of its operands are
3601 // constant or derived from a PHI node themselves.
3602 PHINode *PHI = 0;
3603 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3604 if (!(isa<Constant>(I->getOperand(Op)) ||
3605 isa<GlobalValue>(I->getOperand(Op)))) {
3606 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3607 if (P == 0) return 0; // Not evolving from PHI
3608 if (PHI == 0)
3609 PHI = P;
3610 else if (PHI != P)
3611 return 0; // Evolving from multiple different PHIs.
3612 }
3613
3614 // This is a expression evolving from a constant PHI!
3615 return PHI;
3616}
3617
3618/// EvaluateExpression - Given an expression that passes the
3619/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3620/// in the loop has the value PHIVal. If we can't fold this expression for some
3621/// reason, return null.
3622static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3623 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003624 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003625 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003626 Instruction *I = cast<Instruction>(V);
Owen Anderson07cf79e2009-07-06 23:00:19 +00003627 LLVMContext *Context = I->getParent()->getContext();
Chris Lattner3221ad02004-04-17 22:58:41 +00003628
3629 std::vector<Constant*> Operands;
3630 Operands.resize(I->getNumOperands());
3631
3632 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3633 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3634 if (Operands[i] == 0) return 0;
3635 }
3636
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003637 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3638 return ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003639 &Operands[0], Operands.size(),
3640 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003641 else
3642 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003643 &Operands[0], Operands.size(),
3644 Context);
Chris Lattner3221ad02004-04-17 22:58:41 +00003645}
3646
3647/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3648/// in the header of its containing loop, we know the loop executes a
3649/// constant number of times, and the PHI node is just a recurrence
3650/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003651Constant *
3652ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3653 const APInt& BEs,
3654 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003655 std::map<PHINode*, Constant*>::iterator I =
3656 ConstantEvolutionLoopExitValue.find(PN);
3657 if (I != ConstantEvolutionLoopExitValue.end())
3658 return I->second;
3659
Dan Gohman46bdfb02009-02-24 18:55:53 +00003660 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003661 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3662
3663 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3664
3665 // Since the loop is canonicalized, the PHI node must have two entries. One
3666 // entry must be a constant (coming in from outside of the loop), and the
3667 // second must be derived from the same PHI.
3668 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3669 Constant *StartCST =
3670 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3671 if (StartCST == 0)
3672 return RetVal = 0; // Must be a constant.
3673
3674 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3675 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3676 if (PN2 != PN)
3677 return RetVal = 0; // Not derived from same PHI.
3678
3679 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003680 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003681 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003682
Dan Gohman46bdfb02009-02-24 18:55:53 +00003683 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003684 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003685 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3686 if (IterationNum == NumIterations)
3687 return RetVal = PHIVal; // Got exit value!
3688
3689 // Compute the value of the PHI node for the next iteration.
3690 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3691 if (NextPHI == PHIVal)
3692 return RetVal = NextPHI; // Stopped evolving!
3693 if (NextPHI == 0)
3694 return 0; // Couldn't evaluate!
3695 PHIVal = NextPHI;
3696 }
3697}
3698
Dan Gohman46bdfb02009-02-24 18:55:53 +00003699/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003700/// constant number of times (the condition evolves only from constants),
3701/// try to evaluate a few iterations of the loop until we get the exit
3702/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003703/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003704const SCEV *
3705ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3706 Value *Cond,
3707 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003708 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003709 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003710
3711 // Since the loop is canonicalized, the PHI node must have two entries. One
3712 // entry must be a constant (coming in from outside of the loop), and the
3713 // second must be derived from the same PHI.
3714 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3715 Constant *StartCST =
3716 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003717 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003718
3719 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3720 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003721 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003722
3723 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3724 // the loop symbolically to determine when the condition gets a value of
3725 // "ExitWhen".
3726 unsigned IterationNum = 0;
3727 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3728 for (Constant *PHIVal = StartCST;
3729 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003730 ConstantInt *CondVal =
3731 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003732
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003733 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003734 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003735
Reid Spencere8019bb2007-03-01 07:25:48 +00003736 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003737 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003738 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003739 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003740
Chris Lattner3221ad02004-04-17 22:58:41 +00003741 // Compute the value of the PHI node for the next iteration.
3742 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3743 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003744 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003745 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003746 }
3747
3748 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003749 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003750}
3751
Dan Gohman66a7e852009-05-08 20:38:54 +00003752/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3753/// at the specified scope in the program. The L value specifies a loop
3754/// nest to evaluate the expression at, where null is the top-level or a
3755/// specified loop is immediately inside of the loop.
3756///
3757/// This method can be used to compute the exit value for a variable defined
3758/// in a loop by querying what the value will hold in the parent loop.
3759///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003760/// In the case that a relevant loop exit value cannot be computed, the
3761/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003762const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003763 // FIXME: this should be turned into a virtual method on SCEV!
3764
Chris Lattner3221ad02004-04-17 22:58:41 +00003765 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003766
Nick Lewycky3e630762008-02-20 06:48:22 +00003767 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003768 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003769 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003770 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003771 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003772 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3773 if (PHINode *PN = dyn_cast<PHINode>(I))
3774 if (PN->getParent() == LI->getHeader()) {
3775 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003776 // to see if the loop that contains it has a known backedge-taken
3777 // count. If so, we may be able to force computation of the exit
3778 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003779 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003780 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003781 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003782 // Okay, we know how many times the containing loop executes. If
3783 // this is a constant evolving PHI node, get the final value at
3784 // the specified iteration number.
3785 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003786 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003787 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003788 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003789 }
3790 }
3791
Reid Spencer09906f32006-12-04 21:33:23 +00003792 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003793 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003794 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003795 // result. This is particularly useful for computing loop exit values.
3796 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003797 // Check to see if we've folded this instruction at this loop before.
3798 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3799 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3800 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3801 if (!Pair.second)
Dan Gohman09987962009-06-29 21:31:18 +00003802 return Pair.first->second ? &*getSCEV(Pair.first->second) : V;
Dan Gohman6bce6432009-05-08 20:47:27 +00003803
Chris Lattner3221ad02004-04-17 22:58:41 +00003804 std::vector<Constant*> Operands;
3805 Operands.reserve(I->getNumOperands());
3806 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3807 Value *Op = I->getOperand(i);
3808 if (Constant *C = dyn_cast<Constant>(Op)) {
3809 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003810 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003811 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003812 // non-integer and non-pointer, don't even try to analyze them
3813 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003814 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003815 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003816
Dan Gohman85b05a22009-07-13 21:35:55 +00003817 const SCEV* OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00003818 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003819 Constant *C = SC->getValue();
3820 if (C->getType() != Op->getType())
3821 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3822 Op->getType(),
3823 false),
3824 C, Op->getType());
3825 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003826 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003827 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3828 if (C->getType() != Op->getType())
3829 C =
3830 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3831 Op->getType(),
3832 false),
3833 C, Op->getType());
3834 Operands.push_back(C);
3835 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003836 return V;
3837 } else {
3838 return V;
3839 }
3840 }
3841 }
Dan Gohman64a845e2009-06-24 04:48:43 +00003842
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003843 Constant *C;
3844 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3845 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Owen Anderson50895512009-07-06 18:42:36 +00003846 &Operands[0], Operands.size(),
3847 Context);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003848 else
3849 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Owen Anderson50895512009-07-06 18:42:36 +00003850 &Operands[0], Operands.size(), Context);
Dan Gohman6bce6432009-05-08 20:47:27 +00003851 Pair.first->second = C;
Dan Gohman09987962009-06-29 21:31:18 +00003852 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003853 }
3854 }
3855
3856 // This is some other type of SCEVUnknown, just return it.
3857 return V;
3858 }
3859
Dan Gohman622ed672009-05-04 22:02:23 +00003860 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003861 // Avoid performing the look-up in the common case where the specified
3862 // expression has no loop-variant portions.
3863 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003864 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003865 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003866 // Okay, at least one of these operands is loop variant but might be
3867 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00003868 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3869 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003870 NewOps.push_back(OpAtScope);
3871
3872 for (++i; i != e; ++i) {
3873 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003874 NewOps.push_back(OpAtScope);
3875 }
3876 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003877 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003878 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003879 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003880 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003881 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003882 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003883 return getUMaxExpr(NewOps);
Torok Edwinc25e7582009-07-11 20:10:48 +00003884 LLVM_UNREACHABLE("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003885 }
3886 }
3887 // If we got here, all operands are loop invariant.
3888 return Comm;
3889 }
3890
Dan Gohman622ed672009-05-04 22:02:23 +00003891 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003892 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
3893 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003894 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3895 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003896 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003897 }
3898
3899 // If this is a loop recurrence for a loop that does not contain L, then we
3900 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003901 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003902 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3903 // To evaluate this recurrence, we need to know how many times the AddRec
3904 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003905 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00003906 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003907
Eli Friedmanb42a6262008-08-04 23:49:06 +00003908 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003909 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003910 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003911 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003912 }
3913
Dan Gohman622ed672009-05-04 22:02:23 +00003914 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003915 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003916 if (Op == Cast->getOperand())
3917 return Cast; // must be loop invariant
3918 return getZeroExtendExpr(Op, Cast->getType());
3919 }
3920
Dan Gohman622ed672009-05-04 22:02:23 +00003921 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003922 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003923 if (Op == Cast->getOperand())
3924 return Cast; // must be loop invariant
3925 return getSignExtendExpr(Op, Cast->getType());
3926 }
3927
Dan Gohman622ed672009-05-04 22:02:23 +00003928 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003929 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003930 if (Op == Cast->getOperand())
3931 return Cast; // must be loop invariant
3932 return getTruncateExpr(Op, Cast->getType());
3933 }
3934
Torok Edwinc25e7582009-07-11 20:10:48 +00003935 LLVM_UNREACHABLE("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003936 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003937}
3938
Dan Gohman66a7e852009-05-08 20:38:54 +00003939/// getSCEVAtScope - This is a convenience function which does
3940/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00003941const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003942 return getSCEVAtScope(getSCEV(V), L);
3943}
3944
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003945/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3946/// following equation:
3947///
3948/// A * X = B (mod N)
3949///
3950/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3951/// A and B isn't important.
3952///
3953/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003954static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003955 ScalarEvolution &SE) {
3956 uint32_t BW = A.getBitWidth();
3957 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3958 assert(A != 0 && "A must be non-zero.");
3959
3960 // 1. D = gcd(A, N)
3961 //
3962 // The gcd of A and N may have only one prime factor: 2. The number of
3963 // trailing zeros in A is its multiplicity
3964 uint32_t Mult2 = A.countTrailingZeros();
3965 // D = 2^Mult2
3966
3967 // 2. Check if B is divisible by D.
3968 //
3969 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3970 // is not less than multiplicity of this prime factor for D.
3971 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003972 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003973
3974 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3975 // modulo (N / D).
3976 //
3977 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3978 // bit width during computations.
3979 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3980 APInt Mod(BW + 1, 0);
3981 Mod.set(BW - Mult2); // Mod = N / D
3982 APInt I = AD.multiplicativeInverse(Mod);
3983
3984 // 4. Compute the minimum unsigned root of the equation:
3985 // I * (B / D) mod (N / D)
3986 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3987
3988 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3989 // bits.
3990 return SE.getConstant(Result.trunc(BW));
3991}
Chris Lattner53e677a2004-04-02 20:23:17 +00003992
3993/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3994/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3995/// might be the same) or two SCEVCouldNotCompute objects.
3996///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003997static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00003998SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003999 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004000 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4001 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4002 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004003
Chris Lattner53e677a2004-04-02 20:23:17 +00004004 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004005 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004006 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004007 return std::make_pair(CNC, CNC);
4008 }
4009
Reid Spencere8019bb2007-03-01 07:25:48 +00004010 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004011 const APInt &L = LC->getValue()->getValue();
4012 const APInt &M = MC->getValue()->getValue();
4013 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004014 APInt Two(BitWidth, 2);
4015 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004016
Dan Gohman64a845e2009-06-24 04:48:43 +00004017 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004018 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004019 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004020 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4021 // The B coefficient is M-N/2
4022 APInt B(M);
4023 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004024
Reid Spencere8019bb2007-03-01 07:25:48 +00004025 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004026 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004027
Reid Spencere8019bb2007-03-01 07:25:48 +00004028 // Compute the B^2-4ac term.
4029 APInt SqrtTerm(B);
4030 SqrtTerm *= B;
4031 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004032
Reid Spencere8019bb2007-03-01 07:25:48 +00004033 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4034 // integer value or else APInt::sqrt() will assert.
4035 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004036
Dan Gohman64a845e2009-06-24 04:48:43 +00004037 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004038 // The divisions must be performed as signed divisions.
4039 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004040 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004041 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004042 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004043 return std::make_pair(CNC, CNC);
4044 }
4045
Owen Anderson76f600b2009-07-06 22:37:39 +00004046 LLVMContext *Context = SE.getContext();
4047
4048 ConstantInt *Solution1 =
4049 Context->getConstantInt((NegB + SqrtVal).sdiv(TwoA));
4050 ConstantInt *Solution2 =
4051 Context->getConstantInt((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004052
Dan Gohman64a845e2009-06-24 04:48:43 +00004053 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004054 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004055 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004056}
4057
4058/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004059/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004060const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004061 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004062 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004063 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004064 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004065 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004066 }
4067
Dan Gohman35738ac2009-05-04 22:30:44 +00004068 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004069 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004070 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004071
4072 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004073 // If this is an affine expression, the execution count of this branch is
4074 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004075 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004076 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004077 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004078 // equivalent to:
4079 //
4080 // Step*N = -Start (mod 2^BW)
4081 //
4082 // where BW is the common bit width of Start and Step.
4083
Chris Lattner53e677a2004-04-02 20:23:17 +00004084 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004085 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4086 L->getParentLoop());
4087 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4088 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004089
Dan Gohman622ed672009-05-04 22:02:23 +00004090 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004091 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004092
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004093 // First, handle unitary steps.
4094 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004095 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004096 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4097 return Start; // N = Start (as unsigned)
4098
4099 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004100 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004101 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004102 -StartC->getValue()->getValue(),
4103 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004104 }
Chris Lattner42a75512007-01-15 02:27:26 +00004105 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004106 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4107 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004108 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004109 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004110 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4111 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004112 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004113#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004114 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4115 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004116#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004117 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004118 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004119 dyn_cast<ConstantInt>(Context->getConstantExprICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004120 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004121 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004122 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004123
Chris Lattner53e677a2004-04-02 20:23:17 +00004124 // We can only use this value if the chrec ends up with an exact zero
4125 // value at this index. When solving for "X*X != 5", for example, we
4126 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004127 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004128 if (Val->isZero())
4129 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004130 }
4131 }
4132 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004133
Dan Gohman1c343752009-06-27 21:21:31 +00004134 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004135}
4136
4137/// HowFarToNonZero - Return the number of times a backedge checking the
4138/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004139/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004140const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004141 // Loops that look like: while (X == 0) are very strange indeed. We don't
4142 // handle them yet except for the trivial case. This could be expanded in the
4143 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004144
Chris Lattner53e677a2004-04-02 20:23:17 +00004145 // If the value is a constant, check to see if it is known to be non-zero
4146 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004147 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004148 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004149 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004150 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004151 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004152
Chris Lattner53e677a2004-04-02 20:23:17 +00004153 // We could implement others, but I really doubt anyone writes loops like
4154 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004155 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004156}
4157
Dan Gohman859b4822009-05-18 15:36:09 +00004158/// getLoopPredecessor - If the given loop's header has exactly one unique
4159/// predecessor outside the loop, return it. Otherwise return null.
4160///
4161BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4162 BasicBlock *Header = L->getHeader();
4163 BasicBlock *Pred = 0;
4164 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4165 PI != E; ++PI)
4166 if (!L->contains(*PI)) {
4167 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4168 Pred = *PI;
4169 }
4170 return Pred;
4171}
4172
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004173/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4174/// (which may not be an immediate predecessor) which has exactly one
4175/// successor from which BB is reachable, or null if no such block is
4176/// found.
4177///
4178BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004179ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004180 // If the block has a unique predecessor, then there is no path from the
4181 // predecessor to the block that does not go through the direct edge
4182 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004183 if (BasicBlock *Pred = BB->getSinglePredecessor())
4184 return Pred;
4185
4186 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004187 // If the header has a unique predecessor outside the loop, it must be
4188 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004189 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004190 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004191
4192 return 0;
4193}
4194
Dan Gohman763bad12009-06-20 00:35:32 +00004195/// HasSameValue - SCEV structural equivalence is usually sufficient for
4196/// testing whether two expressions are equal, however for the purposes of
4197/// looking for a condition guarding a loop, it can be useful to be a little
4198/// more general, since a front-end may have replicated the controlling
4199/// expression.
4200///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004201static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004202 // Quick check to see if they are the same SCEV.
4203 if (A == B) return true;
4204
4205 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4206 // two different instructions with the same value. Check for this case.
4207 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4208 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4209 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4210 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
4211 if (AI->isIdenticalTo(BI))
4212 return true;
4213
4214 // Otherwise assume they may have a different value.
4215 return false;
4216}
4217
Dan Gohman85b05a22009-07-13 21:35:55 +00004218bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4219 return getSignedRange(S).getSignedMax().isNegative();
4220}
4221
4222bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4223 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4224}
4225
4226bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4227 return !getSignedRange(S).getSignedMin().isNegative();
4228}
4229
4230bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4231 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4232}
4233
4234bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4235 return isKnownNegative(S) || isKnownPositive(S);
4236}
4237
4238bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4239 const SCEV *LHS, const SCEV *RHS) {
4240
4241 if (HasSameValue(LHS, RHS))
4242 return ICmpInst::isTrueWhenEqual(Pred);
4243
4244 switch (Pred) {
4245 default:
4246 assert(0 && "Unexpected ICmpInst::Predicate value!");
4247 break;
4248 case ICmpInst::ICMP_SGT:
4249 Pred = ICmpInst::ICMP_SLT;
4250 std::swap(LHS, RHS);
4251 case ICmpInst::ICMP_SLT: {
4252 ConstantRange LHSRange = getSignedRange(LHS);
4253 ConstantRange RHSRange = getSignedRange(RHS);
4254 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4255 return true;
4256 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4257 return false;
4258
4259 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4260 ConstantRange DiffRange = getUnsignedRange(Diff);
4261 if (isKnownNegative(Diff)) {
4262 if (DiffRange.getUnsignedMax().ult(LHSRange.getUnsignedMin()))
4263 return true;
4264 if (DiffRange.getUnsignedMin().uge(LHSRange.getUnsignedMax()))
4265 return false;
4266 } else if (isKnownPositive(Diff)) {
4267 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4268 return true;
4269 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4270 return false;
4271 }
4272 break;
4273 }
4274 case ICmpInst::ICMP_SGE:
4275 Pred = ICmpInst::ICMP_SLE;
4276 std::swap(LHS, RHS);
4277 case ICmpInst::ICMP_SLE: {
4278 ConstantRange LHSRange = getSignedRange(LHS);
4279 ConstantRange RHSRange = getSignedRange(RHS);
4280 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4281 return true;
4282 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4283 return false;
4284
4285 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4286 ConstantRange DiffRange = getUnsignedRange(Diff);
4287 if (isKnownNonPositive(Diff)) {
4288 if (DiffRange.getUnsignedMax().ule(LHSRange.getUnsignedMin()))
4289 return true;
4290 if (DiffRange.getUnsignedMin().ugt(LHSRange.getUnsignedMax()))
4291 return false;
4292 } else if (isKnownNonNegative(Diff)) {
4293 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4294 return true;
4295 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4296 return false;
4297 }
4298 break;
4299 }
4300 case ICmpInst::ICMP_UGT:
4301 Pred = ICmpInst::ICMP_ULT;
4302 std::swap(LHS, RHS);
4303 case ICmpInst::ICMP_ULT: {
4304 ConstantRange LHSRange = getUnsignedRange(LHS);
4305 ConstantRange RHSRange = getUnsignedRange(RHS);
4306 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4307 return true;
4308 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4309 return false;
4310
4311 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4312 ConstantRange DiffRange = getUnsignedRange(Diff);
4313 if (LHSRange.getUnsignedMax().ult(DiffRange.getUnsignedMin()))
4314 return true;
4315 if (LHSRange.getUnsignedMin().uge(DiffRange.getUnsignedMax()))
4316 return false;
4317 break;
4318 }
4319 case ICmpInst::ICMP_UGE:
4320 Pred = ICmpInst::ICMP_ULE;
4321 std::swap(LHS, RHS);
4322 case ICmpInst::ICMP_ULE: {
4323 ConstantRange LHSRange = getUnsignedRange(LHS);
4324 ConstantRange RHSRange = getUnsignedRange(RHS);
4325 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4326 return true;
4327 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4328 return false;
4329
4330 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4331 ConstantRange DiffRange = getUnsignedRange(Diff);
4332 if (LHSRange.getUnsignedMax().ule(DiffRange.getUnsignedMin()))
4333 return true;
4334 if (LHSRange.getUnsignedMin().ugt(DiffRange.getUnsignedMax()))
4335 return false;
4336 break;
4337 }
4338 case ICmpInst::ICMP_NE: {
4339 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4340 return true;
4341 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4342 return true;
4343
4344 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4345 if (isKnownNonZero(Diff))
4346 return true;
4347 break;
4348 }
4349 case ICmpInst::ICMP_EQ:
4350 break;
4351 }
4352 return false;
4353}
4354
4355/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4356/// protected by a conditional between LHS and RHS. This is used to
4357/// to eliminate casts.
4358bool
4359ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4360 ICmpInst::Predicate Pred,
4361 const SCEV *LHS, const SCEV *RHS) {
4362 // Interpret a null as meaning no loop, where there is obviously no guard
4363 // (interprocedural conditions notwithstanding).
4364 if (!L) return true;
4365
4366 BasicBlock *Latch = L->getLoopLatch();
4367 if (!Latch)
4368 return false;
4369
4370 BranchInst *LoopContinuePredicate =
4371 dyn_cast<BranchInst>(Latch->getTerminator());
4372 if (!LoopContinuePredicate ||
4373 LoopContinuePredicate->isUnconditional())
4374 return false;
4375
4376 return
4377 isNecessaryCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4378 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
4379}
4380
4381/// isLoopGuardedByCond - Test whether entry to the loop is protected
4382/// by a conditional between LHS and RHS. This is used to help avoid max
4383/// expressions in loop trip counts, and to eliminate casts.
4384bool
4385ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4386 ICmpInst::Predicate Pred,
4387 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004388 // Interpret a null as meaning no loop, where there is obviously no guard
4389 // (interprocedural conditions notwithstanding).
4390 if (!L) return false;
4391
Dan Gohman859b4822009-05-18 15:36:09 +00004392 BasicBlock *Predecessor = getLoopPredecessor(L);
4393 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004394
Dan Gohman859b4822009-05-18 15:36:09 +00004395 // Starting at the loop predecessor, climb up the predecessor chain, as long
4396 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004397 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004398 for (; Predecessor;
4399 PredecessorDest = Predecessor,
4400 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004401
4402 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004403 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004404 if (!LoopEntryPredicate ||
4405 LoopEntryPredicate->isUnconditional())
4406 continue;
4407
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004408 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4409 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004410 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004411 }
4412
Dan Gohman38372182008-08-12 20:17:31 +00004413 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004414}
4415
Dan Gohman85b05a22009-07-13 21:35:55 +00004416/// isNecessaryCond - Test whether the condition described by Pred, LHS,
4417/// and RHS is a necessary condition for the given Cond value to evaluate
4418/// to true.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004419bool ScalarEvolution::isNecessaryCond(Value *CondValue,
4420 ICmpInst::Predicate Pred,
4421 const SCEV *LHS, const SCEV *RHS,
4422 bool Inverse) {
4423 // Recursivly handle And and Or conditions.
4424 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4425 if (BO->getOpcode() == Instruction::And) {
4426 if (!Inverse)
4427 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4428 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4429 } else if (BO->getOpcode() == Instruction::Or) {
4430 if (Inverse)
4431 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4432 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
4433 }
4434 }
4435
4436 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4437 if (!ICI) return false;
4438
4439 // Now that we found a conditional branch that dominates the loop, check to
4440 // see if it is the comparison we are looking for.
4441 Value *PreCondLHS = ICI->getOperand(0);
4442 Value *PreCondRHS = ICI->getOperand(1);
Dan Gohman85b05a22009-07-13 21:35:55 +00004443 ICmpInst::Predicate FoundPred;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004444 if (Inverse)
Dan Gohman85b05a22009-07-13 21:35:55 +00004445 FoundPred = ICI->getInversePredicate();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004446 else
Dan Gohman85b05a22009-07-13 21:35:55 +00004447 FoundPred = ICI->getPredicate();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004448
Dan Gohman85b05a22009-07-13 21:35:55 +00004449 if (FoundPred == Pred)
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004450 ; // An exact match.
Dan Gohman85b05a22009-07-13 21:35:55 +00004451 else if (!ICmpInst::isTrueWhenEqual(FoundPred) && Pred == ICmpInst::ICMP_NE) {
4452 // The actual condition is beyond sufficient.
4453 FoundPred = ICmpInst::ICMP_NE;
4454 // NE is symmetric but the original comparison may not be. Swap
4455 // the operands if necessary so that they match below.
4456 if (isa<SCEVConstant>(LHS))
4457 std::swap(PreCondLHS, PreCondRHS);
4458 } else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004459 // Check a few special cases.
Dan Gohman85b05a22009-07-13 21:35:55 +00004460 switch (FoundPred) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004461 case ICmpInst::ICMP_UGT:
4462 if (Pred == ICmpInst::ICMP_ULT) {
4463 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman85b05a22009-07-13 21:35:55 +00004464 FoundPred = ICmpInst::ICMP_ULT;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004465 break;
4466 }
4467 return false;
4468 case ICmpInst::ICMP_SGT:
4469 if (Pred == ICmpInst::ICMP_SLT) {
4470 std::swap(PreCondLHS, PreCondRHS);
Dan Gohman85b05a22009-07-13 21:35:55 +00004471 FoundPred = ICmpInst::ICMP_SLT;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004472 break;
4473 }
4474 return false;
4475 case ICmpInst::ICMP_NE:
4476 // Expressions like (x >u 0) are often canonicalized to (x != 0),
4477 // so check for this case by checking if the NE is comparing against
4478 // a minimum or maximum constant.
4479 if (!ICmpInst::isTrueWhenEqual(Pred))
Dan Gohman85b05a22009-07-13 21:35:55 +00004480 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(RHS)) {
4481 const APInt &A = C->getValue()->getValue();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004482 switch (Pred) {
4483 case ICmpInst::ICMP_SLT:
4484 if (A.isMaxSignedValue()) break;
4485 return false;
4486 case ICmpInst::ICMP_SGT:
4487 if (A.isMinSignedValue()) break;
4488 return false;
4489 case ICmpInst::ICMP_ULT:
4490 if (A.isMaxValue()) break;
4491 return false;
4492 case ICmpInst::ICMP_UGT:
4493 if (A.isMinValue()) break;
4494 return false;
4495 default:
4496 return false;
4497 }
Dan Gohman85b05a22009-07-13 21:35:55 +00004498 FoundPred = Pred;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004499 // NE is symmetric but the original comparison may not be. Swap
4500 // the operands if necessary so that they match below.
4501 if (isa<SCEVConstant>(LHS))
4502 std::swap(PreCondLHS, PreCondRHS);
4503 break;
4504 }
4505 return false;
4506 default:
4507 // We weren't able to reconcile the condition.
4508 return false;
4509 }
4510
Dan Gohman85b05a22009-07-13 21:35:55 +00004511 assert(Pred == FoundPred && "Conditions were not reconciled!");
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004512
Dan Gohman85b05a22009-07-13 21:35:55 +00004513 // Bail if the ICmp's operands' types are wider than the needed type
4514 // before attempting to call getSCEV on them. This avoids infinite
4515 // recursion, since the analysis of widening casts can require loop
4516 // exit condition information for overflow checking, which would
4517 // lead back here.
4518 if (getTypeSizeInBits(LHS->getType()) <
4519 getTypeSizeInBits(PreCondLHS->getType()))
4520 return false;
4521
4522 const SCEV *FoundLHS = getSCEV(PreCondLHS);
4523 const SCEV *FoundRHS = getSCEV(PreCondRHS);
4524
4525 // Balance the types. The case where FoundLHS' type is wider than
4526 // LHS' type is checked for above.
4527 if (getTypeSizeInBits(LHS->getType()) >
4528 getTypeSizeInBits(FoundLHS->getType())) {
4529 if (CmpInst::isSigned(Pred)) {
4530 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4531 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4532 } else {
4533 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4534 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4535 }
4536 }
4537
4538 return isNecessaryCondOperands(Pred, LHS, RHS,
4539 FoundLHS, FoundRHS) ||
4540 // ~x < ~y --> x > y
4541 isNecessaryCondOperands(Pred, LHS, RHS,
4542 getNotSCEV(FoundRHS), getNotSCEV(FoundLHS));
4543}
4544
4545/// isNecessaryCondOperands - Test whether the condition described by Pred,
4546/// LHS, and RHS is a necessary condition for the condition described by
4547/// Pred, FoundLHS, and FoundRHS to evaluate to true.
4548bool
4549ScalarEvolution::isNecessaryCondOperands(ICmpInst::Predicate Pred,
4550 const SCEV *LHS, const SCEV *RHS,
4551 const SCEV *FoundLHS,
4552 const SCEV *FoundRHS) {
4553 switch (Pred) {
4554 default: break;
4555 case ICmpInst::ICMP_SLT:
4556 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4557 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4558 return true;
4559 break;
4560 case ICmpInst::ICMP_SGT:
4561 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4562 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4563 return true;
4564 break;
4565 case ICmpInst::ICMP_ULT:
4566 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4567 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4568 return true;
4569 break;
4570 case ICmpInst::ICMP_UGT:
4571 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4572 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4573 return true;
4574 break;
4575 }
4576
4577 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004578}
4579
Dan Gohman51f53b72009-06-21 23:46:38 +00004580/// getBECount - Subtract the end and start values and divide by the step,
4581/// rounding up, to get the number of times the backedge is executed. Return
4582/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004583const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004584 const SCEV *End,
4585 const SCEV *Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004586 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004587 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4588 const SCEV *Diff = getMinusSCEV(End, Start);
4589 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004590
4591 // Add an adjustment to the difference between End and Start so that
4592 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004593 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004594
4595 // Check Add for unsigned overflow.
4596 // TODO: More sophisticated things could be done here.
Owen Anderson76f600b2009-07-06 22:37:39 +00004597 const Type *WideTy = Context->getIntegerType(getTypeSizeInBits(Ty) + 1);
Dan Gohman85b05a22009-07-13 21:35:55 +00004598 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4599 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4600 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004601 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
Dan Gohman1c343752009-06-27 21:21:31 +00004602 return getCouldNotCompute();
Dan Gohman51f53b72009-06-21 23:46:38 +00004603
4604 return getUDivExpr(Add, Step);
4605}
4606
Chris Lattnerdb25de42005-08-15 23:33:51 +00004607/// HowManyLessThans - Return the number of times a backedge containing the
4608/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004609/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004610ScalarEvolution::BackedgeTakenInfo
4611ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4612 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004613 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004614 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004615
Dan Gohman35738ac2009-05-04 22:30:44 +00004616 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004617 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004618 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004619
4620 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004621 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004622 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004623 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004624
4625 // TODO: handle non-constant strides.
4626 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4627 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004628 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004629 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004630 // With unit stride, the iteration never steps past the limit value.
4631 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4632 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4633 // Test whether a positive iteration iteration can step past the limit
4634 // value and past the maximum value for its type in a single step.
4635 if (isSigned) {
4636 APInt Max = APInt::getSignedMaxValue(BitWidth);
4637 if ((Max - CStep->getValue()->getValue())
4638 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004639 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004640 } else {
4641 APInt Max = APInt::getMaxValue(BitWidth);
4642 if ((Max - CStep->getValue()->getValue())
4643 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004644 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004645 }
4646 } else
4647 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004648 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004649 } else
4650 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004651 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004652
Dan Gohmana1af7572009-04-30 20:47:05 +00004653 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4654 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4655 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004656 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004657
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004658 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004659 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004660
Dan Gohmana1af7572009-04-30 20:47:05 +00004661 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004662 const SCEV *MinStart = getConstant(isSigned ?
4663 getSignedRange(Start).getSignedMin() :
4664 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004665
Dan Gohmana1af7572009-04-30 20:47:05 +00004666 // If we know that the condition is true in order to enter the loop,
4667 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004668 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4669 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004670 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004671 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00004672 isSigned ? ICmpInst::ICMP_SLT :
4673 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00004674 getMinusSCEV(Start, Step), RHS))
4675 End = isSigned ? getSMaxExpr(RHS, Start)
4676 : getUMaxExpr(RHS, Start);
4677
4678 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004679 const SCEV *MaxEnd = getConstant(isSigned ?
4680 getSignedRange(End).getSignedMax() :
4681 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00004682
4683 // Finally, we subtract these two values and divide, rounding up, to get
4684 // the number of times the backedge is executed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004685 const SCEV *BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004686
4687 // The maximum backedge count is similar, except using the minimum start
4688 // value and the maximum end value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004689 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004690
4691 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004692 }
4693
Dan Gohman1c343752009-06-27 21:21:31 +00004694 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004695}
4696
Chris Lattner53e677a2004-04-02 20:23:17 +00004697/// getNumIterationsInRange - Return the number of iterations of this loop that
4698/// produce values in the specified constant range. Another way of looking at
4699/// this is that it returns the first iteration number where the value is not in
4700/// the condition, thus computing the exit count. If the iteration count can't
4701/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004702const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004703 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004704 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004705 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004706
4707 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004708 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004709 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004710 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004711 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004712 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004713 if (const SCEVAddRecExpr *ShiftedAddRec =
4714 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004715 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004716 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004717 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004718 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004719 }
4720
4721 // The only time we can solve this is when we have all constant indices.
4722 // Otherwise, we cannot determine the overflow conditions.
4723 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4724 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004725 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004726
4727
4728 // Okay at this point we know that all elements of the chrec are constants and
4729 // that the start element is zero.
4730
4731 // First check to see if the range contains zero. If not, the first
4732 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004733 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004734 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004735 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004736
Chris Lattner53e677a2004-04-02 20:23:17 +00004737 if (isAffine()) {
4738 // If this is an affine expression then we have this situation:
4739 // Solve {0,+,A} in Range === Ax in Range
4740
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004741 // We know that zero is in the range. If A is positive then we know that
4742 // the upper value of the range must be the first possible exit value.
4743 // If A is negative then the lower of the range is the last possible loop
4744 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004745 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004746 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4747 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004748
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004749 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004750 APInt ExitVal = (End + A).udiv(A);
Owen Anderson76f600b2009-07-06 22:37:39 +00004751 ConstantInt *ExitValue = SE.getContext()->getConstantInt(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004752
4753 // Evaluate at the exit value. If we really did fall out of the valid
4754 // range, then we computed our trip count, otherwise wrap around or other
4755 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004756 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004757 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004758 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004759
4760 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004761 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00004762 EvaluateConstantChrecAtConstant(this,
Owen Anderson76f600b2009-07-06 22:37:39 +00004763 SE.getContext()->getConstantInt(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004764 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004765 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004766 } else if (isQuadratic()) {
4767 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4768 // quadratic equation to solve it. To do this, we must frame our problem in
4769 // terms of figuring out when zero is crossed, instead of when
4770 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004771 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004772 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00004773 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004774
4775 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00004776 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004777 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004778 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4779 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004780 if (R1) {
4781 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004782 if (ConstantInt *CB =
Owen Anderson76f600b2009-07-06 22:37:39 +00004783 dyn_cast<ConstantInt>(
4784 SE.getContext()->getConstantExprICmp(ICmpInst::ICMP_ULT,
4785 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004786 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004787 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004788
Chris Lattner53e677a2004-04-02 20:23:17 +00004789 // Make sure the root is not off by one. The returned iteration should
4790 // not be in the range, but the previous one should be. When solving
4791 // for "X*X < 5", for example, we should not return a root of 2.
4792 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004793 R1->getValue(),
4794 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004795 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004796 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00004797 ConstantInt *NextVal =
4798 SE.getContext()->getConstantInt(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004799
Dan Gohman246b2562007-10-22 18:31:58 +00004800 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004801 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004802 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004803 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004804 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004805
Chris Lattner53e677a2004-04-02 20:23:17 +00004806 // If R1 was not in the range, then it is a good return value. Make
4807 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00004808 ConstantInt *NextVal =
4809 SE.getContext()->getConstantInt(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004810 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004811 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004812 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004813 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004814 }
4815 }
4816 }
4817
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004818 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004819}
4820
4821
4822
4823//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004824// SCEVCallbackVH Class Implementation
4825//===----------------------------------------------------------------------===//
4826
Dan Gohman1959b752009-05-19 19:22:47 +00004827void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00004828 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004829 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4830 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004831 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4832 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004833 SE->Scalars.erase(getValPtr());
4834 // this now dangles!
4835}
4836
Dan Gohman1959b752009-05-19 19:22:47 +00004837void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00004838 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004839
4840 // Forget all the expressions associated with users of the old value,
4841 // so that future queries will recompute the expressions using the new
4842 // value.
4843 SmallVector<User *, 16> Worklist;
4844 Value *Old = getValPtr();
4845 bool DeleteOld = false;
4846 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4847 UI != UE; ++UI)
4848 Worklist.push_back(*UI);
4849 while (!Worklist.empty()) {
4850 User *U = Worklist.pop_back_val();
4851 // Deleting the Old value will cause this to dangle. Postpone
4852 // that until everything else is done.
4853 if (U == Old) {
4854 DeleteOld = true;
4855 continue;
4856 }
4857 if (PHINode *PN = dyn_cast<PHINode>(U))
4858 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004859 if (Instruction *I = dyn_cast<Instruction>(U))
4860 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004861 if (SE->Scalars.erase(U))
4862 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4863 UI != UE; ++UI)
4864 Worklist.push_back(*UI);
4865 }
4866 if (DeleteOld) {
4867 if (PHINode *PN = dyn_cast<PHINode>(Old))
4868 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004869 if (Instruction *I = dyn_cast<Instruction>(Old))
4870 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004871 SE->Scalars.erase(Old);
4872 // this now dangles!
4873 }
4874 // this may dangle!
4875}
4876
Dan Gohman1959b752009-05-19 19:22:47 +00004877ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004878 : CallbackVH(V), SE(se) {}
4879
4880//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004881// ScalarEvolution Class Implementation
4882//===----------------------------------------------------------------------===//
4883
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004884ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00004885 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004886}
4887
Chris Lattner53e677a2004-04-02 20:23:17 +00004888bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004889 this->F = &F;
4890 LI = &getAnalysis<LoopInfo>();
4891 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004892 return false;
4893}
4894
4895void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004896 Scalars.clear();
4897 BackedgeTakenCounts.clear();
4898 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004899 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00004900 UniqueSCEVs.clear();
4901 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00004902}
4903
4904void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4905 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004906 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004907}
4908
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004909bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004910 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004911}
4912
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004913static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004914 const Loop *L) {
4915 // Print all inner loops first
4916 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4917 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004918
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004919 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004920
Devang Patelb7211a22007-08-21 00:31:24 +00004921 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004922 L->getExitBlocks(ExitBlocks);
4923 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004924 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004925
Dan Gohman46bdfb02009-02-24 18:55:53 +00004926 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4927 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004928 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004929 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004930 }
4931
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004932 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00004933 OS << "Loop " << L->getHeader()->getName() << ": ";
4934
4935 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4936 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4937 } else {
4938 OS << "Unpredictable max backedge-taken count. ";
4939 }
4940
4941 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004942}
4943
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004944void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004945 // ScalarEvolution's implementaiton of the print method is to print
4946 // out SCEV values of all instructions that are interesting. Doing
4947 // this potentially causes it to create new SCEV objects though,
4948 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00004949 // observable from outside the class though, so casting away the
4950 // const isn't dangerous.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004951 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004952
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004953 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004954 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004955 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00004956 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00004957 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00004958 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004959 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004960
Dan Gohman0c689c52009-06-19 17:49:54 +00004961 const Loop *L = LI->getLoopFor((*I).getParent());
4962
Dan Gohman0bba49c2009-07-07 17:06:11 +00004963 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00004964 if (AtUse != SV) {
4965 OS << " --> ";
4966 AtUse->print(OS);
4967 }
4968
4969 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00004970 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00004971 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00004972 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004973 OS << "<<Unknown>>";
4974 } else {
4975 OS << *ExitValue;
4976 }
4977 }
4978
Chris Lattner53e677a2004-04-02 20:23:17 +00004979 OS << "\n";
4980 }
4981
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004982 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4983 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4984 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004985}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004986
4987void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4988 raw_os_ostream OS(o);
4989 print(OS, M);
4990}