blob: 81928c1fe6fd9ed3c792ff65b5a98cdfc58b3906 [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 Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.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"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000078#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000079#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000080#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000081#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000082#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000083#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000084#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000085#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000086#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000087#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000102 "symbolically execute a constant "
103 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000104 cl::init(100));
105
Dan Gohman844731a2008-05-13 00:00:25 +0000106static RegisterPass<ScalarEvolution>
107R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000117
Chris Lattner53e677a2004-04-02 20:23:17 +0000118SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000119
Chris Lattner53e677a2004-04-02 20:23:17 +0000120void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000121 print(dbgs());
122 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Dan Gohman70a1fe72009-05-18 15:22:39 +0000131bool SCEV::isOne() const {
132 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
133 return SC->getValue()->isOne();
134 return false;
135}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
Dan Gohman4d289bf2009-06-24 00:30:26 +0000137bool SCEV::isAllOnesValue() const {
138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
139 return SC->getValue()->isAllOnesValue();
140 return false;
141}
142
Owen Anderson753ad612009-06-22 21:57:23 +0000143SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000144 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000145
Chris Lattner53e677a2004-04-02 20:23:17 +0000146bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000147 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000148 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000149}
150
151const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000152 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000153 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000154}
155
156bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000158 return false;
159}
160
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000161bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
162 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
163 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000164}
165
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
Dan Gohman0bba49c2009-07-07 17:06:11 +0000174const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000175 FoldingSetNodeID ID;
176 ID.AddInteger(scConstant);
177 ID.AddPointer(V);
178 void *IP = 0;
179 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
180 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000181 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000182 UniqueSCEVs.InsertNode(S, IP);
183 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Dan Gohman0bba49c2009-07-07 17:06:11 +0000186const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000187 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000188}
189
Dan Gohman0bba49c2009-07-07 17:06:11 +0000190const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000191ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000192 return getConstant(
Owen Andersoneed707b2009-07-24 23:12:02 +0000193 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000194}
195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000198void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 WriteAsOperand(OS, V, false);
200}
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Dan Gohmanc050fd92009-07-13 20:50:19 +0000202SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
203 unsigned SCEVTy, const SCEV *op, const Type *ty)
204 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000205
Dan Gohman84923602009-04-21 01:25:57 +0000206bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
207 return Op->dominates(BB, DT);
208}
209
Dan Gohman6e70e312009-09-27 15:26:03 +0000210bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
211 return Op->properlyDominates(BB, DT);
212}
213
Dan Gohmanc050fd92009-07-13 20:50:19 +0000214SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
215 const SCEV *op, const Type *ty)
216 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000217 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
218 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
Chris Lattner53e677a2004-04-02 20:23:17 +0000221
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000222void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
225
Dan Gohmanc050fd92009-07-13 20:50:19 +0000226SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
227 const SCEV *op, const Type *ty)
228 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000229 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
230 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232}
233
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000234void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000235 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
Dan Gohmanc050fd92009-07-13 20:50:19 +0000238SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
239 const SCEV *op, const Type *ty)
240 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000241 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
242 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000243 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000244}
245
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000246void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000247 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000248}
249
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000250void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
254 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
255 OS << OpStr << *Operands[i];
256 OS << ")";
257}
258
Dan Gohmanecb403a2009-05-07 14:00:19 +0000259bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000260 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
261 if (!getOperand(i)->dominates(BB, DT))
262 return false;
263 }
264 return true;
265}
266
Dan Gohman6e70e312009-09-27 15:26:03 +0000267bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
268 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
269 if (!getOperand(i)->properlyDominates(BB, DT))
270 return false;
271 }
272 return true;
273}
274
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000275bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
276 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
277}
278
Dan Gohman6e70e312009-09-27 15:26:03 +0000279bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
280 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
281}
282
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000283void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000284 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000285}
286
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000287const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000288 // In most cases the types of LHS and RHS will be the same, but in some
289 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
290 // depend on the type for correctness, but handling types carefully can
291 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
292 // a pointer type than the RHS, so use the RHS' type here.
293 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000294}
295
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000296bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000297 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000298 if (!QueryLoop)
299 return false;
300
301 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000302 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000303 return false;
304
305 // This recurrence is variant w.r.t. QueryLoop if any of its operands
306 // are variant.
307 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
308 if (!getOperand(i)->isLoopInvariant(QueryLoop))
309 return false;
310
311 // Otherwise it's loop-invariant.
312 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000313}
314
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000315void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000316 OS << "{" << *Operands[0];
317 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
318 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000319 OS << "}<";
320 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
321 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322}
Chris Lattner53e677a2004-04-02 20:23:17 +0000323
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000324bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
325 // All non-instruction values are loop invariant. All instructions are loop
326 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000327 // Instructions are never considered invariant in the function body
328 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000329 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman92329c72009-12-18 01:24:09 +0000330 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331 return true;
332}
Chris Lattner53e677a2004-04-02 20:23:17 +0000333
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000334bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
335 if (Instruction *I = dyn_cast<Instruction>(getValue()))
336 return DT->dominates(I->getParent(), BB);
337 return true;
338}
339
Dan Gohman6e70e312009-09-27 15:26:03 +0000340bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
341 if (Instruction *I = dyn_cast<Instruction>(getValue()))
342 return DT->properlyDominates(I->getParent(), BB);
343 return true;
344}
345
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000346const Type *SCEVUnknown::getType() const {
347 return V->getType();
348}
Chris Lattner53e677a2004-04-02 20:23:17 +0000349
Dan Gohman0f5efe52010-01-28 02:15:55 +0000350bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
351 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
352 if (VCE->getOpcode() == Instruction::PtrToInt)
353 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000354 if (CE->getOpcode() == Instruction::GetElementPtr &&
355 CE->getOperand(0)->isNullValue() &&
356 CE->getNumOperands() == 2)
357 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
358 if (CI->isOne()) {
359 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
360 ->getElementType();
361 return true;
362 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000363
364 return false;
365}
366
367bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
368 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
369 if (VCE->getOpcode() == Instruction::PtrToInt)
370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000371 if (CE->getOpcode() == Instruction::GetElementPtr &&
372 CE->getOperand(0)->isNullValue()) {
373 const Type *Ty =
374 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
375 if (const StructType *STy = dyn_cast<StructType>(Ty))
376 if (!STy->isPacked() &&
377 CE->getNumOperands() == 3 &&
378 CE->getOperand(1)->isNullValue()) {
379 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
380 if (CI->isOne() &&
381 STy->getNumElements() == 2 &&
382 STy->getElementType(0)->isInteger(1)) {
383 AllocTy = STy->getElementType(1);
384 return true;
385 }
386 }
387 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000388
389 return false;
390}
391
Dan Gohman4f8eea82010-02-01 18:27:38 +0000392bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
393 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
394 if (VCE->getOpcode() == Instruction::PtrToInt)
395 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
396 if (CE->getOpcode() == Instruction::GetElementPtr &&
397 CE->getNumOperands() == 3 &&
398 CE->getOperand(0)->isNullValue() &&
399 CE->getOperand(1)->isNullValue()) {
400 const Type *Ty =
401 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
402 // Ignore vector types here so that ScalarEvolutionExpander doesn't
403 // emit getelementptrs that index into vectors.
404 if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
405 CTy = Ty;
406 FieldNo = CE->getOperand(2);
407 return true;
408 }
409 }
410
411 return false;
412}
413
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000414void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000415 const Type *AllocTy;
416 if (isSizeOf(AllocTy)) {
417 OS << "sizeof(" << *AllocTy << ")";
418 return;
419 }
420 if (isAlignOf(AllocTy)) {
421 OS << "alignof(" << *AllocTy << ")";
422 return;
423 }
424
Dan Gohman4f8eea82010-02-01 18:27:38 +0000425 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000426 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000427 if (isOffsetOf(CTy, FieldNo)) {
428 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000429 WriteAsOperand(OS, FieldNo, false);
430 OS << ")";
431 return;
432 }
433
434 // Otherwise just print it normally.
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000435 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000436}
437
Chris Lattner8d741b82004-06-20 06:23:15 +0000438//===----------------------------------------------------------------------===//
439// SCEV Utilities
440//===----------------------------------------------------------------------===//
441
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000442static bool CompareTypes(const Type *A, const Type *B) {
443 if (A->getTypeID() != B->getTypeID())
444 return A->getTypeID() < B->getTypeID();
445 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
446 const IntegerType *BI = cast<IntegerType>(B);
447 return AI->getBitWidth() < BI->getBitWidth();
448 }
449 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
450 const PointerType *BI = cast<PointerType>(B);
451 return CompareTypes(AI->getElementType(), BI->getElementType());
452 }
453 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
454 const ArrayType *BI = cast<ArrayType>(B);
455 if (AI->getNumElements() != BI->getNumElements())
456 return AI->getNumElements() < BI->getNumElements();
457 return CompareTypes(AI->getElementType(), BI->getElementType());
458 }
459 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
460 const VectorType *BI = cast<VectorType>(B);
461 if (AI->getNumElements() != BI->getNumElements())
462 return AI->getNumElements() < BI->getNumElements();
463 return CompareTypes(AI->getElementType(), BI->getElementType());
464 }
465 if (const StructType *AI = dyn_cast<StructType>(A)) {
466 const StructType *BI = cast<StructType>(B);
467 if (AI->getNumElements() != BI->getNumElements())
468 return AI->getNumElements() < BI->getNumElements();
469 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
470 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
471 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
472 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
473 }
474 return false;
475}
476
Chris Lattner8d741b82004-06-20 06:23:15 +0000477namespace {
478 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
479 /// than the complexity of the RHS. This comparator is used to canonicalize
480 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000481 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000482 LoopInfo *LI;
483 public:
484 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
485
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000486 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000487 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
488 if (LHS == RHS)
489 return false;
490
Dan Gohman72861302009-05-07 14:39:04 +0000491 // Primarily, sort the SCEVs by their getSCEVType().
492 if (LHS->getSCEVType() != RHS->getSCEVType())
493 return LHS->getSCEVType() < RHS->getSCEVType();
494
495 // Aside from the getSCEVType() ordering, the particular ordering
496 // isn't very important except that it's beneficial to be consistent,
497 // so that (a + b) and (b + a) don't end up as different expressions.
498
499 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
500 // not as complete as it could be.
501 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
502 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
503
Dan Gohman5be18e82009-05-19 02:15:55 +0000504 // Order pointer values after integer values. This helps SCEVExpander
505 // form GEPs.
506 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
507 return false;
508 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
509 return true;
510
Dan Gohman72861302009-05-07 14:39:04 +0000511 // Compare getValueID values.
512 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
513 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
514
515 // Sort arguments by their position.
516 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
517 const Argument *RA = cast<Argument>(RU->getValue());
518 return LA->getArgNo() < RA->getArgNo();
519 }
520
521 // For instructions, compare their loop depth, and their opcode.
522 // This is pretty loose.
523 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
524 Instruction *RV = cast<Instruction>(RU->getValue());
525
526 // Compare loop depths.
527 if (LI->getLoopDepth(LV->getParent()) !=
528 LI->getLoopDepth(RV->getParent()))
529 return LI->getLoopDepth(LV->getParent()) <
530 LI->getLoopDepth(RV->getParent());
531
532 // Compare opcodes.
533 if (LV->getOpcode() != RV->getOpcode())
534 return LV->getOpcode() < RV->getOpcode();
535
536 // Compare the number of operands.
537 if (LV->getNumOperands() != RV->getNumOperands())
538 return LV->getNumOperands() < RV->getNumOperands();
539 }
540
541 return false;
542 }
543
Dan Gohman4dfad292009-06-14 22:51:25 +0000544 // Compare constant values.
545 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
546 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000547 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
548 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000549 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
550 }
551
552 // Compare addrec loop depths.
553 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
554 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
555 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
556 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
557 }
Dan Gohman72861302009-05-07 14:39:04 +0000558
559 // Lexicographically compare n-ary expressions.
560 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
561 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
562 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
563 if (i >= RC->getNumOperands())
564 return false;
565 if (operator()(LC->getOperand(i), RC->getOperand(i)))
566 return true;
567 if (operator()(RC->getOperand(i), LC->getOperand(i)))
568 return false;
569 }
570 return LC->getNumOperands() < RC->getNumOperands();
571 }
572
Dan Gohmana6b35e22009-05-07 19:23:21 +0000573 // Lexicographically compare udiv expressions.
574 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
575 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
576 if (operator()(LC->getLHS(), RC->getLHS()))
577 return true;
578 if (operator()(RC->getLHS(), LC->getLHS()))
579 return false;
580 if (operator()(LC->getRHS(), RC->getRHS()))
581 return true;
582 if (operator()(RC->getRHS(), LC->getRHS()))
583 return false;
584 return false;
585 }
586
Dan Gohman72861302009-05-07 14:39:04 +0000587 // Compare cast expressions by operand.
588 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
589 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
590 return operator()(LC->getOperand(), RC->getOperand());
591 }
592
Torok Edwinc23197a2009-07-14 16:55:14 +0000593 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000594 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000595 }
596 };
597}
598
599/// GroupByComplexity - Given a list of SCEV objects, order them by their
600/// complexity, and group objects of the same complexity together by value.
601/// When this routine is finished, we know that any duplicates in the vector are
602/// consecutive and that complexity is monotonically increasing.
603///
604/// Note that we go take special precautions to ensure that we get determinstic
605/// results from this routine. In other words, we don't want the results of
606/// this to depend on where the addresses of various SCEV objects happened to
607/// land in memory.
608///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000609static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000610 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000611 if (Ops.size() < 2) return; // Noop
612 if (Ops.size() == 2) {
613 // This is the common case, which also happens to be trivially simple.
614 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000615 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000616 std::swap(Ops[0], Ops[1]);
617 return;
618 }
619
620 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000621 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000622
623 // Now that we are sorted by complexity, group elements of the same
624 // complexity. Note that this is, at worst, N^2, but the vector is likely to
625 // be extremely short in practice. Note that we take this approach because we
626 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000627 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000628 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000629 unsigned Complexity = S->getSCEVType();
630
631 // If there are any objects of the same complexity and same value as this
632 // one, group them.
633 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
634 if (Ops[j] == S) { // Found a duplicate.
635 // Move it to immediately after i'th element.
636 std::swap(Ops[i+1], Ops[j]);
637 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000638 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000639 }
640 }
641 }
642}
643
Chris Lattner53e677a2004-04-02 20:23:17 +0000644
Chris Lattner53e677a2004-04-02 20:23:17 +0000645
646//===----------------------------------------------------------------------===//
647// Simple SCEV method implementations
648//===----------------------------------------------------------------------===//
649
Eli Friedmanb42a6262008-08-04 23:49:06 +0000650/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000651/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000652static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000653 ScalarEvolution &SE,
654 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000655 // Handle the simplest case efficiently.
656 if (K == 1)
657 return SE.getTruncateOrZeroExtend(It, ResultTy);
658
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000659 // We are using the following formula for BC(It, K):
660 //
661 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
662 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000663 // Suppose, W is the bitwidth of the return value. We must be prepared for
664 // overflow. Hence, we must assure that the result of our computation is
665 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
666 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000667 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000668 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000669 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000670 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
671 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000672 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000673 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000674 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000675 // This formula is trivially equivalent to the previous formula. However,
676 // this formula can be implemented much more efficiently. The trick is that
677 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
678 // arithmetic. To do exact division in modular arithmetic, all we have
679 // to do is multiply by the inverse. Therefore, this step can be done at
680 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000681 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000682 // The next issue is how to safely do the division by 2^T. The way this
683 // is done is by doing the multiplication step at a width of at least W + T
684 // bits. This way, the bottom W+T bits of the product are accurate. Then,
685 // when we perform the division by 2^T (which is equivalent to a right shift
686 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
687 // truncated out after the division by 2^T.
688 //
689 // In comparison to just directly using the first formula, this technique
690 // is much more efficient; using the first formula requires W * K bits,
691 // but this formula less than W + K bits. Also, the first formula requires
692 // a division step, whereas this formula only requires multiplies and shifts.
693 //
694 // It doesn't matter whether the subtraction step is done in the calculation
695 // width or the input iteration count's width; if the subtraction overflows,
696 // the result must be zero anyway. We prefer here to do it in the width of
697 // the induction variable because it helps a lot for certain cases; CodeGen
698 // isn't smart enough to ignore the overflow, which leads to much less
699 // efficient code if the width of the subtraction is wider than the native
700 // register width.
701 //
702 // (It's possible to not widen at all by pulling out factors of 2 before
703 // the multiplication; for example, K=2 can be calculated as
704 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
705 // extra arithmetic, so it's not an obvious win, and it gets
706 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000707
Eli Friedmanb42a6262008-08-04 23:49:06 +0000708 // Protection from insane SCEVs; this bound is conservative,
709 // but it probably doesn't matter.
710 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000711 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000712
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000713 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000714
Eli Friedmanb42a6262008-08-04 23:49:06 +0000715 // Calculate K! / 2^T and T; we divide out the factors of two before
716 // multiplying for calculating K! / 2^T to avoid overflow.
717 // Other overflow doesn't matter because we only care about the bottom
718 // W bits of the result.
719 APInt OddFactorial(W, 1);
720 unsigned T = 1;
721 for (unsigned i = 3; i <= K; ++i) {
722 APInt Mult(W, i);
723 unsigned TwoFactors = Mult.countTrailingZeros();
724 T += TwoFactors;
725 Mult = Mult.lshr(TwoFactors);
726 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000727 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000728
Eli Friedmanb42a6262008-08-04 23:49:06 +0000729 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000730 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000731
732 // Calcuate 2^T, at width T+W.
733 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
734
735 // Calculate the multiplicative inverse of K! / 2^T;
736 // this multiplication factor will perform the exact division by
737 // K! / 2^T.
738 APInt Mod = APInt::getSignedMinValue(W+1);
739 APInt MultiplyFactor = OddFactorial.zext(W+1);
740 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
741 MultiplyFactor = MultiplyFactor.trunc(W);
742
743 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000744 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
745 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000746 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000747 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000748 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000749 Dividend = SE.getMulExpr(Dividend,
750 SE.getTruncateOrZeroExtend(S, CalculationTy));
751 }
752
753 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000754 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000755
756 // Truncate the result, and divide by K! / 2^T.
757
758 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
759 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000760}
761
Chris Lattner53e677a2004-04-02 20:23:17 +0000762/// evaluateAtIteration - Return the value of this chain of recurrences at
763/// the specified iteration number. We can evaluate this recurrence by
764/// multiplying each element in the chain by the binomial coefficient
765/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
766///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000767/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000768///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000769/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000770///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000771const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000772 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000773 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000774 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000775 // The computation is correct in the face of overflow provided that the
776 // multiplication is performed _after_ the evaluation of the binomial
777 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000778 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000779 if (isa<SCEVCouldNotCompute>(Coeff))
780 return Coeff;
781
782 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000783 }
784 return Result;
785}
786
Chris Lattner53e677a2004-04-02 20:23:17 +0000787//===----------------------------------------------------------------------===//
788// SCEV Expression folder implementations
789//===----------------------------------------------------------------------===//
790
Dan Gohman0bba49c2009-07-07 17:06:11 +0000791const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000792 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000793 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000794 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000795 assert(isSCEVable(Ty) &&
796 "This is not a conversion to a SCEVable type!");
797 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000798
Dan Gohmanc050fd92009-07-13 20:50:19 +0000799 FoldingSetNodeID ID;
800 ID.AddInteger(scTruncate);
801 ID.AddPointer(Op);
802 ID.AddPointer(Ty);
803 void *IP = 0;
804 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
805
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000806 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000807 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000808 return getConstant(
809 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000810
Dan Gohman20900ca2009-04-22 16:20:48 +0000811 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000812 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000813 return getTruncateExpr(ST->getOperand(), Ty);
814
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000815 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000816 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000817 return getTruncateOrSignExtend(SS->getOperand(), Ty);
818
819 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000820 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000821 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
822
Dan Gohman6864db62009-06-18 16:24:47 +0000823 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000824 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000825 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000826 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000827 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
828 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000829 }
830
Dan Gohmanc050fd92009-07-13 20:50:19 +0000831 // The cast wasn't folded; create an explicit cast node.
832 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000833 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
834 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000835 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000836 UniqueSCEVs.InsertNode(S, IP);
837 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000838}
839
Dan Gohman0bba49c2009-07-07 17:06:11 +0000840const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000841 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000842 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000843 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000844 assert(isSCEVable(Ty) &&
845 "This is not a conversion to a SCEVable type!");
846 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000847
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000848 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000849 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000850 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000851 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
852 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000853 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000854 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000855
Dan Gohman20900ca2009-04-22 16:20:48 +0000856 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000857 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000858 return getZeroExtendExpr(SZ->getOperand(), Ty);
859
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000860 // Before doing any expensive analysis, check to see if we've already
861 // computed a SCEV for this Op and Ty.
862 FoldingSetNodeID ID;
863 ID.AddInteger(scZeroExtend);
864 ID.AddPointer(Op);
865 ID.AddPointer(Ty);
866 void *IP = 0;
867 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
868
Dan Gohman01ecca22009-04-27 20:16:15 +0000869 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000870 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000871 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000872 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000873 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000874 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000875 const SCEV *Start = AR->getStart();
876 const SCEV *Step = AR->getStepRecurrence(*this);
877 unsigned BitWidth = getTypeSizeInBits(AR->getType());
878 const Loop *L = AR->getLoop();
879
Dan Gohmaneb490a72009-07-25 01:22:26 +0000880 // If we have special knowledge that this addrec won't overflow,
881 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000882 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000883 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
884 getZeroExtendExpr(Step, Ty),
885 L);
886
Dan Gohman01ecca22009-04-27 20:16:15 +0000887 // Check whether the backedge-taken count is SCEVCouldNotCompute.
888 // Note that this serves two purposes: It filters out loops that are
889 // simply not analyzable, and it covers the case where this code is
890 // being called from within backedge-taken count analysis, such that
891 // attempting to ask for the backedge-taken count would likely result
892 // in infinite recursion. In the later case, the analysis code will
893 // cope with a conservative value, and it will take care to purge
894 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000895 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000896 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000897 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000898 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000899
900 // Check whether the backedge-taken count can be losslessly casted to
901 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000902 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000903 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000904 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000905 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
906 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000907 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000908 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000909 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000910 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000911 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000912 const SCEV *Add = getAddExpr(Start, ZMul);
913 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000914 getAddExpr(getZeroExtendExpr(Start, WideTy),
915 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
916 getZeroExtendExpr(Step, WideTy)));
917 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000918 // Return the expression with the addrec on the outside.
919 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
920 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000921 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000922
923 // Similar to above, only this time treat the step value as signed.
924 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000925 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000926 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000927 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000928 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000929 OperandExtendedAdd =
930 getAddExpr(getZeroExtendExpr(Start, WideTy),
931 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
932 getSignExtendExpr(Step, WideTy)));
933 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000934 // Return the expression with the addrec on the outside.
935 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
936 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000937 L);
938 }
939
940 // If the backedge is guarded by a comparison with the pre-inc value
941 // the addrec is safe. Also, if the entry is guarded by a comparison
942 // with the start value and the backedge is guarded by a comparison
943 // with the post-inc value, the addrec is safe.
944 if (isKnownPositive(Step)) {
945 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
946 getUnsignedRange(Step).getUnsignedMax());
947 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
948 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
949 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
950 AR->getPostIncExpr(*this), N)))
951 // Return the expression with the addrec on the outside.
952 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
953 getZeroExtendExpr(Step, Ty),
954 L);
955 } else if (isKnownNegative(Step)) {
956 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
957 getSignedRange(Step).getSignedMin());
958 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
959 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
960 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
961 AR->getPostIncExpr(*this), N)))
962 // Return the expression with the addrec on the outside.
963 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
964 getSignExtendExpr(Step, Ty),
965 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000966 }
967 }
968 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000969
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000970 // The cast wasn't folded; create an explicit cast node.
971 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000972 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
973 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000974 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000975 UniqueSCEVs.InsertNode(S, IP);
976 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000977}
978
Dan Gohman0bba49c2009-07-07 17:06:11 +0000979const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000980 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000981 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000982 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000983 assert(isSCEVable(Ty) &&
984 "This is not a conversion to a SCEVable type!");
985 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000986
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000987 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000988 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000989 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000990 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
991 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000992 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000993 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000994
Dan Gohman20900ca2009-04-22 16:20:48 +0000995 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000996 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000997 return getSignExtendExpr(SS->getOperand(), Ty);
998
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000999 // Before doing any expensive analysis, check to see if we've already
1000 // computed a SCEV for this Op and Ty.
1001 FoldingSetNodeID ID;
1002 ID.AddInteger(scSignExtend);
1003 ID.AddPointer(Op);
1004 ID.AddPointer(Ty);
1005 void *IP = 0;
1006 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1007
Dan Gohman01ecca22009-04-27 20:16:15 +00001008 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001009 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001010 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001011 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001012 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001013 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001014 const SCEV *Start = AR->getStart();
1015 const SCEV *Step = AR->getStepRecurrence(*this);
1016 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1017 const Loop *L = AR->getLoop();
1018
Dan Gohmaneb490a72009-07-25 01:22:26 +00001019 // If we have special knowledge that this addrec won't overflow,
1020 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001021 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001022 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1023 getSignExtendExpr(Step, Ty),
1024 L);
1025
Dan Gohman01ecca22009-04-27 20:16:15 +00001026 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1027 // Note that this serves two purposes: It filters out loops that are
1028 // simply not analyzable, and it covers the case where this code is
1029 // being called from within backedge-taken count analysis, such that
1030 // attempting to ask for the backedge-taken count would likely result
1031 // in infinite recursion. In the later case, the analysis code will
1032 // cope with a conservative value, and it will take care to purge
1033 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001034 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001035 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001036 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001037 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001038
1039 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001040 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001041 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001042 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001043 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001044 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1045 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001046 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001047 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001048 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +00001049 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +00001050 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001051 const SCEV *Add = getAddExpr(Start, SMul);
1052 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001053 getAddExpr(getSignExtendExpr(Start, WideTy),
1054 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1055 getSignExtendExpr(Step, WideTy)));
1056 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001057 // Return the expression with the addrec on the outside.
1058 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1059 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001060 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001061
1062 // Similar to above, only this time treat the step value as unsigned.
1063 // This covers loops that count up with an unsigned step.
1064 const SCEV *UMul =
1065 getMulExpr(CastedMaxBECount,
1066 getTruncateOrZeroExtend(Step, Start->getType()));
1067 Add = getAddExpr(Start, UMul);
1068 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001069 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001070 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1071 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001072 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001073 // Return the expression with the addrec on the outside.
1074 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1075 getZeroExtendExpr(Step, Ty),
1076 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001077 }
1078
1079 // If the backedge is guarded by a comparison with the pre-inc value
1080 // the addrec is safe. Also, if the entry is guarded by a comparison
1081 // with the start value and the backedge is guarded by a comparison
1082 // with the post-inc value, the addrec is safe.
1083 if (isKnownPositive(Step)) {
1084 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1085 getSignedRange(Step).getSignedMax());
1086 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1087 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1088 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1089 AR->getPostIncExpr(*this), N)))
1090 // Return the expression with the addrec on the outside.
1091 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1092 getSignExtendExpr(Step, Ty),
1093 L);
1094 } else if (isKnownNegative(Step)) {
1095 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1096 getSignedRange(Step).getSignedMin());
1097 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1098 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1099 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1100 AR->getPostIncExpr(*this), N)))
1101 // Return the expression with the addrec on the outside.
1102 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1103 getSignExtendExpr(Step, Ty),
1104 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001105 }
1106 }
1107 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001108
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001109 // The cast wasn't folded; create an explicit cast node.
1110 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001111 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1112 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001113 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001114 UniqueSCEVs.InsertNode(S, IP);
1115 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001116}
1117
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001118/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1119/// unspecified bits out to the given type.
1120///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001121const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001122 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001123 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1124 "This is not an extending conversion!");
1125 assert(isSCEVable(Ty) &&
1126 "This is not a conversion to a SCEVable type!");
1127 Ty = getEffectiveSCEVType(Ty);
1128
1129 // Sign-extend negative constants.
1130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1131 if (SC->getValue()->getValue().isNegative())
1132 return getSignExtendExpr(Op, Ty);
1133
1134 // Peel off a truncate cast.
1135 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001136 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001137 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1138 return getAnyExtendExpr(NewOp, Ty);
1139 return getTruncateOrNoop(NewOp, Ty);
1140 }
1141
1142 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001143 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001144 if (!isa<SCEVZeroExtendExpr>(ZExt))
1145 return ZExt;
1146
1147 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001148 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001149 if (!isa<SCEVSignExtendExpr>(SExt))
1150 return SExt;
1151
Dan Gohmana10756e2010-01-21 02:09:26 +00001152 // Force the cast to be folded into the operands of an addrec.
1153 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1154 SmallVector<const SCEV *, 4> Ops;
1155 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1156 I != E; ++I)
1157 Ops.push_back(getAnyExtendExpr(*I, Ty));
1158 return getAddRecExpr(Ops, AR->getLoop());
1159 }
1160
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001161 // If the expression is obviously signed, use the sext cast value.
1162 if (isa<SCEVSMaxExpr>(Op))
1163 return SExt;
1164
1165 // Absent any other information, use the zext cast value.
1166 return ZExt;
1167}
1168
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001169/// CollectAddOperandsWithScales - Process the given Ops list, which is
1170/// a list of operands to be added under the given scale, update the given
1171/// map. This is a helper function for getAddRecExpr. As an example of
1172/// what it does, given a sequence of operands that would form an add
1173/// expression like this:
1174///
1175/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1176///
1177/// where A and B are constants, update the map with these values:
1178///
1179/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1180///
1181/// and add 13 + A*B*29 to AccumulatedConstant.
1182/// This will allow getAddRecExpr to produce this:
1183///
1184/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1185///
1186/// This form often exposes folding opportunities that are hidden in
1187/// the original operand list.
1188///
1189/// Return true iff it appears that any interesting folding opportunities
1190/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1191/// the common case where no interesting opportunities are present, and
1192/// is also used as a check to avoid infinite recursion.
1193///
1194static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001195CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1196 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001197 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001198 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001199 const APInt &Scale,
1200 ScalarEvolution &SE) {
1201 bool Interesting = false;
1202
1203 // Iterate over the add operands.
1204 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1205 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1206 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1207 APInt NewScale =
1208 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1209 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1210 // A multiplication of a constant with another add; recurse.
1211 Interesting |=
1212 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1213 cast<SCEVAddExpr>(Mul->getOperand(1))
1214 ->getOperands(),
1215 NewScale, SE);
1216 } else {
1217 // A multiplication of a constant with some other value. Update
1218 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001219 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1220 const SCEV *Key = SE.getMulExpr(MulOps);
1221 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001222 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001223 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001224 NewOps.push_back(Pair.first->first);
1225 } else {
1226 Pair.first->second += NewScale;
1227 // The map already had an entry for this value, which may indicate
1228 // a folding opportunity.
1229 Interesting = true;
1230 }
1231 }
1232 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1233 // Pull a buried constant out to the outside.
1234 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1235 Interesting = true;
1236 AccumulatedConstant += Scale * C->getValue()->getValue();
1237 } else {
1238 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001239 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001240 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001241 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001242 NewOps.push_back(Pair.first->first);
1243 } else {
1244 Pair.first->second += Scale;
1245 // The map already had an entry for this value, which may indicate
1246 // a folding opportunity.
1247 Interesting = true;
1248 }
1249 }
1250 }
1251
1252 return Interesting;
1253}
1254
1255namespace {
1256 struct APIntCompare {
1257 bool operator()(const APInt &LHS, const APInt &RHS) const {
1258 return LHS.ult(RHS);
1259 }
1260 };
1261}
1262
Dan Gohman6c0866c2009-05-24 23:45:28 +00001263/// getAddExpr - Get a canonical add expression, or something simpler if
1264/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001265const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1266 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001267 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001268 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001269#ifndef NDEBUG
1270 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1271 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1272 getEffectiveSCEVType(Ops[0]->getType()) &&
1273 "SCEVAddExpr operand types don't match!");
1274#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001275
Dan Gohmana10756e2010-01-21 02:09:26 +00001276 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1277 if (!HasNUW && HasNSW) {
1278 bool All = true;
1279 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1280 if (!isKnownNonNegative(Ops[i])) {
1281 All = false;
1282 break;
1283 }
1284 if (All) HasNUW = true;
1285 }
1286
Chris Lattner53e677a2004-04-02 20:23:17 +00001287 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001288 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001289
1290 // If there are any constants, fold them together.
1291 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001292 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001293 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001294 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001295 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001296 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001297 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1298 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001299 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001300 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001301 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001302 }
1303
1304 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001305 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001306 Ops.erase(Ops.begin());
1307 --Idx;
1308 }
1309 }
1310
Chris Lattner627018b2004-04-07 16:16:11 +00001311 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001312
Chris Lattner53e677a2004-04-02 20:23:17 +00001313 // Okay, check to see if the same value occurs in the operand list twice. If
1314 // so, merge them together into an multiply expression. Since we sorted the
1315 // list, these values are required to be adjacent.
1316 const Type *Ty = Ops[0]->getType();
1317 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1318 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1319 // Found a match, merge the two values into a multiply, and add any
1320 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001321 const SCEV *Two = getIntegerSCEV(2, Ty);
1322 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001323 if (Ops.size() == 2)
1324 return Mul;
1325 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1326 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001327 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001328 }
1329
Dan Gohman728c7f32009-05-08 21:03:19 +00001330 // Check for truncates. If all the operands are truncated from the same
1331 // type, see if factoring out the truncate would permit the result to be
1332 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1333 // if the contents of the resulting outer trunc fold to something simple.
1334 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1335 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1336 const Type *DstType = Trunc->getType();
1337 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001338 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001339 bool Ok = true;
1340 // Check all the operands to see if they can be represented in the
1341 // source type of the truncate.
1342 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1343 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1344 if (T->getOperand()->getType() != SrcType) {
1345 Ok = false;
1346 break;
1347 }
1348 LargeOps.push_back(T->getOperand());
1349 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1350 // This could be either sign or zero extension, but sign extension
1351 // is much more likely to be foldable here.
1352 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1353 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001354 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001355 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1356 if (const SCEVTruncateExpr *T =
1357 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1358 if (T->getOperand()->getType() != SrcType) {
1359 Ok = false;
1360 break;
1361 }
1362 LargeMulOps.push_back(T->getOperand());
1363 } else if (const SCEVConstant *C =
1364 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1365 // This could be either sign or zero extension, but sign extension
1366 // is much more likely to be foldable here.
1367 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1368 } else {
1369 Ok = false;
1370 break;
1371 }
1372 }
1373 if (Ok)
1374 LargeOps.push_back(getMulExpr(LargeMulOps));
1375 } else {
1376 Ok = false;
1377 break;
1378 }
1379 }
1380 if (Ok) {
1381 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001382 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001383 // If it folds to something simple, use it. Otherwise, don't.
1384 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1385 return getTruncateExpr(Fold, DstType);
1386 }
1387 }
1388
1389 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001390 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1391 ++Idx;
1392
1393 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001394 if (Idx < Ops.size()) {
1395 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001396 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001397 // If we have an add, expand the add operands onto the end of the operands
1398 // list.
1399 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1400 Ops.erase(Ops.begin()+Idx);
1401 DeletedAdd = true;
1402 }
1403
1404 // If we deleted at least one add, we added operands to the end of the list,
1405 // and they are not necessarily sorted. Recurse to resort and resimplify
1406 // any operands we just aquired.
1407 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001408 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001409 }
1410
1411 // Skip over the add expression until we get to a multiply.
1412 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1413 ++Idx;
1414
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001415 // Check to see if there are any folding opportunities present with
1416 // operands multiplied by constant values.
1417 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1418 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001419 DenseMap<const SCEV *, APInt> M;
1420 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001421 APInt AccumulatedConstant(BitWidth, 0);
1422 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1423 Ops, APInt(BitWidth, 1), *this)) {
1424 // Some interesting folding opportunity is present, so its worthwhile to
1425 // re-generate the operands list. Group the operands by constant scale,
1426 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001427 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1428 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001429 E = NewOps.end(); I != E; ++I)
1430 MulOpLists[M.find(*I)->second].push_back(*I);
1431 // Re-generate the operands list.
1432 Ops.clear();
1433 if (AccumulatedConstant != 0)
1434 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001435 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1436 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001437 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001438 Ops.push_back(getMulExpr(getConstant(I->first),
1439 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001440 if (Ops.empty())
1441 return getIntegerSCEV(0, Ty);
1442 if (Ops.size() == 1)
1443 return Ops[0];
1444 return getAddExpr(Ops);
1445 }
1446 }
1447
Chris Lattner53e677a2004-04-02 20:23:17 +00001448 // If we are adding something to a multiply expression, make sure the
1449 // something is not already an operand of the multiply. If so, merge it into
1450 // the multiply.
1451 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001452 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001453 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001454 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001455 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001456 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001457 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001458 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001459 if (Mul->getNumOperands() != 2) {
1460 // If the multiply has more than two operands, we must get the
1461 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001462 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001463 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001464 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001466 const SCEV *One = getIntegerSCEV(1, Ty);
1467 const SCEV *AddOne = getAddExpr(InnerMul, One);
1468 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001469 if (Ops.size() == 2) return OuterMul;
1470 if (AddOp < Idx) {
1471 Ops.erase(Ops.begin()+AddOp);
1472 Ops.erase(Ops.begin()+Idx-1);
1473 } else {
1474 Ops.erase(Ops.begin()+Idx);
1475 Ops.erase(Ops.begin()+AddOp-1);
1476 }
1477 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001478 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001479 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001480
Chris Lattner53e677a2004-04-02 20:23:17 +00001481 // Check this multiply against other multiplies being added together.
1482 for (unsigned OtherMulIdx = Idx+1;
1483 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1484 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001485 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001486 // If MulOp occurs in OtherMul, we can fold the two multiplies
1487 // together.
1488 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1489 OMulOp != e; ++OMulOp)
1490 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1491 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001492 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001494 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1495 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001497 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001498 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001499 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001500 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001501 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1502 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001503 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001504 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001505 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001506 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1507 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 if (Ops.size() == 2) return OuterMul;
1509 Ops.erase(Ops.begin()+Idx);
1510 Ops.erase(Ops.begin()+OtherMulIdx-1);
1511 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001512 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001513 }
1514 }
1515 }
1516 }
1517
1518 // If there are any add recurrences in the operands list, see if any other
1519 // added values are loop invariant. If so, we can fold them into the
1520 // recurrence.
1521 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1522 ++Idx;
1523
1524 // Scan over all recurrences, trying to fold loop invariants into them.
1525 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1526 // Scan all of the other operands to this add and add them to the vector if
1527 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001528 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001529 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001530 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1531 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1532 LIOps.push_back(Ops[i]);
1533 Ops.erase(Ops.begin()+i);
1534 --i; --e;
1535 }
1536
1537 // If we found some loop invariants, fold them into the recurrence.
1538 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001539 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001540 LIOps.push_back(AddRec->getStart());
1541
Dan Gohman0bba49c2009-07-07 17:06:11 +00001542 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001543 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001544 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001545
Dan Gohman355b4f32009-12-19 01:46:34 +00001546 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001547 // is not associative so this isn't necessarily safe.
Dan Gohman3a5d4092009-12-18 03:57:04 +00001548 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohman59de33e2009-12-18 18:45:31 +00001549
Chris Lattner53e677a2004-04-02 20:23:17 +00001550 // If all of the other operands were loop invariant, we are done.
1551 if (Ops.size() == 1) return NewRec;
1552
1553 // Otherwise, add the folded AddRec by the non-liv parts.
1554 for (unsigned i = 0;; ++i)
1555 if (Ops[i] == AddRec) {
1556 Ops[i] = NewRec;
1557 break;
1558 }
Dan Gohman246b2562007-10-22 18:31:58 +00001559 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001560 }
1561
1562 // Okay, if there weren't any loop invariants to be folded, check to see if
1563 // there are multiple AddRec's with the same loop induction variable being
1564 // added together. If so, we can fold them.
1565 for (unsigned OtherIdx = Idx+1;
1566 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1567 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001568 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001569 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1570 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001571 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1572 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001573 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1574 if (i >= NewOps.size()) {
1575 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1576 OtherAddRec->op_end());
1577 break;
1578 }
Dan Gohman246b2562007-10-22 18:31:58 +00001579 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001581 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001582
1583 if (Ops.size() == 2) return NewAddRec;
1584
1585 Ops.erase(Ops.begin()+Idx);
1586 Ops.erase(Ops.begin()+OtherIdx-1);
1587 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001588 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 }
1590 }
1591
1592 // Otherwise couldn't fold anything into this recurrence. Move onto the
1593 // next one.
1594 }
1595
1596 // Okay, it looks like we really DO need an add expr. Check to see if we
1597 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001598 FoldingSetNodeID ID;
1599 ID.AddInteger(scAddExpr);
1600 ID.AddInteger(Ops.size());
1601 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1602 ID.AddPointer(Ops[i]);
1603 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001604 SCEVAddExpr *S =
1605 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1606 if (!S) {
1607 S = SCEVAllocator.Allocate<SCEVAddExpr>();
1608 new (S) SCEVAddExpr(ID, Ops);
1609 UniqueSCEVs.InsertNode(S, IP);
1610 }
Dan Gohman3645b012009-10-09 00:10:36 +00001611 if (HasNUW) S->setHasNoUnsignedWrap(true);
1612 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001613 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001614}
1615
Dan Gohman6c0866c2009-05-24 23:45:28 +00001616/// getMulExpr - Get a canonical multiply expression, or something simpler if
1617/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001618const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1619 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001621 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001622#ifndef NDEBUG
1623 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1624 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1625 getEffectiveSCEVType(Ops[0]->getType()) &&
1626 "SCEVMulExpr operand types don't match!");
1627#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001628
Dan Gohmana10756e2010-01-21 02:09:26 +00001629 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1630 if (!HasNUW && HasNSW) {
1631 bool All = true;
1632 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1633 if (!isKnownNonNegative(Ops[i])) {
1634 All = false;
1635 break;
1636 }
1637 if (All) HasNUW = true;
1638 }
1639
Chris Lattner53e677a2004-04-02 20:23:17 +00001640 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001641 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001642
1643 // If there are any constants, fold them together.
1644 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001645 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001646
1647 // C1*(C2+V) -> C1*C2 + C1*V
1648 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001649 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001650 if (Add->getNumOperands() == 2 &&
1651 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001652 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1653 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001654
Chris Lattner53e677a2004-04-02 20:23:17 +00001655 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001656 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001657 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001658 ConstantInt *Fold = ConstantInt::get(getContext(),
1659 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001660 RHSC->getValue()->getValue());
1661 Ops[0] = getConstant(Fold);
1662 Ops.erase(Ops.begin()+1); // Erase the folded element
1663 if (Ops.size() == 1) return Ops[0];
1664 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001665 }
1666
1667 // If we are left with a constant one being multiplied, strip it off.
1668 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1669 Ops.erase(Ops.begin());
1670 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001671 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001672 // If we have a multiply of zero, it will always be zero.
1673 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001674 } else if (Ops[0]->isAllOnesValue()) {
1675 // If we have a mul by -1 of an add, try distributing the -1 among the
1676 // add operands.
1677 if (Ops.size() == 2)
1678 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1679 SmallVector<const SCEV *, 4> NewOps;
1680 bool AnyFolded = false;
1681 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1682 I != E; ++I) {
1683 const SCEV *Mul = getMulExpr(Ops[0], *I);
1684 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1685 NewOps.push_back(Mul);
1686 }
1687 if (AnyFolded)
1688 return getAddExpr(NewOps);
1689 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001690 }
1691 }
1692
1693 // Skip over the add expression until we get to a multiply.
1694 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1695 ++Idx;
1696
1697 if (Ops.size() == 1)
1698 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001699
Chris Lattner53e677a2004-04-02 20:23:17 +00001700 // If there are mul operands inline them all into this expression.
1701 if (Idx < Ops.size()) {
1702 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001703 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001704 // If we have an mul, expand the mul operands onto the end of the operands
1705 // list.
1706 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1707 Ops.erase(Ops.begin()+Idx);
1708 DeletedMul = true;
1709 }
1710
1711 // If we deleted at least one mul, we added operands to the end of the list,
1712 // and they are not necessarily sorted. Recurse to resort and resimplify
1713 // any operands we just aquired.
1714 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001715 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001716 }
1717
1718 // If there are any add recurrences in the operands list, see if any other
1719 // added values are loop invariant. If so, we can fold them into the
1720 // recurrence.
1721 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1722 ++Idx;
1723
1724 // Scan over all recurrences, trying to fold loop invariants into them.
1725 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1726 // Scan all of the other operands to this mul and add them to the vector if
1727 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001728 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001729 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001730 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1731 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1732 LIOps.push_back(Ops[i]);
1733 Ops.erase(Ops.begin()+i);
1734 --i; --e;
1735 }
1736
1737 // If we found some loop invariants, fold them into the recurrence.
1738 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001739 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001740 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001741 NewOps.reserve(AddRec->getNumOperands());
1742 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001743 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001744 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001745 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001746 } else {
1747 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001748 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001749 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001750 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001751 }
1752 }
1753
Dan Gohman355b4f32009-12-19 01:46:34 +00001754 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001755 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001756 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1757 HasNUW && AddRec->hasNoUnsignedWrap(),
1758 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001759
1760 // If all of the other operands were loop invariant, we are done.
1761 if (Ops.size() == 1) return NewRec;
1762
1763 // Otherwise, multiply the folded AddRec by the non-liv parts.
1764 for (unsigned i = 0;; ++i)
1765 if (Ops[i] == AddRec) {
1766 Ops[i] = NewRec;
1767 break;
1768 }
Dan Gohman246b2562007-10-22 18:31:58 +00001769 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001770 }
1771
1772 // Okay, if there weren't any loop invariants to be folded, check to see if
1773 // there are multiple AddRec's with the same loop induction variable being
1774 // multiplied together. If so, we can fold them.
1775 for (unsigned OtherIdx = Idx+1;
1776 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1777 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001778 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001779 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1780 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001781 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001782 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001783 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001784 const SCEV *B = F->getStepRecurrence(*this);
1785 const SCEV *D = G->getStepRecurrence(*this);
1786 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001787 getMulExpr(G, B),
1788 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001789 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001790 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001791 if (Ops.size() == 2) return NewAddRec;
1792
1793 Ops.erase(Ops.begin()+Idx);
1794 Ops.erase(Ops.begin()+OtherIdx-1);
1795 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001796 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001797 }
1798 }
1799
1800 // Otherwise couldn't fold anything into this recurrence. Move onto the
1801 // next one.
1802 }
1803
1804 // Okay, it looks like we really DO need an mul expr. Check to see if we
1805 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001806 FoldingSetNodeID ID;
1807 ID.AddInteger(scMulExpr);
1808 ID.AddInteger(Ops.size());
1809 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1810 ID.AddPointer(Ops[i]);
1811 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001812 SCEVMulExpr *S =
1813 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1814 if (!S) {
1815 S = SCEVAllocator.Allocate<SCEVMulExpr>();
1816 new (S) SCEVMulExpr(ID, Ops);
1817 UniqueSCEVs.InsertNode(S, IP);
1818 }
Dan Gohman3645b012009-10-09 00:10:36 +00001819 if (HasNUW) S->setHasNoUnsignedWrap(true);
1820 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001821 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001822}
1823
Andreas Bolka8a11c982009-08-07 22:55:26 +00001824/// getUDivExpr - Get a canonical unsigned division expression, or something
1825/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001826const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1827 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001828 assert(getEffectiveSCEVType(LHS->getType()) ==
1829 getEffectiveSCEVType(RHS->getType()) &&
1830 "SCEVUDivExpr operand types don't match!");
1831
Dan Gohman622ed672009-05-04 22:02:23 +00001832 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001833 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001834 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001835 if (RHSC->isZero())
1836 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001837
Dan Gohman185cf032009-05-08 20:18:49 +00001838 // Determine if the division can be folded into the operands of
1839 // its operands.
1840 // TODO: Generalize this to non-constants by using known-bits information.
1841 const Type *Ty = LHS->getType();
1842 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1843 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1844 // For non-power-of-two values, effectively round the value up to the
1845 // nearest power of two.
1846 if (!RHSC->getValue()->getValue().isPowerOf2())
1847 ++MaxShiftAmt;
1848 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001849 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001850 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1851 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1852 if (const SCEVConstant *Step =
1853 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1854 if (!Step->getValue()->getValue()
1855 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001856 getZeroExtendExpr(AR, ExtTy) ==
1857 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1858 getZeroExtendExpr(Step, ExtTy),
1859 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001860 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001861 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1862 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1863 return getAddRecExpr(Operands, AR->getLoop());
1864 }
1865 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001866 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001867 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001868 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1869 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1870 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001871 // Find an operand that's safely divisible.
1872 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001873 const SCEV *Op = M->getOperand(i);
1874 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001875 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001876 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1877 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001878 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001879 Operands[i] = Div;
1880 return getMulExpr(Operands);
1881 }
1882 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001883 }
Dan Gohman185cf032009-05-08 20:18:49 +00001884 // (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 +00001885 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001886 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001887 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1888 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1889 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1890 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001891 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001892 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001893 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1894 break;
1895 Operands.push_back(Op);
1896 }
1897 if (Operands.size() == A->getNumOperands())
1898 return getAddExpr(Operands);
1899 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001900 }
Dan Gohman185cf032009-05-08 20:18:49 +00001901
1902 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001903 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001904 Constant *LHSCV = LHSC->getValue();
1905 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001906 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001907 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001908 }
1909 }
1910
Dan Gohman1c343752009-06-27 21:21:31 +00001911 FoldingSetNodeID ID;
1912 ID.AddInteger(scUDivExpr);
1913 ID.AddPointer(LHS);
1914 ID.AddPointer(RHS);
1915 void *IP = 0;
1916 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1917 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001918 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001919 UniqueSCEVs.InsertNode(S, IP);
1920 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001921}
1922
1923
Dan Gohman6c0866c2009-05-24 23:45:28 +00001924/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1925/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001926const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001927 const SCEV *Step, const Loop *L,
1928 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001929 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001930 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001931 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001932 if (StepChrec->getLoop() == L) {
1933 Operands.insert(Operands.end(), StepChrec->op_begin(),
1934 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001935 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001936 }
1937
1938 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001939 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001940}
1941
Dan Gohman6c0866c2009-05-24 23:45:28 +00001942/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1943/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001944const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001945ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001946 const Loop *L,
1947 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001948 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001949#ifndef NDEBUG
1950 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1951 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1952 getEffectiveSCEVType(Operands[0]->getType()) &&
1953 "SCEVAddRecExpr operand types don't match!");
1954#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001955
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001956 if (Operands.back()->isZero()) {
1957 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001958 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001959 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001960
Dan Gohmana10756e2010-01-21 02:09:26 +00001961 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1962 if (!HasNUW && HasNSW) {
1963 bool All = true;
1964 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1965 if (!isKnownNonNegative(Operands[i])) {
1966 All = false;
1967 break;
1968 }
1969 if (All) HasNUW = true;
1970 }
1971
Dan Gohmand9cc7492008-08-08 18:33:12 +00001972 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001973 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001974 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001975 if (L->contains(NestedLoop->getHeader()) ?
1976 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1977 (!NestedLoop->contains(L->getHeader()) &&
1978 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001979 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001980 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001981 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001982 // AddRecs require their operands be loop-invariant with respect to their
1983 // loops. Don't perform this transformation if it would break this
1984 // requirement.
1985 bool AllInvariant = true;
1986 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1987 if (!Operands[i]->isLoopInvariant(L)) {
1988 AllInvariant = false;
1989 break;
1990 }
1991 if (AllInvariant) {
1992 NestedOperands[0] = getAddRecExpr(Operands, L);
1993 AllInvariant = true;
1994 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1995 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1996 AllInvariant = false;
1997 break;
1998 }
1999 if (AllInvariant)
2000 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002001 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002002 }
2003 // Reset Operands to its original state.
2004 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002005 }
2006 }
2007
Dan Gohman67847532010-01-19 22:27:22 +00002008 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2009 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002010 FoldingSetNodeID ID;
2011 ID.AddInteger(scAddRecExpr);
2012 ID.AddInteger(Operands.size());
2013 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2014 ID.AddPointer(Operands[i]);
2015 ID.AddPointer(L);
2016 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002017 SCEVAddRecExpr *S =
2018 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2019 if (!S) {
2020 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
2021 new (S) SCEVAddRecExpr(ID, Operands, L);
2022 UniqueSCEVs.InsertNode(S, IP);
2023 }
Dan Gohman3645b012009-10-09 00:10:36 +00002024 if (HasNUW) S->setHasNoUnsignedWrap(true);
2025 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002026 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002027}
2028
Dan Gohman9311ef62009-06-24 14:49:00 +00002029const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2030 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002031 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002032 Ops.push_back(LHS);
2033 Ops.push_back(RHS);
2034 return getSMaxExpr(Ops);
2035}
2036
Dan Gohman0bba49c2009-07-07 17:06:11 +00002037const SCEV *
2038ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002039 assert(!Ops.empty() && "Cannot get empty smax!");
2040 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002041#ifndef NDEBUG
2042 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2043 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2044 getEffectiveSCEVType(Ops[0]->getType()) &&
2045 "SCEVSMaxExpr operand types don't match!");
2046#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002047
2048 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002049 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002050
2051 // If there are any constants, fold them together.
2052 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002053 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002054 ++Idx;
2055 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002056 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002057 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002058 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002059 APIntOps::smax(LHSC->getValue()->getValue(),
2060 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002061 Ops[0] = getConstant(Fold);
2062 Ops.erase(Ops.begin()+1); // Erase the folded element
2063 if (Ops.size() == 1) return Ops[0];
2064 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002065 }
2066
Dan Gohmane5aceed2009-06-24 14:46:22 +00002067 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002068 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2069 Ops.erase(Ops.begin());
2070 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002071 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2072 // If we have an smax with a constant maximum-int, it will always be
2073 // maximum-int.
2074 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002075 }
2076 }
2077
2078 if (Ops.size() == 1) return Ops[0];
2079
2080 // Find the first SMax
2081 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2082 ++Idx;
2083
2084 // Check to see if one of the operands is an SMax. If so, expand its operands
2085 // onto our operand list, and recurse to simplify.
2086 if (Idx < Ops.size()) {
2087 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002088 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002089 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2090 Ops.erase(Ops.begin()+Idx);
2091 DeletedSMax = true;
2092 }
2093
2094 if (DeletedSMax)
2095 return getSMaxExpr(Ops);
2096 }
2097
2098 // Okay, check to see if the same value occurs in the operand list twice. If
2099 // so, delete one. Since we sorted the list, these values are required to
2100 // be adjacent.
2101 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2102 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2103 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2104 --i; --e;
2105 }
2106
2107 if (Ops.size() == 1) return Ops[0];
2108
2109 assert(!Ops.empty() && "Reduced smax down to nothing!");
2110
Nick Lewycky3e630762008-02-20 06:48:22 +00002111 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002112 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002113 FoldingSetNodeID ID;
2114 ID.AddInteger(scSMaxExpr);
2115 ID.AddInteger(Ops.size());
2116 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2117 ID.AddPointer(Ops[i]);
2118 void *IP = 0;
2119 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2120 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002121 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002122 UniqueSCEVs.InsertNode(S, IP);
2123 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002124}
2125
Dan Gohman9311ef62009-06-24 14:49:00 +00002126const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2127 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002128 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002129 Ops.push_back(LHS);
2130 Ops.push_back(RHS);
2131 return getUMaxExpr(Ops);
2132}
2133
Dan Gohman0bba49c2009-07-07 17:06:11 +00002134const SCEV *
2135ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002136 assert(!Ops.empty() && "Cannot get empty umax!");
2137 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002138#ifndef NDEBUG
2139 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2140 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2141 getEffectiveSCEVType(Ops[0]->getType()) &&
2142 "SCEVUMaxExpr operand types don't match!");
2143#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002144
2145 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002146 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002147
2148 // If there are any constants, fold them together.
2149 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002150 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002151 ++Idx;
2152 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002153 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002154 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002155 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002156 APIntOps::umax(LHSC->getValue()->getValue(),
2157 RHSC->getValue()->getValue()));
2158 Ops[0] = getConstant(Fold);
2159 Ops.erase(Ops.begin()+1); // Erase the folded element
2160 if (Ops.size() == 1) return Ops[0];
2161 LHSC = cast<SCEVConstant>(Ops[0]);
2162 }
2163
Dan Gohmane5aceed2009-06-24 14:46:22 +00002164 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002165 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2166 Ops.erase(Ops.begin());
2167 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002168 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2169 // If we have an umax with a constant maximum-int, it will always be
2170 // maximum-int.
2171 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002172 }
2173 }
2174
2175 if (Ops.size() == 1) return Ops[0];
2176
2177 // Find the first UMax
2178 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2179 ++Idx;
2180
2181 // Check to see if one of the operands is a UMax. If so, expand its operands
2182 // onto our operand list, and recurse to simplify.
2183 if (Idx < Ops.size()) {
2184 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002185 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002186 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2187 Ops.erase(Ops.begin()+Idx);
2188 DeletedUMax = true;
2189 }
2190
2191 if (DeletedUMax)
2192 return getUMaxExpr(Ops);
2193 }
2194
2195 // Okay, check to see if the same value occurs in the operand list twice. If
2196 // so, delete one. Since we sorted the list, these values are required to
2197 // be adjacent.
2198 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2199 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2200 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2201 --i; --e;
2202 }
2203
2204 if (Ops.size() == 1) return Ops[0];
2205
2206 assert(!Ops.empty() && "Reduced umax down to nothing!");
2207
2208 // Okay, it looks like we really DO need a umax expr. Check to see if we
2209 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002210 FoldingSetNodeID ID;
2211 ID.AddInteger(scUMaxExpr);
2212 ID.AddInteger(Ops.size());
2213 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2214 ID.AddPointer(Ops[i]);
2215 void *IP = 0;
2216 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2217 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002218 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002219 UniqueSCEVs.InsertNode(S, IP);
2220 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002221}
2222
Dan Gohman9311ef62009-06-24 14:49:00 +00002223const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2224 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002225 // ~smax(~x, ~y) == smin(x, y).
2226 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2227}
2228
Dan Gohman9311ef62009-06-24 14:49:00 +00002229const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2230 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002231 // ~umax(~x, ~y) == umin(x, y)
2232 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2233}
2234
Dan Gohman4f8eea82010-02-01 18:27:38 +00002235const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
2236 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2237 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2238 C = ConstantFoldConstantExpression(CE, TD);
2239 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2240 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2241}
2242
2243const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2244 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2245 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2246 C = ConstantFoldConstantExpression(CE, TD);
2247 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2248 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2249}
2250
2251const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2252 unsigned FieldNo) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00002253 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2254 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2255 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002256 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002257 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002258}
2259
Dan Gohman4f8eea82010-02-01 18:27:38 +00002260const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2261 Constant *FieldNo) {
2262 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002263 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2264 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohman4f8eea82010-02-01 18:27:38 +00002265 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002266 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002267}
2268
Dan Gohman0bba49c2009-07-07 17:06:11 +00002269const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002270 // Don't attempt to do anything other than create a SCEVUnknown object
2271 // here. createSCEV only calls getUnknown after checking for all other
2272 // interesting possibilities, and any other code that calls getUnknown
2273 // is doing so in order to hide a value from SCEV canonicalization.
2274
Dan Gohman1c343752009-06-27 21:21:31 +00002275 FoldingSetNodeID ID;
2276 ID.AddInteger(scUnknown);
2277 ID.AddPointer(V);
2278 void *IP = 0;
2279 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2280 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002281 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002282 UniqueSCEVs.InsertNode(S, IP);
2283 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002284}
2285
Chris Lattner53e677a2004-04-02 20:23:17 +00002286//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002287// Basic SCEV Analysis and PHI Idiom Recognition Code
2288//
2289
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002290/// isSCEVable - Test if values of the given type are analyzable within
2291/// the SCEV framework. This primarily includes integer types, and it
2292/// can optionally include pointer types if the ScalarEvolution class
2293/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002294bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002295 // Integers and pointers are always SCEVable.
2296 return Ty->isInteger() || isa<PointerType>(Ty);
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002297}
2298
2299/// getTypeSizeInBits - Return the size in bits of the specified type,
2300/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002301uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002302 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2303
2304 // If we have a TargetData, use it!
2305 if (TD)
2306 return TD->getTypeSizeInBits(Ty);
2307
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002308 // Integer types have fixed sizes.
2309 if (Ty->isInteger())
2310 return Ty->getPrimitiveSizeInBits();
2311
2312 // The only other support type is pointer. Without TargetData, conservatively
2313 // assume pointers are 64-bit.
2314 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2315 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002316}
2317
2318/// getEffectiveSCEVType - Return a type with the same bitwidth as
2319/// the given type and which represents how SCEV will treat the given
2320/// type, for which isSCEVable must return true. For pointer types,
2321/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002322const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002323 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2324
2325 if (Ty->isInteger())
2326 return Ty;
2327
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002328 // The only other support type is pointer.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002329 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002330 if (TD) return TD->getIntPtrType(getContext());
2331
2332 // Without TargetData, conservatively assume pointers are 64-bit.
2333 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002334}
Chris Lattner53e677a2004-04-02 20:23:17 +00002335
Dan Gohman0bba49c2009-07-07 17:06:11 +00002336const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002337 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002338}
2339
Chris Lattner53e677a2004-04-02 20:23:17 +00002340/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2341/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002342const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002343 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002344
Dan Gohman0bba49c2009-07-07 17:06:11 +00002345 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002346 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002347 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002348 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002349 return S;
2350}
2351
Dan Gohman6bbcba12009-06-24 00:54:57 +00002352/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002353/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002354const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002355 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002356 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002357}
2358
2359/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2360///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002361const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002362 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002363 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002364 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002365
2366 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002367 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002368 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002369 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002370}
2371
2372/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002373const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002374 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002375 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002376 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002377
2378 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002379 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002380 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002381 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002382 return getMinusSCEV(AllOnes, V);
2383}
2384
2385/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2386///
Dan Gohman9311ef62009-06-24 14:49:00 +00002387const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2388 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002389 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002390 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002391}
2392
2393/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2394/// input value to the specified type. If the type must be extended, it is zero
2395/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002396const SCEV *
2397ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002398 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002399 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002400 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2401 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002402 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002403 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002404 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002405 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002406 return getTruncateExpr(V, Ty);
2407 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002408}
2409
2410/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2411/// input value to the specified type. If the type must be extended, it is sign
2412/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002413const SCEV *
2414ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002415 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002416 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002417 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2418 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002419 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002420 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002421 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002422 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002423 return getTruncateExpr(V, Ty);
2424 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002425}
2426
Dan Gohman467c4302009-05-13 03:46:30 +00002427/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2428/// input value to the specified type. If the type must be extended, it is zero
2429/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002430const SCEV *
2431ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002432 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002433 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2434 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002435 "Cannot noop or zero extend with non-integer arguments!");
2436 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2437 "getNoopOrZeroExtend cannot truncate!");
2438 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2439 return V; // No conversion
2440 return getZeroExtendExpr(V, Ty);
2441}
2442
2443/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2444/// input value to the specified type. If the type must be extended, it is sign
2445/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002446const SCEV *
2447ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002448 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002449 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2450 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002451 "Cannot noop or sign extend with non-integer arguments!");
2452 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2453 "getNoopOrSignExtend cannot truncate!");
2454 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2455 return V; // No conversion
2456 return getSignExtendExpr(V, Ty);
2457}
2458
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002459/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2460/// the input value to the specified type. If the type must be extended,
2461/// it is extended with unspecified bits. The conversion must not be
2462/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002463const SCEV *
2464ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002465 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002466 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2467 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002468 "Cannot noop or any extend with non-integer arguments!");
2469 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2470 "getNoopOrAnyExtend cannot truncate!");
2471 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2472 return V; // No conversion
2473 return getAnyExtendExpr(V, Ty);
2474}
2475
Dan Gohman467c4302009-05-13 03:46:30 +00002476/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2477/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002478const SCEV *
2479ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002480 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002481 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2482 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002483 "Cannot truncate or noop with non-integer arguments!");
2484 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2485 "getTruncateOrNoop cannot extend!");
2486 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2487 return V; // No conversion
2488 return getTruncateExpr(V, Ty);
2489}
2490
Dan Gohmana334aa72009-06-22 00:31:57 +00002491/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2492/// the types using zero-extension, and then perform a umax operation
2493/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002494const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2495 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002496 const SCEV *PromotedLHS = LHS;
2497 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002498
2499 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2500 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2501 else
2502 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2503
2504 return getUMaxExpr(PromotedLHS, PromotedRHS);
2505}
2506
Dan Gohmanc9759e82009-06-22 15:03:27 +00002507/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2508/// the types using zero-extension, and then perform a umin operation
2509/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002510const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2511 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002512 const SCEV *PromotedLHS = LHS;
2513 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002514
2515 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2516 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2517 else
2518 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2519
2520 return getUMinExpr(PromotedLHS, PromotedRHS);
2521}
2522
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002523/// PushDefUseChildren - Push users of the given Instruction
2524/// onto the given Worklist.
2525static void
2526PushDefUseChildren(Instruction *I,
2527 SmallVectorImpl<Instruction *> &Worklist) {
2528 // Push the def-use children onto the Worklist stack.
2529 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2530 UI != UE; ++UI)
2531 Worklist.push_back(cast<Instruction>(UI));
2532}
2533
2534/// ForgetSymbolicValue - This looks up computed SCEV values for all
2535/// instructions that depend on the given instruction and removes them from
2536/// the Scalars map if they reference SymName. This is used during PHI
2537/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002538void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002539ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2540 SmallVector<Instruction *, 16> Worklist;
2541 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002542
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002543 SmallPtrSet<Instruction *, 8> Visited;
2544 Visited.insert(I);
2545 while (!Worklist.empty()) {
2546 Instruction *I = Worklist.pop_back_val();
2547 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002548
Dan Gohman5d984912009-12-18 01:14:11 +00002549 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002550 Scalars.find(static_cast<Value *>(I));
2551 if (It != Scalars.end()) {
2552 // Short-circuit the def-use traversal if the symbolic name
2553 // ceases to appear in expressions.
2554 if (!It->second->hasOperand(SymName))
2555 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002556
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002557 // SCEVUnknown for a PHI either means that it has an unrecognized
2558 // structure, or it's a PHI that's in the progress of being computed
2559 // by createNodeForPHI. In the former case, additional loop trip
2560 // count information isn't going to change anything. In the later
2561 // case, createNodeForPHI will perform the necessary updates on its
2562 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00002563 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2564 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002565 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002566 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002567 }
2568
2569 PushDefUseChildren(I, Worklist);
2570 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002571}
Chris Lattner53e677a2004-04-02 20:23:17 +00002572
2573/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2574/// a loop header, making it a potential recurrence, or it doesn't.
2575///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002576const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002577 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002578 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002579 if (L->getHeader() == PN->getParent()) {
2580 // If it lives in the loop header, it has two incoming values, one
2581 // from outside the loop, and one from inside.
2582 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2583 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002584
Chris Lattner53e677a2004-04-02 20:23:17 +00002585 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002586 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002587 assert(Scalars.find(PN) == Scalars.end() &&
2588 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002589 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002590
2591 // Using this symbolic name for the PHI, analyze the value coming around
2592 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002593 Value *BEValueV = PN->getIncomingValue(BackEdge);
2594 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002595
2596 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2597 // has a special value for the first iteration of the loop.
2598
2599 // If the value coming around the backedge is an add with the symbolic
2600 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002601 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002602 // If there is a single occurrence of the symbolic value, replace it
2603 // with a recurrence.
2604 unsigned FoundIndex = Add->getNumOperands();
2605 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2606 if (Add->getOperand(i) == SymbolicName)
2607 if (FoundIndex == e) {
2608 FoundIndex = i;
2609 break;
2610 }
2611
2612 if (FoundIndex != Add->getNumOperands()) {
2613 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002614 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002615 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2616 if (i != FoundIndex)
2617 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002618 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002619
2620 // This is not a valid addrec if the step amount is varying each
2621 // loop iteration, but is not itself an addrec in this loop.
2622 if (Accum->isLoopInvariant(L) ||
2623 (isa<SCEVAddRecExpr>(Accum) &&
2624 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002625 bool HasNUW = false;
2626 bool HasNSW = false;
2627
2628 // If the increment doesn't overflow, then neither the addrec nor
2629 // the post-increment will overflow.
2630 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2631 if (OBO->hasNoUnsignedWrap())
2632 HasNUW = true;
2633 if (OBO->hasNoSignedWrap())
2634 HasNSW = true;
2635 }
2636
Dan Gohman64a845e2009-06-24 04:48:43 +00002637 const SCEV *StartVal =
2638 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmana10756e2010-01-21 02:09:26 +00002639 const SCEV *PHISCEV =
2640 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002641
Dan Gohmana10756e2010-01-21 02:09:26 +00002642 // Since the no-wrap flags are on the increment, they apply to the
2643 // post-incremented value as well.
2644 if (Accum->isLoopInvariant(L))
2645 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2646 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002647
2648 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002649 // to be symbolic. We now need to go back and purge all of the
2650 // entries for the scalars that use the symbolic expression.
2651 ForgetSymbolicName(PN, SymbolicName);
2652 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002653 return PHISCEV;
2654 }
2655 }
Dan Gohman622ed672009-05-04 22:02:23 +00002656 } else if (const SCEVAddRecExpr *AddRec =
2657 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002658 // Otherwise, this could be a loop like this:
2659 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2660 // In this case, j = {1,+,1} and BEValue is j.
2661 // Because the other in-value of i (0) fits the evolution of BEValue
2662 // i really is an addrec evolution.
2663 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002664 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002665
2666 // If StartVal = j.start - j.stride, we can use StartVal as the
2667 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002668 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002669 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002670 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002671 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002672
2673 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002674 // to be symbolic. We now need to go back and purge all of the
2675 // entries for the scalars that use the symbolic expression.
2676 ForgetSymbolicName(PN, SymbolicName);
2677 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002678 return PHISCEV;
2679 }
2680 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002681 }
2682
2683 return SymbolicName;
2684 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002685
Dan Gohmana653fc52009-07-14 14:06:25 +00002686 // It's tempting to recognize PHIs with a unique incoming value, however
2687 // this leads passes like indvars to break LCSSA form. Fortunately, such
2688 // PHIs are rare, as instcombine zaps them.
2689
Chris Lattner53e677a2004-04-02 20:23:17 +00002690 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002691 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002692}
2693
Dan Gohman26466c02009-05-08 20:26:55 +00002694/// createNodeForGEP - Expand GEP instructions into add and multiply
2695/// operations. This allows them to be analyzed by regular SCEV code.
2696///
Dan Gohmand281ed22009-12-18 02:09:29 +00002697const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002698
Dan Gohmand281ed22009-12-18 02:09:29 +00002699 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002700 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002701 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002702 // Don't attempt to analyze GEPs over unsized objects.
2703 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2704 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002705 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002706 gep_type_iterator GTI = gep_type_begin(GEP);
2707 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2708 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002709 I != E; ++I) {
2710 Value *Index = *I;
2711 // Compute the (potentially symbolic) offset in bytes for this index.
2712 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2713 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002714 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002715 TotalOffset = getAddExpr(TotalOffset,
Dan Gohman4f8eea82010-02-01 18:27:38 +00002716 getOffsetOfExpr(STy, FieldNo),
Dan Gohmand281ed22009-12-18 02:09:29 +00002717 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002718 } else {
2719 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002720 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman8db08df2010-02-02 01:38:49 +00002721 // Getelementptr indicies are signed.
2722 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002723 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohman4f8eea82010-02-01 18:27:38 +00002724 LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
Dan Gohmand281ed22009-12-18 02:09:29 +00002725 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2726 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2727 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002728 }
2729 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002730 return getAddExpr(getSCEV(Base), TotalOffset,
2731 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002732}
2733
Nick Lewycky83bb0052007-11-22 07:59:40 +00002734/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2735/// guaranteed to end in (at every loop iteration). It is, at the same time,
2736/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2737/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002738uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002739ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002740 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002741 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002742
Dan Gohman622ed672009-05-04 22:02:23 +00002743 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002744 return std::min(GetMinTrailingZeros(T->getOperand()),
2745 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002746
Dan Gohman622ed672009-05-04 22:02:23 +00002747 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002748 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2749 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2750 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002751 }
2752
Dan Gohman622ed672009-05-04 22:02:23 +00002753 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002754 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2755 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2756 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002757 }
2758
Dan Gohman622ed672009-05-04 22:02:23 +00002759 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002760 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002761 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002762 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002763 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002764 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002765 }
2766
Dan Gohman622ed672009-05-04 22:02:23 +00002767 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002768 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002769 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2770 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002771 for (unsigned i = 1, e = M->getNumOperands();
2772 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002773 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002774 BitWidth);
2775 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002776 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002777
Dan Gohman622ed672009-05-04 22:02:23 +00002778 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002779 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002780 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002781 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002782 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002783 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002784 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002785
Dan Gohman622ed672009-05-04 22:02:23 +00002786 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002787 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002788 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002789 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002790 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002791 return MinOpRes;
2792 }
2793
Dan Gohman622ed672009-05-04 22:02:23 +00002794 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002795 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002796 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002797 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002798 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002799 return MinOpRes;
2800 }
2801
Dan Gohman2c364ad2009-06-19 23:29:04 +00002802 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2803 // For a SCEVUnknown, ask ValueTracking.
2804 unsigned BitWidth = getTypeSizeInBits(U->getType());
2805 APInt Mask = APInt::getAllOnesValue(BitWidth);
2806 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2807 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2808 return Zeros.countTrailingOnes();
2809 }
2810
2811 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002812 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002813}
Chris Lattner53e677a2004-04-02 20:23:17 +00002814
Dan Gohman85b05a22009-07-13 21:35:55 +00002815/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2816///
2817ConstantRange
2818ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002819
2820 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002821 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002822
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002823 unsigned BitWidth = getTypeSizeInBits(S->getType());
2824 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2825
2826 // If the value has known zeros, the maximum unsigned value will have those
2827 // known zeros as well.
2828 uint32_t TZ = GetMinTrailingZeros(S);
2829 if (TZ != 0)
2830 ConservativeResult =
2831 ConstantRange(APInt::getMinValue(BitWidth),
2832 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2833
Dan Gohman85b05a22009-07-13 21:35:55 +00002834 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2835 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2836 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2837 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002838 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002839 }
2840
2841 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2842 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2843 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2844 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002845 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002846 }
2847
2848 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2849 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2850 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2851 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002852 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002853 }
2854
2855 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2856 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2857 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2858 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002859 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002860 }
2861
2862 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2863 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2864 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002865 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002866 }
2867
2868 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2869 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002870 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002871 }
2872
2873 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2874 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002875 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002876 }
2877
2878 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2879 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002880 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002881 }
2882
Dan Gohman85b05a22009-07-13 21:35:55 +00002883 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002884 // If there's no unsigned wrap, the value will never be less than its
2885 // initial value.
2886 if (AddRec->hasNoUnsignedWrap())
2887 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2888 ConservativeResult =
2889 ConstantRange(C->getValue()->getValue(),
2890 APInt(getTypeSizeInBits(C->getType()), 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002891
2892 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002893 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002894 const Type *Ty = AddRec->getType();
2895 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002896 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2897 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002898 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2899
2900 const SCEV *Start = AddRec->getStart();
2901 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2902
2903 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00002904 if (!AddRec->hasNoUnsignedWrap())
2905 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00002906
2907 ConstantRange StartRange = getUnsignedRange(Start);
2908 ConstantRange EndRange = getUnsignedRange(End);
2909 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2910 EndRange.getUnsignedMin());
2911 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2912 EndRange.getUnsignedMax());
2913 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002914 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002915 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002916 }
2917 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002918
2919 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002920 }
2921
2922 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2923 // For a SCEVUnknown, ask ValueTracking.
2924 unsigned BitWidth = getTypeSizeInBits(U->getType());
2925 APInt Mask = APInt::getAllOnesValue(BitWidth);
2926 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2927 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002928 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002929 return ConservativeResult;
2930 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002931 }
2932
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002933 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002934}
2935
Dan Gohman85b05a22009-07-13 21:35:55 +00002936/// getSignedRange - Determine the signed range for a particular SCEV.
2937///
2938ConstantRange
2939ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002940
Dan Gohman85b05a22009-07-13 21:35:55 +00002941 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2942 return ConstantRange(C->getValue()->getValue());
2943
Dan Gohman52fddd32010-01-26 04:40:18 +00002944 unsigned BitWidth = getTypeSizeInBits(S->getType());
2945 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2946
2947 // If the value has known zeros, the maximum signed value will have those
2948 // known zeros as well.
2949 uint32_t TZ = GetMinTrailingZeros(S);
2950 if (TZ != 0)
2951 ConservativeResult =
2952 ConstantRange(APInt::getSignedMinValue(BitWidth),
2953 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2954
Dan Gohman85b05a22009-07-13 21:35:55 +00002955 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2956 ConstantRange X = getSignedRange(Add->getOperand(0));
2957 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2958 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002959 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002960 }
2961
Dan Gohman85b05a22009-07-13 21:35:55 +00002962 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2963 ConstantRange X = getSignedRange(Mul->getOperand(0));
2964 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2965 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002966 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002967 }
2968
Dan Gohman85b05a22009-07-13 21:35:55 +00002969 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2970 ConstantRange X = getSignedRange(SMax->getOperand(0));
2971 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2972 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002973 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002974 }
Dan Gohman62849c02009-06-24 01:05:09 +00002975
Dan Gohman85b05a22009-07-13 21:35:55 +00002976 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2977 ConstantRange X = getSignedRange(UMax->getOperand(0));
2978 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2979 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002980 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002981 }
Dan Gohman62849c02009-06-24 01:05:09 +00002982
Dan Gohman85b05a22009-07-13 21:35:55 +00002983 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2984 ConstantRange X = getSignedRange(UDiv->getLHS());
2985 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00002986 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002987 }
Dan Gohman62849c02009-06-24 01:05:09 +00002988
Dan Gohman85b05a22009-07-13 21:35:55 +00002989 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2990 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002991 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002992 }
2993
2994 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2995 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002996 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002997 }
2998
2999 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3000 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00003001 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00003002 }
3003
Dan Gohman85b05a22009-07-13 21:35:55 +00003004 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003005 // If there's no signed wrap, and all the operands have the same sign or
3006 // zero, the value won't ever change sign.
3007 if (AddRec->hasNoSignedWrap()) {
3008 bool AllNonNeg = true;
3009 bool AllNonPos = true;
3010 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3011 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3012 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3013 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003014 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003015 ConservativeResult = ConservativeResult.intersectWith(
3016 ConstantRange(APInt(BitWidth, 0),
3017 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003018 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003019 ConservativeResult = ConservativeResult.intersectWith(
3020 ConstantRange(APInt::getSignedMinValue(BitWidth),
3021 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003022 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003023
3024 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003025 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003026 const Type *Ty = AddRec->getType();
3027 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003028 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3029 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003030 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3031
3032 const SCEV *Start = AddRec->getStart();
Dan Gohman85b05a22009-07-13 21:35:55 +00003033 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3034
3035 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00003036 if (!AddRec->hasNoSignedWrap())
3037 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003038
3039 ConstantRange StartRange = getSignedRange(Start);
3040 ConstantRange EndRange = getSignedRange(End);
3041 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3042 EndRange.getSignedMin());
3043 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3044 EndRange.getSignedMax());
3045 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003046 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003047 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003048 }
Dan Gohman62849c02009-06-24 01:05:09 +00003049 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003050
3051 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003052 }
3053
Dan Gohman2c364ad2009-06-19 23:29:04 +00003054 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3055 // For a SCEVUnknown, ask ValueTracking.
Dan Gohmana10756e2010-01-21 02:09:26 +00003056 if (!U->getValue()->getType()->isInteger() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003057 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003058 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3059 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003060 return ConservativeResult;
3061 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003062 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003063 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003064 }
3065
Dan Gohman52fddd32010-01-26 04:40:18 +00003066 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003067}
3068
Chris Lattner53e677a2004-04-02 20:23:17 +00003069/// createSCEV - We know that there is no SCEV for the specified value.
3070/// Analyze the expression.
3071///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003072const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003073 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003074 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003075
Dan Gohman6c459a22008-06-22 19:56:46 +00003076 unsigned Opcode = Instruction::UserOp1;
3077 if (Instruction *I = dyn_cast<Instruction>(V))
3078 Opcode = I->getOpcode();
3079 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3080 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003081 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3082 return getConstant(CI);
3083 else if (isa<ConstantPointerNull>(V))
3084 return getIntegerSCEV(0, V->getType());
3085 else if (isa<UndefValue>(V))
3086 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00003087 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3088 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003089 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003090 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003091
Dan Gohmanca178902009-07-17 20:47:02 +00003092 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003093 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003094 case Instruction::Add:
3095 // Don't transfer the NSW and NUW bits from the Add instruction to the
3096 // Add expression, because the Instruction may be guarded by control
3097 // flow and the no-overflow bits may not be valid for the expression in
3098 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003099 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003100 getSCEV(U->getOperand(1)));
3101 case Instruction::Mul:
3102 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3103 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003104 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003105 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003106 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003107 return getUDivExpr(getSCEV(U->getOperand(0)),
3108 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003109 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003110 return getMinusSCEV(getSCEV(U->getOperand(0)),
3111 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003112 case Instruction::And:
3113 // For an expression like x&255 that merely masks off the high bits,
3114 // use zext(trunc(x)) as the SCEV expression.
3115 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003116 if (CI->isNullValue())
3117 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003118 if (CI->isAllOnesValue())
3119 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003120 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003121
3122 // Instcombine's ShrinkDemandedConstant may strip bits out of
3123 // constants, obscuring what would otherwise be a low-bits mask.
3124 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3125 // knew about to reconstruct a low-bits mask value.
3126 unsigned LZ = A.countLeadingZeros();
3127 unsigned BitWidth = A.getBitWidth();
3128 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3129 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3130 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3131
3132 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3133
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003134 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003135 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003136 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003137 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003138 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003139 }
3140 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003141
Dan Gohman6c459a22008-06-22 19:56:46 +00003142 case Instruction::Or:
3143 // If the RHS of the Or is a constant, we may have something like:
3144 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3145 // optimizations will transparently handle this case.
3146 //
3147 // In order for this transformation to be safe, the LHS must be of the
3148 // form X*(2^n) and the Or constant must be less than 2^n.
3149 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003150 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003151 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003152 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003153 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3154 // Build a plain add SCEV.
3155 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3156 // If the LHS of the add was an addrec and it has no-wrap flags,
3157 // transfer the no-wrap flags, since an or won't introduce a wrap.
3158 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3159 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3160 if (OldAR->hasNoUnsignedWrap())
3161 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3162 if (OldAR->hasNoSignedWrap())
3163 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3164 }
3165 return S;
3166 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003167 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003168 break;
3169 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003170 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003171 // If the RHS of the xor is a signbit, then this is just an add.
3172 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003173 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003174 return getAddExpr(getSCEV(U->getOperand(0)),
3175 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003176
3177 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003178 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003179 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003180
3181 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3182 // This is a variant of the check for xor with -1, and it handles
3183 // the case where instcombine has trimmed non-demanded bits out
3184 // of an xor with -1.
3185 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3186 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3187 if (BO->getOpcode() == Instruction::And &&
3188 LCI->getValue() == CI->getValue())
3189 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003190 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003191 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003192 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003193 const Type *Z0Ty = Z0->getType();
3194 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3195
3196 // If C is a low-bits mask, the zero extend is zerving to
3197 // mask off the high bits. Complement the operand and
3198 // re-apply the zext.
3199 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3200 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3201
3202 // If C is a single bit, it may be in the sign-bit position
3203 // before the zero-extend. In this case, represent the xor
3204 // using an add, which is equivalent, and re-apply the zext.
3205 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3206 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3207 Trunc.isSignBit())
3208 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3209 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003210 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003211 }
3212 break;
3213
3214 case Instruction::Shl:
3215 // Turn shift left of a constant amount into a multiply.
3216 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003217 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003218 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003219 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003220 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003221 }
3222 break;
3223
Nick Lewycky01eaf802008-07-07 06:15:49 +00003224 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003225 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003226 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003227 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003228 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003229 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003230 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003231 }
3232 break;
3233
Dan Gohman4ee29af2009-04-21 02:26:00 +00003234 case Instruction::AShr:
3235 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3236 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3237 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3238 if (L->getOpcode() == Instruction::Shl &&
3239 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003240 unsigned BitWidth = getTypeSizeInBits(U->getType());
3241 uint64_t Amt = BitWidth - CI->getZExtValue();
3242 if (Amt == BitWidth)
3243 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3244 if (Amt > BitWidth)
3245 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003246 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003247 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003248 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003249 U->getType());
3250 }
3251 break;
3252
Dan Gohman6c459a22008-06-22 19:56:46 +00003253 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003254 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003255
3256 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003257 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003258
3259 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003260 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003261
3262 case Instruction::BitCast:
3263 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003264 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003265 return getSCEV(U->getOperand(0));
3266 break;
3267
Dan Gohman4f8eea82010-02-01 18:27:38 +00003268 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3269 // lead to pointer expressions which cannot safely be expanded to GEPs,
3270 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3271 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003272
Dan Gohman26466c02009-05-08 20:26:55 +00003273 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003274 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003275
Dan Gohman6c459a22008-06-22 19:56:46 +00003276 case Instruction::PHI:
3277 return createNodeForPHI(cast<PHINode>(U));
3278
3279 case Instruction::Select:
3280 // This could be a smax or umax that was lowered earlier.
3281 // Try to recover it.
3282 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3283 Value *LHS = ICI->getOperand(0);
3284 Value *RHS = ICI->getOperand(1);
3285 switch (ICI->getPredicate()) {
3286 case ICmpInst::ICMP_SLT:
3287 case ICmpInst::ICMP_SLE:
3288 std::swap(LHS, RHS);
3289 // fall through
3290 case ICmpInst::ICMP_SGT:
3291 case ICmpInst::ICMP_SGE:
3292 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003293 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003294 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003295 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003296 break;
3297 case ICmpInst::ICMP_ULT:
3298 case ICmpInst::ICMP_ULE:
3299 std::swap(LHS, RHS);
3300 // fall through
3301 case ICmpInst::ICMP_UGT:
3302 case ICmpInst::ICMP_UGE:
3303 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003304 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003305 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003306 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003307 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003308 case ICmpInst::ICMP_NE:
3309 // n != 0 ? n : 1 -> umax(n, 1)
3310 if (LHS == U->getOperand(1) &&
3311 isa<ConstantInt>(U->getOperand(2)) &&
3312 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3313 isa<ConstantInt>(RHS) &&
3314 cast<ConstantInt>(RHS)->isZero())
3315 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3316 break;
3317 case ICmpInst::ICMP_EQ:
3318 // n == 0 ? 1 : n -> umax(n, 1)
3319 if (LHS == U->getOperand(2) &&
3320 isa<ConstantInt>(U->getOperand(1)) &&
3321 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3322 isa<ConstantInt>(RHS) &&
3323 cast<ConstantInt>(RHS)->isZero())
3324 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3325 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003326 default:
3327 break;
3328 }
3329 }
3330
3331 default: // We cannot analyze this expression.
3332 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003333 }
3334
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003335 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003336}
3337
3338
3339
3340//===----------------------------------------------------------------------===//
3341// Iteration Count Computation Code
3342//
3343
Dan Gohman46bdfb02009-02-24 18:55:53 +00003344/// getBackedgeTakenCount - If the specified loop has a predictable
3345/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3346/// object. The backedge-taken count is the number of times the loop header
3347/// will be branched to from within the loop. This is one less than the
3348/// trip count of the loop, since it doesn't count the first iteration,
3349/// when the header is branched to from outside the loop.
3350///
3351/// Note that it is not valid to call this method on a loop without a
3352/// loop-invariant backedge-taken count (see
3353/// hasLoopInvariantBackedgeTakenCount).
3354///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003355const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003356 return getBackedgeTakenInfo(L).Exact;
3357}
3358
3359/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3360/// return the least SCEV value that is known never to be less than the
3361/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003362const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003363 return getBackedgeTakenInfo(L).Max;
3364}
3365
Dan Gohman59ae6b92009-07-08 19:23:34 +00003366/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3367/// onto the given Worklist.
3368static void
3369PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3370 BasicBlock *Header = L->getHeader();
3371
3372 // Push all Loop-header PHIs onto the Worklist stack.
3373 for (BasicBlock::iterator I = Header->begin();
3374 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3375 Worklist.push_back(PN);
3376}
3377
Dan Gohmana1af7572009-04-30 20:47:05 +00003378const ScalarEvolution::BackedgeTakenInfo &
3379ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003380 // Initially insert a CouldNotCompute for this loop. If the insertion
3381 // succeeds, procede to actually compute a backedge-taken count and
3382 // update the value. The temporary CouldNotCompute value tells SCEV
3383 // code elsewhere that it shouldn't attempt to request a new
3384 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003385 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003386 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3387 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003388 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3389 if (BECount.Exact != getCouldNotCompute()) {
3390 assert(BECount.Exact->isLoopInvariant(L) &&
3391 BECount.Max->isLoopInvariant(L) &&
3392 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003393 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003394
Dan Gohman01ecca22009-04-27 20:16:15 +00003395 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003396 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003397 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003398 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003399 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003400 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003401 if (isa<PHINode>(L->getHeader()->begin()))
3402 // Only count loops that have phi nodes as not being computable.
3403 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003404 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003405
3406 // Now that we know more about the trip count for this loop, forget any
3407 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003408 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003409 // information. This is similar to the code in forgetLoop, except that
3410 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003411 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003412 SmallVector<Instruction *, 16> Worklist;
3413 PushLoopPHIs(L, Worklist);
3414
3415 SmallPtrSet<Instruction *, 8> Visited;
3416 while (!Worklist.empty()) {
3417 Instruction *I = Worklist.pop_back_val();
3418 if (!Visited.insert(I)) continue;
3419
Dan Gohman5d984912009-12-18 01:14:11 +00003420 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003421 Scalars.find(static_cast<Value *>(I));
3422 if (It != Scalars.end()) {
3423 // SCEVUnknown for a PHI either means that it has an unrecognized
3424 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003425 // by createNodeForPHI. In the former case, additional loop trip
3426 // count information isn't going to change anything. In the later
3427 // case, createNodeForPHI will perform the necessary updates on its
3428 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003429 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3430 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003431 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003432 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003433 if (PHINode *PN = dyn_cast<PHINode>(I))
3434 ConstantEvolutionLoopExitValue.erase(PN);
3435 }
3436
3437 PushDefUseChildren(I, Worklist);
3438 }
3439 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003440 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003441 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003442}
3443
Dan Gohman4c7279a2009-10-31 15:04:55 +00003444/// forgetLoop - This method should be called by the client when it has
3445/// changed a loop in a way that may effect ScalarEvolution's ability to
3446/// compute a trip count, or if the loop is deleted.
3447void ScalarEvolution::forgetLoop(const Loop *L) {
3448 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003449 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003450
Dan Gohman4c7279a2009-10-31 15:04:55 +00003451 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003452 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003453 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003454
Dan Gohman59ae6b92009-07-08 19:23:34 +00003455 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003456 while (!Worklist.empty()) {
3457 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003458 if (!Visited.insert(I)) continue;
3459
Dan Gohman5d984912009-12-18 01:14:11 +00003460 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003461 Scalars.find(static_cast<Value *>(I));
3462 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003463 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003464 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003465 if (PHINode *PN = dyn_cast<PHINode>(I))
3466 ConstantEvolutionLoopExitValue.erase(PN);
3467 }
3468
3469 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003470 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003471}
3472
Dan Gohman46bdfb02009-02-24 18:55:53 +00003473/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3474/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003475ScalarEvolution::BackedgeTakenInfo
3476ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003477 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003478 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003479
Dan Gohmana334aa72009-06-22 00:31:57 +00003480 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003481 const SCEV *BECount = getCouldNotCompute();
3482 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003483 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003484 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3485 BackedgeTakenInfo NewBTI =
3486 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003487
Dan Gohman1c343752009-06-27 21:21:31 +00003488 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003489 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003490 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003491 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003492 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003493 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003494 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003495 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003496 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003497 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003498 }
Dan Gohman1c343752009-06-27 21:21:31 +00003499 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003500 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003501 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003502 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003503 }
3504
3505 return BackedgeTakenInfo(BECount, MaxBECount);
3506}
3507
3508/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3509/// of the specified loop will execute if it exits via the specified block.
3510ScalarEvolution::BackedgeTakenInfo
3511ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3512 BasicBlock *ExitingBlock) {
3513
3514 // Okay, we've chosen an exiting block. See what condition causes us to
3515 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003516 //
3517 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003518 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003519 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003520 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003521
Chris Lattner8b0e3602007-01-07 02:24:26 +00003522 // At this point, we know we have a conditional branch that determines whether
3523 // the loop is exited. However, we don't know if the branch is executed each
3524 // time through the loop. If not, then the execution count of the branch will
3525 // not be equal to the trip count of the loop.
3526 //
3527 // Currently we check for this by checking to see if the Exit branch goes to
3528 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003529 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003530 // loop header. This is common for un-rotated loops.
3531 //
3532 // If both of those tests fail, walk up the unique predecessor chain to the
3533 // header, stopping if there is an edge that doesn't exit the loop. If the
3534 // header is reached, the execution count of the branch will be equal to the
3535 // trip count of the loop.
3536 //
3537 // More extensive analysis could be done to handle more cases here.
3538 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003539 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003540 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003541 ExitBr->getParent() != L->getHeader()) {
3542 // The simple checks failed, try climbing the unique predecessor chain
3543 // up to the header.
3544 bool Ok = false;
3545 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3546 BasicBlock *Pred = BB->getUniquePredecessor();
3547 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003548 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003549 TerminatorInst *PredTerm = Pred->getTerminator();
3550 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3551 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3552 if (PredSucc == BB)
3553 continue;
3554 // If the predecessor has a successor that isn't BB and isn't
3555 // outside the loop, assume the worst.
3556 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003557 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003558 }
3559 if (Pred == L->getHeader()) {
3560 Ok = true;
3561 break;
3562 }
3563 BB = Pred;
3564 }
3565 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003566 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003567 }
3568
3569 // Procede to the next level to examine the exit condition expression.
3570 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3571 ExitBr->getSuccessor(0),
3572 ExitBr->getSuccessor(1));
3573}
3574
3575/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3576/// backedge of the specified loop will execute if its exit condition
3577/// were a conditional branch of ExitCond, TBB, and FBB.
3578ScalarEvolution::BackedgeTakenInfo
3579ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3580 Value *ExitCond,
3581 BasicBlock *TBB,
3582 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003583 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003584 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3585 if (BO->getOpcode() == Instruction::And) {
3586 // Recurse on the operands of the and.
3587 BackedgeTakenInfo BTI0 =
3588 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3589 BackedgeTakenInfo BTI1 =
3590 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003591 const SCEV *BECount = getCouldNotCompute();
3592 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003593 if (L->contains(TBB)) {
3594 // Both conditions must be true for the loop to continue executing.
3595 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003596 if (BTI0.Exact == getCouldNotCompute() ||
3597 BTI1.Exact == getCouldNotCompute())
3598 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003599 else
3600 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003601 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003602 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003603 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003604 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003605 else
3606 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003607 } else {
3608 // Both conditions must be true for the loop to exit.
3609 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003610 if (BTI0.Exact != getCouldNotCompute() &&
3611 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003612 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003613 if (BTI0.Max != getCouldNotCompute() &&
3614 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003615 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3616 }
3617
3618 return BackedgeTakenInfo(BECount, MaxBECount);
3619 }
3620 if (BO->getOpcode() == Instruction::Or) {
3621 // Recurse on the operands of the or.
3622 BackedgeTakenInfo BTI0 =
3623 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3624 BackedgeTakenInfo BTI1 =
3625 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003626 const SCEV *BECount = getCouldNotCompute();
3627 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003628 if (L->contains(FBB)) {
3629 // Both conditions must be false for the loop to continue executing.
3630 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003631 if (BTI0.Exact == getCouldNotCompute() ||
3632 BTI1.Exact == getCouldNotCompute())
3633 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003634 else
3635 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003636 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003637 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003638 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003639 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003640 else
3641 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003642 } else {
3643 // Both conditions must be false for the loop to exit.
3644 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003645 if (BTI0.Exact != getCouldNotCompute() &&
3646 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003647 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003648 if (BTI0.Max != getCouldNotCompute() &&
3649 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003650 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3651 }
3652
3653 return BackedgeTakenInfo(BECount, MaxBECount);
3654 }
3655 }
3656
3657 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3658 // Procede to the next level to examine the icmp.
3659 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3660 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661
Eli Friedman361e54d2009-05-09 12:32:42 +00003662 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003663 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3664}
3665
3666/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3667/// backedge of the specified loop will execute if its exit condition
3668/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3669ScalarEvolution::BackedgeTakenInfo
3670ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3671 ICmpInst *ExitCond,
3672 BasicBlock *TBB,
3673 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003674
Reid Spencere4d87aa2006-12-23 06:05:41 +00003675 // If the condition was exit on true, convert the condition to exit on false
3676 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003677 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003679 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003680 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003681
3682 // Handle common loops like: for (X = "string"; *X; ++X)
3683 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3684 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003685 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003686 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003687 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3688 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3689 return BackedgeTakenInfo(ItCnt,
3690 isa<SCEVConstant>(ItCnt) ? ItCnt :
3691 getConstant(APInt::getMaxValue(BitWidth)-1));
3692 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003693 }
3694
Dan Gohman0bba49c2009-07-07 17:06:11 +00003695 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3696 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003697
3698 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003699 LHS = getSCEVAtScope(LHS, L);
3700 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003701
Dan Gohman64a845e2009-06-24 04:48:43 +00003702 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003703 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003704 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3705 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003706 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003708 }
3709
Chris Lattner53e677a2004-04-02 20:23:17 +00003710 // If we have a comparison of a chrec against a constant, try to use value
3711 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003712 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3713 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003714 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003715 // Form the constant range.
3716 ConstantRange CompRange(
3717 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003718
Dan Gohman0bba49c2009-07-07 17:06:11 +00003719 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003720 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003721 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003722
Chris Lattner53e677a2004-04-02 20:23:17 +00003723 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003724 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003725 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003726 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003727 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003728 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003729 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003730 case ICmpInst::ICMP_EQ: { // while (X == Y)
3731 // Convert to: while (X-Y == 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003732 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003733 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003734 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003735 }
3736 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003737 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3738 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003739 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003740 }
3741 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003742 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3743 getNotSCEV(RHS), L, true);
3744 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003745 break;
3746 }
3747 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003748 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3749 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003750 break;
3751 }
3752 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003753 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3754 getNotSCEV(RHS), L, false);
3755 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003756 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003757 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003758 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003759#if 0
David Greene25e0e872009-12-23 22:18:14 +00003760 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003761 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003762 dbgs() << "[unsigned] ";
3763 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003764 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003765 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003766#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003767 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003768 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003769 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003770 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003771}
3772
Chris Lattner673e02b2004-10-12 01:49:27 +00003773static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003774EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3775 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003776 const SCEV *InVal = SE.getConstant(C);
3777 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003778 assert(isa<SCEVConstant>(Val) &&
3779 "Evaluation of SCEV at constant didn't fold correctly?");
3780 return cast<SCEVConstant>(Val)->getValue();
3781}
3782
3783/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3784/// and a GEP expression (missing the pointer index) indexing into it, return
3785/// the addressed element of the initializer or null if the index expression is
3786/// invalid.
3787static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003788GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003789 const std::vector<ConstantInt*> &Indices) {
3790 Constant *Init = GV->getInitializer();
3791 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003792 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003793 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3794 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3795 Init = cast<Constant>(CS->getOperand(Idx));
3796 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3797 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3798 Init = cast<Constant>(CA->getOperand(Idx));
3799 } else if (isa<ConstantAggregateZero>(Init)) {
3800 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3801 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003802 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003803 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3804 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003805 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003806 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003807 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003808 }
3809 return 0;
3810 } else {
3811 return 0; // Unknown initializer type
3812 }
3813 }
3814 return Init;
3815}
3816
Dan Gohman46bdfb02009-02-24 18:55:53 +00003817/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3818/// 'icmp op load X, cst', try to see if we can compute the backedge
3819/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003820const SCEV *
3821ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3822 LoadInst *LI,
3823 Constant *RHS,
3824 const Loop *L,
3825 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003826 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003827
3828 // Check to see if the loaded pointer is a getelementptr of a global.
3829 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003830 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003831
3832 // Make sure that it is really a constant global we are gepping, with an
3833 // initializer, and make sure the first IDX is really 0.
3834 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003835 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003836 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3837 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003838 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003839
3840 // Okay, we allow one non-constant index into the GEP instruction.
3841 Value *VarIdx = 0;
3842 std::vector<ConstantInt*> Indexes;
3843 unsigned VarIdxNum = 0;
3844 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3845 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3846 Indexes.push_back(CI);
3847 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003848 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003849 VarIdx = GEP->getOperand(i);
3850 VarIdxNum = i-2;
3851 Indexes.push_back(0);
3852 }
3853
3854 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3855 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003856 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003857 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003858
3859 // We can only recognize very limited forms of loop index expressions, in
3860 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003861 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003862 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3863 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3864 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003865 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003866
3867 unsigned MaxSteps = MaxBruteForceIterations;
3868 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003869 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003870 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003871 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003872
3873 // Form the GEP offset.
3874 Indexes[VarIdxNum] = Val;
3875
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003876 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003877 if (Result == 0) break; // Cannot compute!
3878
3879 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003880 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003881 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003882 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003883#if 0
David Greene25e0e872009-12-23 22:18:14 +00003884 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003885 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3886 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003887#endif
3888 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003889 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003890 }
3891 }
Dan Gohman1c343752009-06-27 21:21:31 +00003892 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003893}
3894
3895
Chris Lattner3221ad02004-04-17 22:58:41 +00003896/// CanConstantFold - Return true if we can constant fold an instruction of the
3897/// specified type, assuming that all operands were constants.
3898static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003899 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003900 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3901 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003902
Chris Lattner3221ad02004-04-17 22:58:41 +00003903 if (const CallInst *CI = dyn_cast<CallInst>(I))
3904 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003905 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003906 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003907}
3908
Chris Lattner3221ad02004-04-17 22:58:41 +00003909/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3910/// in the loop that V is derived from. We allow arbitrary operations along the
3911/// way, but the operands of an operation must either be constants or a value
3912/// derived from a constant PHI. If this expression does not fit with these
3913/// constraints, return null.
3914static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3915 // If this is not an instruction, or if this is an instruction outside of the
3916 // loop, it can't be derived from a loop PHI.
3917 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00003918 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003919
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003920 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003921 if (L->getHeader() == I->getParent())
3922 return PN;
3923 else
3924 // We don't currently keep track of the control flow needed to evaluate
3925 // PHIs, so we cannot handle PHIs inside of loops.
3926 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003927 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003928
3929 // If we won't be able to constant fold this expression even if the operands
3930 // are constants, return early.
3931 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003932
Chris Lattner3221ad02004-04-17 22:58:41 +00003933 // Otherwise, we can evaluate this instruction if all of its operands are
3934 // constant or derived from a PHI node themselves.
3935 PHINode *PHI = 0;
3936 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3937 if (!(isa<Constant>(I->getOperand(Op)) ||
3938 isa<GlobalValue>(I->getOperand(Op)))) {
3939 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3940 if (P == 0) return 0; // Not evolving from PHI
3941 if (PHI == 0)
3942 PHI = P;
3943 else if (PHI != P)
3944 return 0; // Evolving from multiple different PHIs.
3945 }
3946
3947 // This is a expression evolving from a constant PHI!
3948 return PHI;
3949}
3950
3951/// EvaluateExpression - Given an expression that passes the
3952/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3953/// in the loop has the value PHIVal. If we can't fold this expression for some
3954/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003955static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
3956 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003957 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003958 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003959 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003960 Instruction *I = cast<Instruction>(V);
3961
3962 std::vector<Constant*> Operands;
3963 Operands.resize(I->getNumOperands());
3964
3965 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003966 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003967 if (Operands[i] == 0) return 0;
3968 }
3969
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003970 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00003971 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003972 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00003973 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003974 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003975}
3976
3977/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3978/// in the header of its containing loop, we know the loop executes a
3979/// constant number of times, and the PHI node is just a recurrence
3980/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003981Constant *
3982ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00003983 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00003984 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003985 std::map<PHINode*, Constant*>::iterator I =
3986 ConstantEvolutionLoopExitValue.find(PN);
3987 if (I != ConstantEvolutionLoopExitValue.end())
3988 return I->second;
3989
Dan Gohman46bdfb02009-02-24 18:55:53 +00003990 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003991 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3992
3993 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3994
3995 // Since the loop is canonicalized, the PHI node must have two entries. One
3996 // entry must be a constant (coming in from outside of the loop), and the
3997 // second must be derived from the same PHI.
3998 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3999 Constant *StartCST =
4000 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4001 if (StartCST == 0)
4002 return RetVal = 0; // Must be a constant.
4003
4004 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4005 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
4006 if (PN2 != PN)
4007 return RetVal = 0; // Not derived from same PHI.
4008
4009 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004010 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004011 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004012
Dan Gohman46bdfb02009-02-24 18:55:53 +00004013 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004014 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004015 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4016 if (IterationNum == NumIterations)
4017 return RetVal = PHIVal; // Got exit value!
4018
4019 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004020 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004021 if (NextPHI == PHIVal)
4022 return RetVal = NextPHI; // Stopped evolving!
4023 if (NextPHI == 0)
4024 return 0; // Couldn't evaluate!
4025 PHIVal = NextPHI;
4026 }
4027}
4028
Dan Gohman07ad19b2009-07-27 16:09:48 +00004029/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004030/// constant number of times (the condition evolves only from constants),
4031/// try to evaluate a few iterations of the loop until we get the exit
4032/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004033/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004034const SCEV *
4035ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4036 Value *Cond,
4037 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004038 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004039 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004040
4041 // Since the loop is canonicalized, the PHI node must have two entries. One
4042 // entry must be a constant (coming in from outside of the loop), and the
4043 // second must be derived from the same PHI.
4044 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4045 Constant *StartCST =
4046 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004047 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004048
4049 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4050 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004051 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004052
4053 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4054 // the loop symbolically to determine when the condition gets a value of
4055 // "ExitWhen".
4056 unsigned IterationNum = 0;
4057 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4058 for (Constant *PHIVal = StartCST;
4059 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004060 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004061 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004062
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004063 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004064 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004065
Reid Spencere8019bb2007-03-01 07:25:48 +00004066 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004067 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004068 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004069 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004070
Chris Lattner3221ad02004-04-17 22:58:41 +00004071 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004072 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004073 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004074 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004075 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004076 }
4077
4078 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004079 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004080}
4081
Dan Gohmane7125f42009-09-03 15:00:26 +00004082/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004083/// at the specified scope in the program. The L value specifies a loop
4084/// nest to evaluate the expression at, where null is the top-level or a
4085/// specified loop is immediately inside of the loop.
4086///
4087/// This method can be used to compute the exit value for a variable defined
4088/// in a loop by querying what the value will hold in the parent loop.
4089///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004090/// In the case that a relevant loop exit value cannot be computed, the
4091/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004092const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004093 // Check to see if we've folded this expression at this loop before.
4094 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4095 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4096 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4097 if (!Pair.second)
4098 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004099
Dan Gohman42214892009-08-31 21:15:23 +00004100 // Otherwise compute it.
4101 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004102 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004103 return C;
4104}
4105
4106const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004107 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004108
Nick Lewycky3e630762008-02-20 06:48:22 +00004109 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004110 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004111 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004112 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004113 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004114 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4115 if (PHINode *PN = dyn_cast<PHINode>(I))
4116 if (PN->getParent() == LI->getHeader()) {
4117 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004118 // to see if the loop that contains it has a known backedge-taken
4119 // count. If so, we may be able to force computation of the exit
4120 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004121 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004122 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004123 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004124 // Okay, we know how many times the containing loop executes. If
4125 // this is a constant evolving PHI node, get the final value at
4126 // the specified iteration number.
4127 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004128 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004129 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004130 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004131 }
4132 }
4133
Reid Spencer09906f32006-12-04 21:33:23 +00004134 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004135 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004136 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004137 // result. This is particularly useful for computing loop exit values.
4138 if (CanConstantFold(I)) {
4139 std::vector<Constant*> Operands;
4140 Operands.reserve(I->getNumOperands());
4141 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4142 Value *Op = I->getOperand(i);
4143 if (Constant *C = dyn_cast<Constant>(Op)) {
4144 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004145 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004146 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004147 // non-integer and non-pointer, don't even try to analyze them
4148 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004149 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004150 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004151
Dan Gohman5d984912009-12-18 01:14:11 +00004152 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004154 Constant *C = SC->getValue();
4155 if (C->getType() != Op->getType())
4156 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4157 Op->getType(),
4158 false),
4159 C, Op->getType());
4160 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004161 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004162 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4163 if (C->getType() != Op->getType())
4164 C =
4165 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4166 Op->getType(),
4167 false),
4168 C, Op->getType());
4169 Operands.push_back(C);
4170 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004171 return V;
4172 } else {
4173 return V;
4174 }
4175 }
4176 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004177
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004178 Constant *C;
4179 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4180 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004181 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004182 else
4183 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004184 &Operands[0], Operands.size(), TD);
Dan Gohman09987962009-06-29 21:31:18 +00004185 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004186 }
4187 }
4188
4189 // This is some other type of SCEVUnknown, just return it.
4190 return V;
4191 }
4192
Dan Gohman622ed672009-05-04 22:02:23 +00004193 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004194 // Avoid performing the look-up in the common case where the specified
4195 // expression has no loop-variant portions.
4196 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004197 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004198 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004199 // Okay, at least one of these operands is loop variant but might be
4200 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004201 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4202 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004203 NewOps.push_back(OpAtScope);
4204
4205 for (++i; i != e; ++i) {
4206 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004207 NewOps.push_back(OpAtScope);
4208 }
4209 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004210 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004211 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004212 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004213 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004214 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004215 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004216 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004217 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004218 }
4219 }
4220 // If we got here, all operands are loop invariant.
4221 return Comm;
4222 }
4223
Dan Gohman622ed672009-05-04 22:02:23 +00004224 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004225 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4226 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004227 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4228 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004229 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004230 }
4231
4232 // If this is a loop recurrence for a loop that does not contain L, then we
4233 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004234 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004235 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004236 // To evaluate this recurrence, we need to know how many times the AddRec
4237 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004238 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004239 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004240
Eli Friedmanb42a6262008-08-04 23:49:06 +00004241 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004242 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004243 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004244 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004245 }
4246
Dan Gohman622ed672009-05-04 22:02:23 +00004247 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004248 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004249 if (Op == Cast->getOperand())
4250 return Cast; // must be loop invariant
4251 return getZeroExtendExpr(Op, Cast->getType());
4252 }
4253
Dan Gohman622ed672009-05-04 22:02:23 +00004254 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004255 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004256 if (Op == Cast->getOperand())
4257 return Cast; // must be loop invariant
4258 return getSignExtendExpr(Op, Cast->getType());
4259 }
4260
Dan Gohman622ed672009-05-04 22:02:23 +00004261 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004262 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004263 if (Op == Cast->getOperand())
4264 return Cast; // must be loop invariant
4265 return getTruncateExpr(Op, Cast->getType());
4266 }
4267
Torok Edwinc23197a2009-07-14 16:55:14 +00004268 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004269 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004270}
4271
Dan Gohman66a7e852009-05-08 20:38:54 +00004272/// getSCEVAtScope - This is a convenience function which does
4273/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004274const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004275 return getSCEVAtScope(getSCEV(V), L);
4276}
4277
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004278/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4279/// following equation:
4280///
4281/// A * X = B (mod N)
4282///
4283/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4284/// A and B isn't important.
4285///
4286/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004287static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004288 ScalarEvolution &SE) {
4289 uint32_t BW = A.getBitWidth();
4290 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4291 assert(A != 0 && "A must be non-zero.");
4292
4293 // 1. D = gcd(A, N)
4294 //
4295 // The gcd of A and N may have only one prime factor: 2. The number of
4296 // trailing zeros in A is its multiplicity
4297 uint32_t Mult2 = A.countTrailingZeros();
4298 // D = 2^Mult2
4299
4300 // 2. Check if B is divisible by D.
4301 //
4302 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4303 // is not less than multiplicity of this prime factor for D.
4304 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004305 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004306
4307 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4308 // modulo (N / D).
4309 //
4310 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4311 // bit width during computations.
4312 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4313 APInt Mod(BW + 1, 0);
4314 Mod.set(BW - Mult2); // Mod = N / D
4315 APInt I = AD.multiplicativeInverse(Mod);
4316
4317 // 4. Compute the minimum unsigned root of the equation:
4318 // I * (B / D) mod (N / D)
4319 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4320
4321 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4322 // bits.
4323 return SE.getConstant(Result.trunc(BW));
4324}
Chris Lattner53e677a2004-04-02 20:23:17 +00004325
4326/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4327/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4328/// might be the same) or two SCEVCouldNotCompute objects.
4329///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004330static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004331SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004332 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004333 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4334 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4335 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004336
Chris Lattner53e677a2004-04-02 20:23:17 +00004337 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004338 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004339 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004340 return std::make_pair(CNC, CNC);
4341 }
4342
Reid Spencere8019bb2007-03-01 07:25:48 +00004343 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004344 const APInt &L = LC->getValue()->getValue();
4345 const APInt &M = MC->getValue()->getValue();
4346 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004347 APInt Two(BitWidth, 2);
4348 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004349
Dan Gohman64a845e2009-06-24 04:48:43 +00004350 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004351 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004352 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004353 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4354 // The B coefficient is M-N/2
4355 APInt B(M);
4356 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004357
Reid Spencere8019bb2007-03-01 07:25:48 +00004358 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004359 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004360
Reid Spencere8019bb2007-03-01 07:25:48 +00004361 // Compute the B^2-4ac term.
4362 APInt SqrtTerm(B);
4363 SqrtTerm *= B;
4364 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004365
Reid Spencere8019bb2007-03-01 07:25:48 +00004366 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4367 // integer value or else APInt::sqrt() will assert.
4368 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004369
Dan Gohman64a845e2009-06-24 04:48:43 +00004370 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004371 // The divisions must be performed as signed divisions.
4372 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004373 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004374 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004375 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004376 return std::make_pair(CNC, CNC);
4377 }
4378
Owen Andersone922c022009-07-22 00:24:57 +00004379 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004380
4381 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004382 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004383 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004384 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004385
Dan Gohman64a845e2009-06-24 04:48:43 +00004386 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004387 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004388 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004389}
4390
4391/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004392/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004393const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004394 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004395 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004396 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004397 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004398 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004399 }
4400
Dan Gohman35738ac2009-05-04 22:30:44 +00004401 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004402 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004403 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004404
4405 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004406 // If this is an affine expression, the execution count of this branch is
4407 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004408 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004409 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004410 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004411 // equivalent to:
4412 //
4413 // Step*N = -Start (mod 2^BW)
4414 //
4415 // where BW is the common bit width of Start and Step.
4416
Chris Lattner53e677a2004-04-02 20:23:17 +00004417 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004418 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4419 L->getParentLoop());
4420 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4421 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004422
Dan Gohman622ed672009-05-04 22:02:23 +00004423 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004424 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004425
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004426 // First, handle unitary steps.
4427 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004428 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004429 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4430 return Start; // N = Start (as unsigned)
4431
4432 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004433 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004434 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004435 -StartC->getValue()->getValue(),
4436 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004437 }
Chris Lattner42a75512007-01-15 02:27:26 +00004438 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004439 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4440 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004441 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004442 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004443 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4444 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004445 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004446#if 0
David Greene25e0e872009-12-23 22:18:14 +00004447 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004448 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004449#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004450 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004451 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004452 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004453 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004454 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004455 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004456
Chris Lattner53e677a2004-04-02 20:23:17 +00004457 // We can only use this value if the chrec ends up with an exact zero
4458 // value at this index. When solving for "X*X != 5", for example, we
4459 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004460 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004461 if (Val->isZero())
4462 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004463 }
4464 }
4465 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004466
Dan Gohman1c343752009-06-27 21:21:31 +00004467 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004468}
4469
4470/// HowFarToNonZero - Return the number of times a backedge checking the
4471/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004472/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004473const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004474 // Loops that look like: while (X == 0) are very strange indeed. We don't
4475 // handle them yet except for the trivial case. This could be expanded in the
4476 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004477
Chris Lattner53e677a2004-04-02 20:23:17 +00004478 // If the value is a constant, check to see if it is known to be non-zero
4479 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004480 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004481 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004482 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004483 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004484 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004485
Chris Lattner53e677a2004-04-02 20:23:17 +00004486 // We could implement others, but I really doubt anyone writes loops like
4487 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004488 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004489}
4490
Dan Gohman859b4822009-05-18 15:36:09 +00004491/// getLoopPredecessor - If the given loop's header has exactly one unique
4492/// predecessor outside the loop, return it. Otherwise return null.
4493///
4494BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4495 BasicBlock *Header = L->getHeader();
4496 BasicBlock *Pred = 0;
4497 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4498 PI != E; ++PI)
4499 if (!L->contains(*PI)) {
4500 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4501 Pred = *PI;
4502 }
4503 return Pred;
4504}
4505
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004506/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4507/// (which may not be an immediate predecessor) which has exactly one
4508/// successor from which BB is reachable, or null if no such block is
4509/// found.
4510///
4511BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004512ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004513 // If the block has a unique predecessor, then there is no path from the
4514 // predecessor to the block that does not go through the direct edge
4515 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004516 if (BasicBlock *Pred = BB->getSinglePredecessor())
4517 return Pred;
4518
4519 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004520 // If the header has a unique predecessor outside the loop, it must be
4521 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004522 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004523 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004524
4525 return 0;
4526}
4527
Dan Gohman763bad12009-06-20 00:35:32 +00004528/// HasSameValue - SCEV structural equivalence is usually sufficient for
4529/// testing whether two expressions are equal, however for the purposes of
4530/// looking for a condition guarding a loop, it can be useful to be a little
4531/// more general, since a front-end may have replicated the controlling
4532/// expression.
4533///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004534static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004535 // Quick check to see if they are the same SCEV.
4536 if (A == B) return true;
4537
4538 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4539 // two different instructions with the same value. Check for this case.
4540 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4541 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4542 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4543 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004544 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004545 return true;
4546
4547 // Otherwise assume they may have a different value.
4548 return false;
4549}
4550
Dan Gohman85b05a22009-07-13 21:35:55 +00004551bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4552 return getSignedRange(S).getSignedMax().isNegative();
4553}
4554
4555bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4556 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4557}
4558
4559bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4560 return !getSignedRange(S).getSignedMin().isNegative();
4561}
4562
4563bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4564 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4565}
4566
4567bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4568 return isKnownNegative(S) || isKnownPositive(S);
4569}
4570
4571bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4572 const SCEV *LHS, const SCEV *RHS) {
4573
4574 if (HasSameValue(LHS, RHS))
4575 return ICmpInst::isTrueWhenEqual(Pred);
4576
4577 switch (Pred) {
4578 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004579 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004580 break;
4581 case ICmpInst::ICMP_SGT:
4582 Pred = ICmpInst::ICMP_SLT;
4583 std::swap(LHS, RHS);
4584 case ICmpInst::ICMP_SLT: {
4585 ConstantRange LHSRange = getSignedRange(LHS);
4586 ConstantRange RHSRange = getSignedRange(RHS);
4587 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4588 return true;
4589 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4590 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004591 break;
4592 }
4593 case ICmpInst::ICMP_SGE:
4594 Pred = ICmpInst::ICMP_SLE;
4595 std::swap(LHS, RHS);
4596 case ICmpInst::ICMP_SLE: {
4597 ConstantRange LHSRange = getSignedRange(LHS);
4598 ConstantRange RHSRange = getSignedRange(RHS);
4599 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4600 return true;
4601 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4602 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004603 break;
4604 }
4605 case ICmpInst::ICMP_UGT:
4606 Pred = ICmpInst::ICMP_ULT;
4607 std::swap(LHS, RHS);
4608 case ICmpInst::ICMP_ULT: {
4609 ConstantRange LHSRange = getUnsignedRange(LHS);
4610 ConstantRange RHSRange = getUnsignedRange(RHS);
4611 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4612 return true;
4613 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4614 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004615 break;
4616 }
4617 case ICmpInst::ICMP_UGE:
4618 Pred = ICmpInst::ICMP_ULE;
4619 std::swap(LHS, RHS);
4620 case ICmpInst::ICMP_ULE: {
4621 ConstantRange LHSRange = getUnsignedRange(LHS);
4622 ConstantRange RHSRange = getUnsignedRange(RHS);
4623 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4624 return true;
4625 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4626 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004627 break;
4628 }
4629 case ICmpInst::ICMP_NE: {
4630 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4631 return true;
4632 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4633 return true;
4634
4635 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4636 if (isKnownNonZero(Diff))
4637 return true;
4638 break;
4639 }
4640 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004641 // The check at the top of the function catches the case where
4642 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004643 break;
4644 }
4645 return false;
4646}
4647
4648/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4649/// protected by a conditional between LHS and RHS. This is used to
4650/// to eliminate casts.
4651bool
4652ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4653 ICmpInst::Predicate Pred,
4654 const SCEV *LHS, const SCEV *RHS) {
4655 // Interpret a null as meaning no loop, where there is obviously no guard
4656 // (interprocedural conditions notwithstanding).
4657 if (!L) return true;
4658
4659 BasicBlock *Latch = L->getLoopLatch();
4660 if (!Latch)
4661 return false;
4662
4663 BranchInst *LoopContinuePredicate =
4664 dyn_cast<BranchInst>(Latch->getTerminator());
4665 if (!LoopContinuePredicate ||
4666 LoopContinuePredicate->isUnconditional())
4667 return false;
4668
Dan Gohman0f4b2852009-07-21 23:03:19 +00004669 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4670 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004671}
4672
4673/// isLoopGuardedByCond - Test whether entry to the loop is protected
4674/// by a conditional between LHS and RHS. This is used to help avoid max
4675/// expressions in loop trip counts, and to eliminate casts.
4676bool
4677ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4678 ICmpInst::Predicate Pred,
4679 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004680 // Interpret a null as meaning no loop, where there is obviously no guard
4681 // (interprocedural conditions notwithstanding).
4682 if (!L) return false;
4683
Dan Gohman859b4822009-05-18 15:36:09 +00004684 BasicBlock *Predecessor = getLoopPredecessor(L);
4685 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004686
Dan Gohman859b4822009-05-18 15:36:09 +00004687 // Starting at the loop predecessor, climb up the predecessor chain, as long
4688 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004689 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004690 for (; Predecessor;
4691 PredecessorDest = Predecessor,
4692 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004693
4694 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004695 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004696 if (!LoopEntryPredicate ||
4697 LoopEntryPredicate->isUnconditional())
4698 continue;
4699
Dan Gohman0f4b2852009-07-21 23:03:19 +00004700 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4701 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004702 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004703 }
4704
Dan Gohman38372182008-08-12 20:17:31 +00004705 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004706}
4707
Dan Gohman0f4b2852009-07-21 23:03:19 +00004708/// isImpliedCond - Test whether the condition described by Pred, LHS,
4709/// and RHS is true whenever the given Cond value evaluates to true.
4710bool ScalarEvolution::isImpliedCond(Value *CondValue,
4711 ICmpInst::Predicate Pred,
4712 const SCEV *LHS, const SCEV *RHS,
4713 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004714 // Recursivly handle And and Or conditions.
4715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4716 if (BO->getOpcode() == Instruction::And) {
4717 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004718 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4719 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004720 } else if (BO->getOpcode() == Instruction::Or) {
4721 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004722 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4723 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004724 }
4725 }
4726
4727 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4728 if (!ICI) return false;
4729
Dan Gohman85b05a22009-07-13 21:35:55 +00004730 // Bail if the ICmp's operands' types are wider than the needed type
4731 // before attempting to call getSCEV on them. This avoids infinite
4732 // recursion, since the analysis of widening casts can require loop
4733 // exit condition information for overflow checking, which would
4734 // lead back here.
4735 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004736 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004737 return false;
4738
Dan Gohman0f4b2852009-07-21 23:03:19 +00004739 // Now that we found a conditional branch that dominates the loop, check to
4740 // see if it is the comparison we are looking for.
4741 ICmpInst::Predicate FoundPred;
4742 if (Inverse)
4743 FoundPred = ICI->getInversePredicate();
4744 else
4745 FoundPred = ICI->getPredicate();
4746
4747 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4748 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004749
4750 // Balance the types. The case where FoundLHS' type is wider than
4751 // LHS' type is checked for above.
4752 if (getTypeSizeInBits(LHS->getType()) >
4753 getTypeSizeInBits(FoundLHS->getType())) {
4754 if (CmpInst::isSigned(Pred)) {
4755 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4756 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4757 } else {
4758 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4759 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4760 }
4761 }
4762
Dan Gohman0f4b2852009-07-21 23:03:19 +00004763 // Canonicalize the query to match the way instcombine will have
4764 // canonicalized the comparison.
4765 // First, put a constant operand on the right.
4766 if (isa<SCEVConstant>(LHS)) {
4767 std::swap(LHS, RHS);
4768 Pred = ICmpInst::getSwappedPredicate(Pred);
4769 }
4770 // Then, canonicalize comparisons with boundary cases.
4771 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4772 const APInt &RA = RC->getValue()->getValue();
4773 switch (Pred) {
4774 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4775 case ICmpInst::ICMP_EQ:
4776 case ICmpInst::ICMP_NE:
4777 break;
4778 case ICmpInst::ICMP_UGE:
4779 if ((RA - 1).isMinValue()) {
4780 Pred = ICmpInst::ICMP_NE;
4781 RHS = getConstant(RA - 1);
4782 break;
4783 }
4784 if (RA.isMaxValue()) {
4785 Pred = ICmpInst::ICMP_EQ;
4786 break;
4787 }
4788 if (RA.isMinValue()) return true;
4789 break;
4790 case ICmpInst::ICMP_ULE:
4791 if ((RA + 1).isMaxValue()) {
4792 Pred = ICmpInst::ICMP_NE;
4793 RHS = getConstant(RA + 1);
4794 break;
4795 }
4796 if (RA.isMinValue()) {
4797 Pred = ICmpInst::ICMP_EQ;
4798 break;
4799 }
4800 if (RA.isMaxValue()) return true;
4801 break;
4802 case ICmpInst::ICMP_SGE:
4803 if ((RA - 1).isMinSignedValue()) {
4804 Pred = ICmpInst::ICMP_NE;
4805 RHS = getConstant(RA - 1);
4806 break;
4807 }
4808 if (RA.isMaxSignedValue()) {
4809 Pred = ICmpInst::ICMP_EQ;
4810 break;
4811 }
4812 if (RA.isMinSignedValue()) return true;
4813 break;
4814 case ICmpInst::ICMP_SLE:
4815 if ((RA + 1).isMaxSignedValue()) {
4816 Pred = ICmpInst::ICMP_NE;
4817 RHS = getConstant(RA + 1);
4818 break;
4819 }
4820 if (RA.isMinSignedValue()) {
4821 Pred = ICmpInst::ICMP_EQ;
4822 break;
4823 }
4824 if (RA.isMaxSignedValue()) return true;
4825 break;
4826 case ICmpInst::ICMP_UGT:
4827 if (RA.isMinValue()) {
4828 Pred = ICmpInst::ICMP_NE;
4829 break;
4830 }
4831 if ((RA + 1).isMaxValue()) {
4832 Pred = ICmpInst::ICMP_EQ;
4833 RHS = getConstant(RA + 1);
4834 break;
4835 }
4836 if (RA.isMaxValue()) return false;
4837 break;
4838 case ICmpInst::ICMP_ULT:
4839 if (RA.isMaxValue()) {
4840 Pred = ICmpInst::ICMP_NE;
4841 break;
4842 }
4843 if ((RA - 1).isMinValue()) {
4844 Pred = ICmpInst::ICMP_EQ;
4845 RHS = getConstant(RA - 1);
4846 break;
4847 }
4848 if (RA.isMinValue()) return false;
4849 break;
4850 case ICmpInst::ICMP_SGT:
4851 if (RA.isMinSignedValue()) {
4852 Pred = ICmpInst::ICMP_NE;
4853 break;
4854 }
4855 if ((RA + 1).isMaxSignedValue()) {
4856 Pred = ICmpInst::ICMP_EQ;
4857 RHS = getConstant(RA + 1);
4858 break;
4859 }
4860 if (RA.isMaxSignedValue()) return false;
4861 break;
4862 case ICmpInst::ICMP_SLT:
4863 if (RA.isMaxSignedValue()) {
4864 Pred = ICmpInst::ICMP_NE;
4865 break;
4866 }
4867 if ((RA - 1).isMinSignedValue()) {
4868 Pred = ICmpInst::ICMP_EQ;
4869 RHS = getConstant(RA - 1);
4870 break;
4871 }
4872 if (RA.isMinSignedValue()) return false;
4873 break;
4874 }
4875 }
4876
4877 // Check to see if we can make the LHS or RHS match.
4878 if (LHS == FoundRHS || RHS == FoundLHS) {
4879 if (isa<SCEVConstant>(RHS)) {
4880 std::swap(FoundLHS, FoundRHS);
4881 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4882 } else {
4883 std::swap(LHS, RHS);
4884 Pred = ICmpInst::getSwappedPredicate(Pred);
4885 }
4886 }
4887
4888 // Check whether the found predicate is the same as the desired predicate.
4889 if (FoundPred == Pred)
4890 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4891
4892 // Check whether swapping the found predicate makes it the same as the
4893 // desired predicate.
4894 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4895 if (isa<SCEVConstant>(RHS))
4896 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4897 else
4898 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4899 RHS, LHS, FoundLHS, FoundRHS);
4900 }
4901
4902 // Check whether the actual condition is beyond sufficient.
4903 if (FoundPred == ICmpInst::ICMP_EQ)
4904 if (ICmpInst::isTrueWhenEqual(Pred))
4905 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4906 return true;
4907 if (Pred == ICmpInst::ICMP_NE)
4908 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4909 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4910 return true;
4911
4912 // Otherwise assume the worst.
4913 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004914}
4915
Dan Gohman0f4b2852009-07-21 23:03:19 +00004916/// isImpliedCondOperands - Test whether the condition described by Pred,
4917/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4918/// and FoundRHS is true.
4919bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4920 const SCEV *LHS, const SCEV *RHS,
4921 const SCEV *FoundLHS,
4922 const SCEV *FoundRHS) {
4923 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4924 FoundLHS, FoundRHS) ||
4925 // ~x < ~y --> x > y
4926 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4927 getNotSCEV(FoundRHS),
4928 getNotSCEV(FoundLHS));
4929}
4930
4931/// isImpliedCondOperandsHelper - Test whether the condition described by
4932/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4933/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004934bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004935ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4936 const SCEV *LHS, const SCEV *RHS,
4937 const SCEV *FoundLHS,
4938 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004939 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004940 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4941 case ICmpInst::ICMP_EQ:
4942 case ICmpInst::ICMP_NE:
4943 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4944 return true;
4945 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004946 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004947 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004948 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4949 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4950 return true;
4951 break;
4952 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004953 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004954 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4955 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4956 return true;
4957 break;
4958 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004959 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004960 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4961 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4962 return true;
4963 break;
4964 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004965 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004966 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4967 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4968 return true;
4969 break;
4970 }
4971
4972 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004973}
4974
Dan Gohman51f53b72009-06-21 23:46:38 +00004975/// getBECount - Subtract the end and start values and divide by the step,
4976/// rounding up, to get the number of times the backedge is executed. Return
4977/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004978const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004979 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00004980 const SCEV *Step,
4981 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00004982 assert(!isKnownNegative(Step) &&
4983 "This code doesn't handle negative strides yet!");
4984
Dan Gohman51f53b72009-06-21 23:46:38 +00004985 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004986 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4987 const SCEV *Diff = getMinusSCEV(End, Start);
4988 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004989
4990 // Add an adjustment to the difference between End and Start so that
4991 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004992 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004993
Dan Gohman1f96e672009-09-17 18:05:20 +00004994 if (!NoWrap) {
4995 // Check Add for unsigned overflow.
4996 // TODO: More sophisticated things could be done here.
4997 const Type *WideTy = IntegerType::get(getContext(),
4998 getTypeSizeInBits(Ty) + 1);
4999 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5000 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5001 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5002 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5003 return getCouldNotCompute();
5004 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005005
5006 return getUDivExpr(Add, Step);
5007}
5008
Chris Lattnerdb25de42005-08-15 23:33:51 +00005009/// HowManyLessThans - Return the number of times a backedge containing the
5010/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005011/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005012ScalarEvolution::BackedgeTakenInfo
5013ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5014 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005015 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00005016 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005017
Dan Gohman35738ac2009-05-04 22:30:44 +00005018 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005019 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005020 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005021
Dan Gohman1f96e672009-09-17 18:05:20 +00005022 // Check to see if we have a flag which makes analysis easy.
5023 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5024 AddRec->hasNoUnsignedWrap();
5025
Chris Lattnerdb25de42005-08-15 23:33:51 +00005026 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005027 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005028 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005029
Dan Gohman52fddd32010-01-26 04:40:18 +00005030 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005031 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005032 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005033 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005034 } else if (isKnownPositive(Step)) {
5035 // Test whether a positive iteration iteration can step past the limit
5036 // value and past the maximum value for its type in a single step.
5037 // Note that it's not sufficient to check NoWrap here, because even
5038 // though the value after a wrap is undefined, it's not undefined
5039 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005040 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005041 // iterate at least until the iteration where the wrapping occurs.
5042 const SCEV *One = getIntegerSCEV(1, Step->getType());
5043 if (isSigned) {
5044 APInt Max = APInt::getSignedMaxValue(BitWidth);
5045 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5046 .slt(getSignedRange(RHS).getSignedMax()))
5047 return getCouldNotCompute();
5048 } else {
5049 APInt Max = APInt::getMaxValue(BitWidth);
5050 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5051 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5052 return getCouldNotCompute();
5053 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005054 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005055 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005056 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005057
Dan Gohmana1af7572009-04-30 20:47:05 +00005058 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5059 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5060 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005061 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005062
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005063 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005064 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005065
Dan Gohmana1af7572009-04-30 20:47:05 +00005066 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005067 const SCEV *MinStart = getConstant(isSigned ?
5068 getSignedRange(Start).getSignedMin() :
5069 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005070
Dan Gohmana1af7572009-04-30 20:47:05 +00005071 // If we know that the condition is true in order to enter the loop,
5072 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005073 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5074 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005075 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00005076 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00005077 isSigned ? ICmpInst::ICMP_SLT :
5078 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00005079 getMinusSCEV(Start, Step), RHS))
5080 End = isSigned ? getSMaxExpr(RHS, Start)
5081 : getUMaxExpr(RHS, Start);
5082
5083 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005084 const SCEV *MaxEnd = getConstant(isSigned ?
5085 getSignedRange(End).getSignedMax() :
5086 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005087
Dan Gohman52fddd32010-01-26 04:40:18 +00005088 // If MaxEnd is within a step of the maximum integer value in its type,
5089 // adjust it down to the minimum value which would produce the same effect.
5090 // This allows the subsequent ceiling divison of (N+(step-1))/step to
5091 // compute the correct value.
5092 const SCEV *StepMinusOne = getMinusSCEV(Step,
5093 getIntegerSCEV(1, Step->getType()));
5094 MaxEnd = isSigned ?
5095 getSMinExpr(MaxEnd,
5096 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5097 StepMinusOne)) :
5098 getUMinExpr(MaxEnd,
5099 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5100 StepMinusOne));
5101
Dan Gohmana1af7572009-04-30 20:47:05 +00005102 // Finally, we subtract these two values and divide, rounding up, to get
5103 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005104 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005105
5106 // The maximum backedge count is similar, except using the minimum start
5107 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005108 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005109
5110 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005111 }
5112
Dan Gohman1c343752009-06-27 21:21:31 +00005113 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005114}
5115
Chris Lattner53e677a2004-04-02 20:23:17 +00005116/// getNumIterationsInRange - Return the number of iterations of this loop that
5117/// produce values in the specified constant range. Another way of looking at
5118/// this is that it returns the first iteration number where the value is not in
5119/// the condition, thus computing the exit count. If the iteration count can't
5120/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005121const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005122 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005123 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005124 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005125
5126 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005127 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005128 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005129 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005130 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005131 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005132 if (const SCEVAddRecExpr *ShiftedAddRec =
5133 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005134 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005135 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005136 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005137 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005138 }
5139
5140 // The only time we can solve this is when we have all constant indices.
5141 // Otherwise, we cannot determine the overflow conditions.
5142 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5143 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005144 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005145
5146
5147 // Okay at this point we know that all elements of the chrec are constants and
5148 // that the start element is zero.
5149
5150 // First check to see if the range contains zero. If not, the first
5151 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005152 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005153 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005154 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005155
Chris Lattner53e677a2004-04-02 20:23:17 +00005156 if (isAffine()) {
5157 // If this is an affine expression then we have this situation:
5158 // Solve {0,+,A} in Range === Ax in Range
5159
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005160 // We know that zero is in the range. If A is positive then we know that
5161 // the upper value of the range must be the first possible exit value.
5162 // If A is negative then the lower of the range is the last possible loop
5163 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005164 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005165 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5166 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005167
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005168 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005169 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005170 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005171
5172 // Evaluate at the exit value. If we really did fall out of the valid
5173 // range, then we computed our trip count, otherwise wrap around or other
5174 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005175 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005176 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005177 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005178
5179 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005180 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005181 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005182 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005183 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005184 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005185 } else if (isQuadratic()) {
5186 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5187 // quadratic equation to solve it. To do this, we must frame our problem in
5188 // terms of figuring out when zero is crossed, instead of when
5189 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005190 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005191 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005192 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005193
5194 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005195 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005196 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005197 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5198 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005199 if (R1) {
5200 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005201 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005202 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005203 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005204 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005205 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005206
Chris Lattner53e677a2004-04-02 20:23:17 +00005207 // Make sure the root is not off by one. The returned iteration should
5208 // not be in the range, but the previous one should be. When solving
5209 // for "X*X < 5", for example, we should not return a root of 2.
5210 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005211 R1->getValue(),
5212 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005213 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005214 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005215 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005216 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005217
Dan Gohman246b2562007-10-22 18:31:58 +00005218 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005219 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005220 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005221 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005222 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005223
Chris Lattner53e677a2004-04-02 20:23:17 +00005224 // If R1 was not in the range, then it is a good return value. Make
5225 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005226 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005227 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005228 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005229 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005230 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005231 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005232 }
5233 }
5234 }
5235
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005236 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005237}
5238
5239
5240
5241//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005242// SCEVCallbackVH Class Implementation
5243//===----------------------------------------------------------------------===//
5244
Dan Gohman1959b752009-05-19 19:22:47 +00005245void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005246 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005247 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5248 SE->ConstantEvolutionLoopExitValue.erase(PN);
5249 SE->Scalars.erase(getValPtr());
5250 // this now dangles!
5251}
5252
Dan Gohman1959b752009-05-19 19:22:47 +00005253void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005254 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005255
5256 // Forget all the expressions associated with users of the old value,
5257 // so that future queries will recompute the expressions using the new
5258 // value.
5259 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005260 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005261 Value *Old = getValPtr();
5262 bool DeleteOld = false;
5263 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5264 UI != UE; ++UI)
5265 Worklist.push_back(*UI);
5266 while (!Worklist.empty()) {
5267 User *U = Worklist.pop_back_val();
5268 // Deleting the Old value will cause this to dangle. Postpone
5269 // that until everything else is done.
5270 if (U == Old) {
5271 DeleteOld = true;
5272 continue;
5273 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005274 if (!Visited.insert(U))
5275 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005276 if (PHINode *PN = dyn_cast<PHINode>(U))
5277 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005278 SE->Scalars.erase(U);
5279 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5280 UI != UE; ++UI)
5281 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005282 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005283 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005284 if (DeleteOld) {
5285 if (PHINode *PN = dyn_cast<PHINode>(Old))
5286 SE->ConstantEvolutionLoopExitValue.erase(PN);
5287 SE->Scalars.erase(Old);
5288 // this now dangles!
5289 }
5290 // this may dangle!
5291}
5292
Dan Gohman1959b752009-05-19 19:22:47 +00005293ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005294 : CallbackVH(V), SE(se) {}
5295
5296//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005297// ScalarEvolution Class Implementation
5298//===----------------------------------------------------------------------===//
5299
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005300ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005301 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005302}
5303
Chris Lattner53e677a2004-04-02 20:23:17 +00005304bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005305 this->F = &F;
5306 LI = &getAnalysis<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005307 DT = &getAnalysis<DominatorTree>();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005308 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005309 return false;
5310}
5311
5312void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005313 Scalars.clear();
5314 BackedgeTakenCounts.clear();
5315 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005316 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005317 UniqueSCEVs.clear();
5318 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005319}
5320
5321void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5322 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005323 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005324 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005325}
5326
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005327bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005328 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005329}
5330
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005331static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005332 const Loop *L) {
5333 // Print all inner loops first
5334 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5335 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005336
Dan Gohman30733292010-01-09 18:17:45 +00005337 OS << "Loop ";
5338 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5339 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005340
Dan Gohman5d984912009-12-18 01:14:11 +00005341 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005342 L->getExitBlocks(ExitBlocks);
5343 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005344 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005345
Dan Gohman46bdfb02009-02-24 18:55:53 +00005346 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5347 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005348 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005349 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005350 }
5351
Dan Gohman30733292010-01-09 18:17:45 +00005352 OS << "\n"
5353 "Loop ";
5354 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5355 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005356
5357 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5358 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5359 } else {
5360 OS << "Unpredictable max backedge-taken count. ";
5361 }
5362
5363 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005364}
5365
Dan Gohman5d984912009-12-18 01:14:11 +00005366void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005367 // ScalarEvolution's implementaiton of the print method is to print
5368 // out SCEV values of all instructions that are interesting. Doing
5369 // this potentially causes it to create new SCEV objects though,
5370 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005371 // observable from outside the class though, so casting away the
5372 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005373 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005374
Dan Gohman30733292010-01-09 18:17:45 +00005375 OS << "Classifying expressions for: ";
5376 WriteAsOperand(OS, F, /*PrintType=*/false);
5377 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005378 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005379 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005380 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005381 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005382 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005383 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005384
Dan Gohman0c689c52009-06-19 17:49:54 +00005385 const Loop *L = LI->getLoopFor((*I).getParent());
5386
Dan Gohman0bba49c2009-07-07 17:06:11 +00005387 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005388 if (AtUse != SV) {
5389 OS << " --> ";
5390 AtUse->print(OS);
5391 }
5392
5393 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005394 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005395 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005396 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005397 OS << "<<Unknown>>";
5398 } else {
5399 OS << *ExitValue;
5400 }
5401 }
5402
Chris Lattner53e677a2004-04-02 20:23:17 +00005403 OS << "\n";
5404 }
5405
Dan Gohman30733292010-01-09 18:17:45 +00005406 OS << "Determining loop execution counts for: ";
5407 WriteAsOperand(OS, F, /*PrintType=*/false);
5408 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005409 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5410 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005411}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005412