blob: f19e153e0d40b3f278ee922d1660f8612fda91e1 [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::isOffsetOf(const StructType *&STy, Constant *&FieldNo) 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)))
354 if (CE->getOpcode() == Instruction::GetElementPtr)
355 if (CE->getOperand(0)->isNullValue()) {
356 const Type *Ty =
357 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
358 if (const StructType *StructTy = dyn_cast<StructType>(Ty))
359 if (CE->getNumOperands() == 3 &&
360 CE->getOperand(1)->isNullValue()) {
361 STy = StructTy;
362 FieldNo = CE->getOperand(2);
363 return true;
364 }
365 }
366
367 return false;
368}
369
370bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
371 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
372 if (VCE->getOpcode() == Instruction::PtrToInt)
373 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
374 if (CE->getOpcode() == Instruction::GetElementPtr)
375 if (CE->getOperand(0)->isNullValue()) {
376 const Type *Ty =
377 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
378 if (CE->getNumOperands() == 2)
379 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
380 if (CI->isOne()) {
381 AllocTy = Ty;
382 return true;
383 }
384 }
385
386 return false;
387}
388
389bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
391 if (VCE->getOpcode() == Instruction::PtrToInt)
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
393 if (CE->getOpcode() == Instruction::GetElementPtr)
394 if (CE->getOperand(0)->isNullValue()) {
395 const Type *Ty =
396 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
397 if (const StructType *STy = dyn_cast<StructType>(Ty))
398 if (CE->getNumOperands() == 3 &&
399 CE->getOperand(1)->isNullValue()) {
400 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
401 if (CI->isOne() &&
402 STy->getNumElements() == 2 &&
403 STy->getElementType(0)->isInteger(1)) {
404 AllocTy = STy->getElementType(1);
405 return true;
406 }
407 }
408 }
409
410 return false;
411}
412
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000413void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000414 const Type *AllocTy;
415 if (isSizeOf(AllocTy)) {
416 OS << "sizeof(" << *AllocTy << ")";
417 return;
418 }
419 if (isAlignOf(AllocTy)) {
420 OS << "alignof(" << *AllocTy << ")";
421 return;
422 }
423
424 const StructType *STy;
425 Constant *FieldNo;
426 if (isOffsetOf(STy, FieldNo)) {
427 OS << "offsetof(" << *STy << ", ";
428 WriteAsOperand(OS, FieldNo, false);
429 OS << ")";
430 return;
431 }
432
433 // Otherwise just print it normally.
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000434 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000435}
436
Chris Lattner8d741b82004-06-20 06:23:15 +0000437//===----------------------------------------------------------------------===//
438// SCEV Utilities
439//===----------------------------------------------------------------------===//
440
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000441static bool CompareTypes(const Type *A, const Type *B) {
442 if (A->getTypeID() != B->getTypeID())
443 return A->getTypeID() < B->getTypeID();
444 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
445 const IntegerType *BI = cast<IntegerType>(B);
446 return AI->getBitWidth() < BI->getBitWidth();
447 }
448 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
449 const PointerType *BI = cast<PointerType>(B);
450 return CompareTypes(AI->getElementType(), BI->getElementType());
451 }
452 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
453 const ArrayType *BI = cast<ArrayType>(B);
454 if (AI->getNumElements() != BI->getNumElements())
455 return AI->getNumElements() < BI->getNumElements();
456 return CompareTypes(AI->getElementType(), BI->getElementType());
457 }
458 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
459 const VectorType *BI = cast<VectorType>(B);
460 if (AI->getNumElements() != BI->getNumElements())
461 return AI->getNumElements() < BI->getNumElements();
462 return CompareTypes(AI->getElementType(), BI->getElementType());
463 }
464 if (const StructType *AI = dyn_cast<StructType>(A)) {
465 const StructType *BI = cast<StructType>(B);
466 if (AI->getNumElements() != BI->getNumElements())
467 return AI->getNumElements() < BI->getNumElements();
468 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
469 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
470 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
471 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
472 }
473 return false;
474}
475
Chris Lattner8d741b82004-06-20 06:23:15 +0000476namespace {
477 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
478 /// than the complexity of the RHS. This comparator is used to canonicalize
479 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000480 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000481 LoopInfo *LI;
482 public:
483 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
484
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000485 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000486 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
487 if (LHS == RHS)
488 return false;
489
Dan Gohman72861302009-05-07 14:39:04 +0000490 // Primarily, sort the SCEVs by their getSCEVType().
491 if (LHS->getSCEVType() != RHS->getSCEVType())
492 return LHS->getSCEVType() < RHS->getSCEVType();
493
494 // Aside from the getSCEVType() ordering, the particular ordering
495 // isn't very important except that it's beneficial to be consistent,
496 // so that (a + b) and (b + a) don't end up as different expressions.
497
498 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
499 // not as complete as it could be.
500 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
501 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
502
Dan Gohman5be18e82009-05-19 02:15:55 +0000503 // Order pointer values after integer values. This helps SCEVExpander
504 // form GEPs.
505 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
506 return false;
507 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
508 return true;
509
Dan Gohman72861302009-05-07 14:39:04 +0000510 // Compare getValueID values.
511 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
512 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
513
514 // Sort arguments by their position.
515 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
516 const Argument *RA = cast<Argument>(RU->getValue());
517 return LA->getArgNo() < RA->getArgNo();
518 }
519
520 // For instructions, compare their loop depth, and their opcode.
521 // This is pretty loose.
522 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
523 Instruction *RV = cast<Instruction>(RU->getValue());
524
525 // Compare loop depths.
526 if (LI->getLoopDepth(LV->getParent()) !=
527 LI->getLoopDepth(RV->getParent()))
528 return LI->getLoopDepth(LV->getParent()) <
529 LI->getLoopDepth(RV->getParent());
530
531 // Compare opcodes.
532 if (LV->getOpcode() != RV->getOpcode())
533 return LV->getOpcode() < RV->getOpcode();
534
535 // Compare the number of operands.
536 if (LV->getNumOperands() != RV->getNumOperands())
537 return LV->getNumOperands() < RV->getNumOperands();
538 }
539
540 return false;
541 }
542
Dan Gohman4dfad292009-06-14 22:51:25 +0000543 // Compare constant values.
544 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
545 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000546 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
547 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000548 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
549 }
550
551 // Compare addrec loop depths.
552 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
553 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
554 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
555 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
556 }
Dan Gohman72861302009-05-07 14:39:04 +0000557
558 // Lexicographically compare n-ary expressions.
559 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
560 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
561 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
562 if (i >= RC->getNumOperands())
563 return false;
564 if (operator()(LC->getOperand(i), RC->getOperand(i)))
565 return true;
566 if (operator()(RC->getOperand(i), LC->getOperand(i)))
567 return false;
568 }
569 return LC->getNumOperands() < RC->getNumOperands();
570 }
571
Dan Gohmana6b35e22009-05-07 19:23:21 +0000572 // Lexicographically compare udiv expressions.
573 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
574 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
575 if (operator()(LC->getLHS(), RC->getLHS()))
576 return true;
577 if (operator()(RC->getLHS(), LC->getLHS()))
578 return false;
579 if (operator()(LC->getRHS(), RC->getRHS()))
580 return true;
581 if (operator()(RC->getRHS(), LC->getRHS()))
582 return false;
583 return false;
584 }
585
Dan Gohman72861302009-05-07 14:39:04 +0000586 // Compare cast expressions by operand.
587 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
588 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
589 return operator()(LC->getOperand(), RC->getOperand());
590 }
591
Torok Edwinc23197a2009-07-14 16:55:14 +0000592 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000593 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000594 }
595 };
596}
597
598/// GroupByComplexity - Given a list of SCEV objects, order them by their
599/// complexity, and group objects of the same complexity together by value.
600/// When this routine is finished, we know that any duplicates in the vector are
601/// consecutive and that complexity is monotonically increasing.
602///
603/// Note that we go take special precautions to ensure that we get determinstic
604/// results from this routine. In other words, we don't want the results of
605/// this to depend on where the addresses of various SCEV objects happened to
606/// land in memory.
607///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000608static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000609 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000610 if (Ops.size() < 2) return; // Noop
611 if (Ops.size() == 2) {
612 // This is the common case, which also happens to be trivially simple.
613 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000614 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000615 std::swap(Ops[0], Ops[1]);
616 return;
617 }
618
619 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000620 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000621
622 // Now that we are sorted by complexity, group elements of the same
623 // complexity. Note that this is, at worst, N^2, but the vector is likely to
624 // be extremely short in practice. Note that we take this approach because we
625 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000626 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000627 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000628 unsigned Complexity = S->getSCEVType();
629
630 // If there are any objects of the same complexity and same value as this
631 // one, group them.
632 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
633 if (Ops[j] == S) { // Found a duplicate.
634 // Move it to immediately after i'th element.
635 std::swap(Ops[i+1], Ops[j]);
636 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000637 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000638 }
639 }
640 }
641}
642
Chris Lattner53e677a2004-04-02 20:23:17 +0000643
Chris Lattner53e677a2004-04-02 20:23:17 +0000644
645//===----------------------------------------------------------------------===//
646// Simple SCEV method implementations
647//===----------------------------------------------------------------------===//
648
Eli Friedmanb42a6262008-08-04 23:49:06 +0000649/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000650/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000651static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000652 ScalarEvolution &SE,
653 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000654 // Handle the simplest case efficiently.
655 if (K == 1)
656 return SE.getTruncateOrZeroExtend(It, ResultTy);
657
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000658 // We are using the following formula for BC(It, K):
659 //
660 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
661 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000662 // Suppose, W is the bitwidth of the return value. We must be prepared for
663 // overflow. Hence, we must assure that the result of our computation is
664 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
665 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000666 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000667 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000668 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000669 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
670 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000671 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000672 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000673 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000674 // This formula is trivially equivalent to the previous formula. However,
675 // this formula can be implemented much more efficiently. The trick is that
676 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
677 // arithmetic. To do exact division in modular arithmetic, all we have
678 // to do is multiply by the inverse. Therefore, this step can be done at
679 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000680 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000681 // The next issue is how to safely do the division by 2^T. The way this
682 // is done is by doing the multiplication step at a width of at least W + T
683 // bits. This way, the bottom W+T bits of the product are accurate. Then,
684 // when we perform the division by 2^T (which is equivalent to a right shift
685 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
686 // truncated out after the division by 2^T.
687 //
688 // In comparison to just directly using the first formula, this technique
689 // is much more efficient; using the first formula requires W * K bits,
690 // but this formula less than W + K bits. Also, the first formula requires
691 // a division step, whereas this formula only requires multiplies and shifts.
692 //
693 // It doesn't matter whether the subtraction step is done in the calculation
694 // width or the input iteration count's width; if the subtraction overflows,
695 // the result must be zero anyway. We prefer here to do it in the width of
696 // the induction variable because it helps a lot for certain cases; CodeGen
697 // isn't smart enough to ignore the overflow, which leads to much less
698 // efficient code if the width of the subtraction is wider than the native
699 // register width.
700 //
701 // (It's possible to not widen at all by pulling out factors of 2 before
702 // the multiplication; for example, K=2 can be calculated as
703 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
704 // extra arithmetic, so it's not an obvious win, and it gets
705 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000706
Eli Friedmanb42a6262008-08-04 23:49:06 +0000707 // Protection from insane SCEVs; this bound is conservative,
708 // but it probably doesn't matter.
709 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000710 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000711
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000712 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000713
Eli Friedmanb42a6262008-08-04 23:49:06 +0000714 // Calculate K! / 2^T and T; we divide out the factors of two before
715 // multiplying for calculating K! / 2^T to avoid overflow.
716 // Other overflow doesn't matter because we only care about the bottom
717 // W bits of the result.
718 APInt OddFactorial(W, 1);
719 unsigned T = 1;
720 for (unsigned i = 3; i <= K; ++i) {
721 APInt Mult(W, i);
722 unsigned TwoFactors = Mult.countTrailingZeros();
723 T += TwoFactors;
724 Mult = Mult.lshr(TwoFactors);
725 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000726 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000727
Eli Friedmanb42a6262008-08-04 23:49:06 +0000728 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000729 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000730
731 // Calcuate 2^T, at width T+W.
732 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
733
734 // Calculate the multiplicative inverse of K! / 2^T;
735 // this multiplication factor will perform the exact division by
736 // K! / 2^T.
737 APInt Mod = APInt::getSignedMinValue(W+1);
738 APInt MultiplyFactor = OddFactorial.zext(W+1);
739 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
740 MultiplyFactor = MultiplyFactor.trunc(W);
741
742 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000743 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
744 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000745 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000746 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000747 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000748 Dividend = SE.getMulExpr(Dividend,
749 SE.getTruncateOrZeroExtend(S, CalculationTy));
750 }
751
752 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000753 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000754
755 // Truncate the result, and divide by K! / 2^T.
756
757 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
758 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000759}
760
Chris Lattner53e677a2004-04-02 20:23:17 +0000761/// evaluateAtIteration - Return the value of this chain of recurrences at
762/// the specified iteration number. We can evaluate this recurrence by
763/// multiplying each element in the chain by the binomial coefficient
764/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
765///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000766/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000767///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000768/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000769///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000770const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000771 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000772 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000773 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000774 // The computation is correct in the face of overflow provided that the
775 // multiplication is performed _after_ the evaluation of the binomial
776 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000777 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000778 if (isa<SCEVCouldNotCompute>(Coeff))
779 return Coeff;
780
781 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000782 }
783 return Result;
784}
785
Chris Lattner53e677a2004-04-02 20:23:17 +0000786//===----------------------------------------------------------------------===//
787// SCEV Expression folder implementations
788//===----------------------------------------------------------------------===//
789
Dan Gohman0bba49c2009-07-07 17:06:11 +0000790const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000791 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000792 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000793 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000794 assert(isSCEVable(Ty) &&
795 "This is not a conversion to a SCEVable type!");
796 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000797
Dan Gohmanc050fd92009-07-13 20:50:19 +0000798 FoldingSetNodeID ID;
799 ID.AddInteger(scTruncate);
800 ID.AddPointer(Op);
801 ID.AddPointer(Ty);
802 void *IP = 0;
803 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
804
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000805 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000806 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000807 return getConstant(
808 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000809
Dan Gohman20900ca2009-04-22 16:20:48 +0000810 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000811 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000812 return getTruncateExpr(ST->getOperand(), Ty);
813
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000814 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000815 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000816 return getTruncateOrSignExtend(SS->getOperand(), Ty);
817
818 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000819 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000820 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
821
Dan Gohman6864db62009-06-18 16:24:47 +0000822 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000823 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000824 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000825 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000826 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
827 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000828 }
829
Dan Gohmanc050fd92009-07-13 20:50:19 +0000830 // The cast wasn't folded; create an explicit cast node.
831 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000832 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
833 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000834 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000835 UniqueSCEVs.InsertNode(S, IP);
836 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000837}
838
Dan Gohman0bba49c2009-07-07 17:06:11 +0000839const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000840 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000841 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000842 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000843 assert(isSCEVable(Ty) &&
844 "This is not a conversion to a SCEVable type!");
845 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000846
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000847 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000848 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000849 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000850 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
851 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000852 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000853 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000854
Dan Gohman20900ca2009-04-22 16:20:48 +0000855 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000856 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000857 return getZeroExtendExpr(SZ->getOperand(), Ty);
858
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000859 // Before doing any expensive analysis, check to see if we've already
860 // computed a SCEV for this Op and Ty.
861 FoldingSetNodeID ID;
862 ID.AddInteger(scZeroExtend);
863 ID.AddPointer(Op);
864 ID.AddPointer(Ty);
865 void *IP = 0;
866 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
867
Dan Gohman01ecca22009-04-27 20:16:15 +0000868 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000869 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000870 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000871 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000872 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000873 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000874 const SCEV *Start = AR->getStart();
875 const SCEV *Step = AR->getStepRecurrence(*this);
876 unsigned BitWidth = getTypeSizeInBits(AR->getType());
877 const Loop *L = AR->getLoop();
878
Dan Gohmaneb490a72009-07-25 01:22:26 +0000879 // If we have special knowledge that this addrec won't overflow,
880 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000881 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000882 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
883 getZeroExtendExpr(Step, Ty),
884 L);
885
Dan Gohman01ecca22009-04-27 20:16:15 +0000886 // Check whether the backedge-taken count is SCEVCouldNotCompute.
887 // Note that this serves two purposes: It filters out loops that are
888 // simply not analyzable, and it covers the case where this code is
889 // being called from within backedge-taken count analysis, such that
890 // attempting to ask for the backedge-taken count would likely result
891 // in infinite recursion. In the later case, the analysis code will
892 // cope with a conservative value, and it will take care to purge
893 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000894 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000895 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000896 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000897 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000898
899 // Check whether the backedge-taken count can be losslessly casted to
900 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000901 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000902 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000903 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000904 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
905 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000906 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000907 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000908 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000909 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000910 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000911 const SCEV *Add = getAddExpr(Start, ZMul);
912 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000913 getAddExpr(getZeroExtendExpr(Start, WideTy),
914 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
915 getZeroExtendExpr(Step, WideTy)));
916 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000917 // Return the expression with the addrec on the outside.
918 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
919 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000920 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000921
922 // Similar to above, only this time treat the step value as signed.
923 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000924 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000925 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000926 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000927 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000928 OperandExtendedAdd =
929 getAddExpr(getZeroExtendExpr(Start, WideTy),
930 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
931 getSignExtendExpr(Step, WideTy)));
932 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000933 // Return the expression with the addrec on the outside.
934 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
935 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000936 L);
937 }
938
939 // If the backedge is guarded by a comparison with the pre-inc value
940 // the addrec is safe. Also, if the entry is guarded by a comparison
941 // with the start value and the backedge is guarded by a comparison
942 // with the post-inc value, the addrec is safe.
943 if (isKnownPositive(Step)) {
944 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
945 getUnsignedRange(Step).getUnsignedMax());
946 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
947 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
948 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
949 AR->getPostIncExpr(*this), N)))
950 // Return the expression with the addrec on the outside.
951 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
952 getZeroExtendExpr(Step, Ty),
953 L);
954 } else if (isKnownNegative(Step)) {
955 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
956 getSignedRange(Step).getSignedMin());
957 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
958 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
959 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
960 AR->getPostIncExpr(*this), N)))
961 // Return the expression with the addrec on the outside.
962 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
963 getSignExtendExpr(Step, Ty),
964 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000965 }
966 }
967 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000968
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000969 // The cast wasn't folded; create an explicit cast node.
970 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000971 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
972 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000973 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000974 UniqueSCEVs.InsertNode(S, IP);
975 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000976}
977
Dan Gohman0bba49c2009-07-07 17:06:11 +0000978const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000979 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000980 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000981 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000982 assert(isSCEVable(Ty) &&
983 "This is not a conversion to a SCEVable type!");
984 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000985
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000986 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000987 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000988 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000989 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
990 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000991 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000992 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000993
Dan Gohman20900ca2009-04-22 16:20:48 +0000994 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000995 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000996 return getSignExtendExpr(SS->getOperand(), Ty);
997
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000998 // Before doing any expensive analysis, check to see if we've already
999 // computed a SCEV for this Op and Ty.
1000 FoldingSetNodeID ID;
1001 ID.AddInteger(scSignExtend);
1002 ID.AddPointer(Op);
1003 ID.AddPointer(Ty);
1004 void *IP = 0;
1005 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1006
Dan Gohman01ecca22009-04-27 20:16:15 +00001007 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +00001008 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +00001009 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +00001010 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +00001011 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +00001012 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00001013 const SCEV *Start = AR->getStart();
1014 const SCEV *Step = AR->getStepRecurrence(*this);
1015 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1016 const Loop *L = AR->getLoop();
1017
Dan Gohmaneb490a72009-07-25 01:22:26 +00001018 // If we have special knowledge that this addrec won't overflow,
1019 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +00001020 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001021 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1022 getSignExtendExpr(Step, Ty),
1023 L);
1024
Dan Gohman01ecca22009-04-27 20:16:15 +00001025 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1026 // Note that this serves two purposes: It filters out loops that are
1027 // simply not analyzable, and it covers the case where this code is
1028 // being called from within backedge-taken count analysis, such that
1029 // attempting to ask for the backedge-taken count would likely result
1030 // in infinite recursion. In the later case, the analysis code will
1031 // cope with a conservative value, and it will take care to purge
1032 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001033 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001034 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001035 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001036 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001037
1038 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001039 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001040 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001041 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001042 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001043 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1044 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001045 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001046 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001047 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +00001048 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +00001049 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001050 const SCEV *Add = getAddExpr(Start, SMul);
1051 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001052 getAddExpr(getSignExtendExpr(Start, WideTy),
1053 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1054 getSignExtendExpr(Step, WideTy)));
1055 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001056 // Return the expression with the addrec on the outside.
1057 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1058 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001059 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001060
1061 // Similar to above, only this time treat the step value as unsigned.
1062 // This covers loops that count up with an unsigned step.
1063 const SCEV *UMul =
1064 getMulExpr(CastedMaxBECount,
1065 getTruncateOrZeroExtend(Step, Start->getType()));
1066 Add = getAddExpr(Start, UMul);
1067 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001068 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001069 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1070 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001071 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001072 // Return the expression with the addrec on the outside.
1073 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1074 getZeroExtendExpr(Step, Ty),
1075 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001076 }
1077
1078 // If the backedge is guarded by a comparison with the pre-inc value
1079 // the addrec is safe. Also, if the entry is guarded by a comparison
1080 // with the start value and the backedge is guarded by a comparison
1081 // with the post-inc value, the addrec is safe.
1082 if (isKnownPositive(Step)) {
1083 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1084 getSignedRange(Step).getSignedMax());
1085 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1086 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1087 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1088 AR->getPostIncExpr(*this), N)))
1089 // Return the expression with the addrec on the outside.
1090 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1091 getSignExtendExpr(Step, Ty),
1092 L);
1093 } else if (isKnownNegative(Step)) {
1094 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1095 getSignedRange(Step).getSignedMin());
1096 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1097 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1098 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1099 AR->getPostIncExpr(*this), N)))
1100 // Return the expression with the addrec on the outside.
1101 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1102 getSignExtendExpr(Step, Ty),
1103 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001104 }
1105 }
1106 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001107
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001108 // The cast wasn't folded; create an explicit cast node.
1109 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001110 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1111 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001112 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001113 UniqueSCEVs.InsertNode(S, IP);
1114 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001115}
1116
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001117/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1118/// unspecified bits out to the given type.
1119///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001120const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001121 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001122 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1123 "This is not an extending conversion!");
1124 assert(isSCEVable(Ty) &&
1125 "This is not a conversion to a SCEVable type!");
1126 Ty = getEffectiveSCEVType(Ty);
1127
1128 // Sign-extend negative constants.
1129 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1130 if (SC->getValue()->getValue().isNegative())
1131 return getSignExtendExpr(Op, Ty);
1132
1133 // Peel off a truncate cast.
1134 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001135 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001136 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1137 return getAnyExtendExpr(NewOp, Ty);
1138 return getTruncateOrNoop(NewOp, Ty);
1139 }
1140
1141 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001142 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001143 if (!isa<SCEVZeroExtendExpr>(ZExt))
1144 return ZExt;
1145
1146 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001147 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001148 if (!isa<SCEVSignExtendExpr>(SExt))
1149 return SExt;
1150
Dan Gohmana10756e2010-01-21 02:09:26 +00001151 // Force the cast to be folded into the operands of an addrec.
1152 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1153 SmallVector<const SCEV *, 4> Ops;
1154 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1155 I != E; ++I)
1156 Ops.push_back(getAnyExtendExpr(*I, Ty));
1157 return getAddRecExpr(Ops, AR->getLoop());
1158 }
1159
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001160 // If the expression is obviously signed, use the sext cast value.
1161 if (isa<SCEVSMaxExpr>(Op))
1162 return SExt;
1163
1164 // Absent any other information, use the zext cast value.
1165 return ZExt;
1166}
1167
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001168/// CollectAddOperandsWithScales - Process the given Ops list, which is
1169/// a list of operands to be added under the given scale, update the given
1170/// map. This is a helper function for getAddRecExpr. As an example of
1171/// what it does, given a sequence of operands that would form an add
1172/// expression like this:
1173///
1174/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1175///
1176/// where A and B are constants, update the map with these values:
1177///
1178/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1179///
1180/// and add 13 + A*B*29 to AccumulatedConstant.
1181/// This will allow getAddRecExpr to produce this:
1182///
1183/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1184///
1185/// This form often exposes folding opportunities that are hidden in
1186/// the original operand list.
1187///
1188/// Return true iff it appears that any interesting folding opportunities
1189/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1190/// the common case where no interesting opportunities are present, and
1191/// is also used as a check to avoid infinite recursion.
1192///
1193static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001194CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1195 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001196 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001197 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001198 const APInt &Scale,
1199 ScalarEvolution &SE) {
1200 bool Interesting = false;
1201
1202 // Iterate over the add operands.
1203 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1204 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1205 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1206 APInt NewScale =
1207 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1208 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1209 // A multiplication of a constant with another add; recurse.
1210 Interesting |=
1211 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1212 cast<SCEVAddExpr>(Mul->getOperand(1))
1213 ->getOperands(),
1214 NewScale, SE);
1215 } else {
1216 // A multiplication of a constant with some other value. Update
1217 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001218 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1219 const SCEV *Key = SE.getMulExpr(MulOps);
1220 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001221 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001222 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001223 NewOps.push_back(Pair.first->first);
1224 } else {
1225 Pair.first->second += NewScale;
1226 // The map already had an entry for this value, which may indicate
1227 // a folding opportunity.
1228 Interesting = true;
1229 }
1230 }
1231 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1232 // Pull a buried constant out to the outside.
1233 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1234 Interesting = true;
1235 AccumulatedConstant += Scale * C->getValue()->getValue();
1236 } else {
1237 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001238 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001239 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001240 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001241 NewOps.push_back(Pair.first->first);
1242 } else {
1243 Pair.first->second += Scale;
1244 // The map already had an entry for this value, which may indicate
1245 // a folding opportunity.
1246 Interesting = true;
1247 }
1248 }
1249 }
1250
1251 return Interesting;
1252}
1253
1254namespace {
1255 struct APIntCompare {
1256 bool operator()(const APInt &LHS, const APInt &RHS) const {
1257 return LHS.ult(RHS);
1258 }
1259 };
1260}
1261
Dan Gohman6c0866c2009-05-24 23:45:28 +00001262/// getAddExpr - Get a canonical add expression, or something simpler if
1263/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001264const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1265 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001266 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001267 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001268#ifndef NDEBUG
1269 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1270 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1271 getEffectiveSCEVType(Ops[0]->getType()) &&
1272 "SCEVAddExpr operand types don't match!");
1273#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001274
Dan Gohmana10756e2010-01-21 02:09:26 +00001275 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1276 if (!HasNUW && HasNSW) {
1277 bool All = true;
1278 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1279 if (!isKnownNonNegative(Ops[i])) {
1280 All = false;
1281 break;
1282 }
1283 if (All) HasNUW = true;
1284 }
1285
Chris Lattner53e677a2004-04-02 20:23:17 +00001286 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001287 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001288
1289 // If there are any constants, fold them together.
1290 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001291 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001292 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001293 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001294 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001295 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001296 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1297 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001298 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001299 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001300 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001301 }
1302
1303 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001304 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001305 Ops.erase(Ops.begin());
1306 --Idx;
1307 }
1308 }
1309
Chris Lattner627018b2004-04-07 16:16:11 +00001310 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001311
Chris Lattner53e677a2004-04-02 20:23:17 +00001312 // Okay, check to see if the same value occurs in the operand list twice. If
1313 // so, merge them together into an multiply expression. Since we sorted the
1314 // list, these values are required to be adjacent.
1315 const Type *Ty = Ops[0]->getType();
1316 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1317 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1318 // Found a match, merge the two values into a multiply, and add any
1319 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001320 const SCEV *Two = getIntegerSCEV(2, Ty);
1321 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001322 if (Ops.size() == 2)
1323 return Mul;
1324 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1325 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001326 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001327 }
1328
Dan Gohman728c7f32009-05-08 21:03:19 +00001329 // Check for truncates. If all the operands are truncated from the same
1330 // type, see if factoring out the truncate would permit the result to be
1331 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1332 // if the contents of the resulting outer trunc fold to something simple.
1333 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1334 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1335 const Type *DstType = Trunc->getType();
1336 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001337 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001338 bool Ok = true;
1339 // Check all the operands to see if they can be represented in the
1340 // source type of the truncate.
1341 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1342 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1343 if (T->getOperand()->getType() != SrcType) {
1344 Ok = false;
1345 break;
1346 }
1347 LargeOps.push_back(T->getOperand());
1348 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1349 // This could be either sign or zero extension, but sign extension
1350 // is much more likely to be foldable here.
1351 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1352 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001353 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001354 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1355 if (const SCEVTruncateExpr *T =
1356 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1357 if (T->getOperand()->getType() != SrcType) {
1358 Ok = false;
1359 break;
1360 }
1361 LargeMulOps.push_back(T->getOperand());
1362 } else if (const SCEVConstant *C =
1363 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1364 // This could be either sign or zero extension, but sign extension
1365 // is much more likely to be foldable here.
1366 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1367 } else {
1368 Ok = false;
1369 break;
1370 }
1371 }
1372 if (Ok)
1373 LargeOps.push_back(getMulExpr(LargeMulOps));
1374 } else {
1375 Ok = false;
1376 break;
1377 }
1378 }
1379 if (Ok) {
1380 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001381 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001382 // If it folds to something simple, use it. Otherwise, don't.
1383 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1384 return getTruncateExpr(Fold, DstType);
1385 }
1386 }
1387
1388 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001389 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1390 ++Idx;
1391
1392 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001393 if (Idx < Ops.size()) {
1394 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001395 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 // If we have an add, expand the add operands onto the end of the operands
1397 // list.
1398 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1399 Ops.erase(Ops.begin()+Idx);
1400 DeletedAdd = true;
1401 }
1402
1403 // If we deleted at least one add, we added operands to the end of the list,
1404 // and they are not necessarily sorted. Recurse to resort and resimplify
1405 // any operands we just aquired.
1406 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001407 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001408 }
1409
1410 // Skip over the add expression until we get to a multiply.
1411 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1412 ++Idx;
1413
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001414 // Check to see if there are any folding opportunities present with
1415 // operands multiplied by constant values.
1416 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1417 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001418 DenseMap<const SCEV *, APInt> M;
1419 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001420 APInt AccumulatedConstant(BitWidth, 0);
1421 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1422 Ops, APInt(BitWidth, 1), *this)) {
1423 // Some interesting folding opportunity is present, so its worthwhile to
1424 // re-generate the operands list. Group the operands by constant scale,
1425 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001426 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1427 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001428 E = NewOps.end(); I != E; ++I)
1429 MulOpLists[M.find(*I)->second].push_back(*I);
1430 // Re-generate the operands list.
1431 Ops.clear();
1432 if (AccumulatedConstant != 0)
1433 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001434 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1435 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001436 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001437 Ops.push_back(getMulExpr(getConstant(I->first),
1438 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001439 if (Ops.empty())
1440 return getIntegerSCEV(0, Ty);
1441 if (Ops.size() == 1)
1442 return Ops[0];
1443 return getAddExpr(Ops);
1444 }
1445 }
1446
Chris Lattner53e677a2004-04-02 20:23:17 +00001447 // If we are adding something to a multiply expression, make sure the
1448 // something is not already an operand of the multiply. If so, merge it into
1449 // the multiply.
1450 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001451 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001452 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001453 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001454 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001455 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001456 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001457 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001458 if (Mul->getNumOperands() != 2) {
1459 // If the multiply has more than two operands, we must get the
1460 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001461 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001463 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001464 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001465 const SCEV *One = getIntegerSCEV(1, Ty);
1466 const SCEV *AddOne = getAddExpr(InnerMul, One);
1467 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 if (Ops.size() == 2) return OuterMul;
1469 if (AddOp < Idx) {
1470 Ops.erase(Ops.begin()+AddOp);
1471 Ops.erase(Ops.begin()+Idx-1);
1472 } else {
1473 Ops.erase(Ops.begin()+Idx);
1474 Ops.erase(Ops.begin()+AddOp-1);
1475 }
1476 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001477 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001478 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001479
Chris Lattner53e677a2004-04-02 20:23:17 +00001480 // Check this multiply against other multiplies being added together.
1481 for (unsigned OtherMulIdx = Idx+1;
1482 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1483 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001484 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001485 // If MulOp occurs in OtherMul, we can fold the two multiplies
1486 // together.
1487 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1488 OMulOp != e; ++OMulOp)
1489 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1490 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001491 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001492 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001493 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1494 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001495 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001496 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001497 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001498 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001499 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001500 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1501 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001502 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001503 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001505 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1506 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001507 if (Ops.size() == 2) return OuterMul;
1508 Ops.erase(Ops.begin()+Idx);
1509 Ops.erase(Ops.begin()+OtherMulIdx-1);
1510 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001511 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001512 }
1513 }
1514 }
1515 }
1516
1517 // If there are any add recurrences in the operands list, see if any other
1518 // added values are loop invariant. If so, we can fold them into the
1519 // recurrence.
1520 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1521 ++Idx;
1522
1523 // Scan over all recurrences, trying to fold loop invariants into them.
1524 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1525 // Scan all of the other operands to this add and add them to the vector if
1526 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001527 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001528 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001529 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1530 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1531 LIOps.push_back(Ops[i]);
1532 Ops.erase(Ops.begin()+i);
1533 --i; --e;
1534 }
1535
1536 // If we found some loop invariants, fold them into the recurrence.
1537 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001538 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001539 LIOps.push_back(AddRec->getStart());
1540
Dan Gohman0bba49c2009-07-07 17:06:11 +00001541 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001542 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001543 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001544
Dan Gohman355b4f32009-12-19 01:46:34 +00001545 // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
Dan Gohman59de33e2009-12-18 18:45:31 +00001546 // is not associative so this isn't necessarily safe.
Dan Gohman3a5d4092009-12-18 03:57:04 +00001547 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohman59de33e2009-12-18 18:45:31 +00001548
Chris Lattner53e677a2004-04-02 20:23:17 +00001549 // If all of the other operands were loop invariant, we are done.
1550 if (Ops.size() == 1) return NewRec;
1551
1552 // Otherwise, add the folded AddRec by the non-liv parts.
1553 for (unsigned i = 0;; ++i)
1554 if (Ops[i] == AddRec) {
1555 Ops[i] = NewRec;
1556 break;
1557 }
Dan Gohman246b2562007-10-22 18:31:58 +00001558 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001559 }
1560
1561 // Okay, if there weren't any loop invariants to be folded, check to see if
1562 // there are multiple AddRec's with the same loop induction variable being
1563 // added together. If so, we can fold them.
1564 for (unsigned OtherIdx = Idx+1;
1565 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1566 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001567 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001568 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1569 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001570 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1571 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001572 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1573 if (i >= NewOps.size()) {
1574 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1575 OtherAddRec->op_end());
1576 break;
1577 }
Dan Gohman246b2562007-10-22 18:31:58 +00001578 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001579 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001580 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001581
1582 if (Ops.size() == 2) return NewAddRec;
1583
1584 Ops.erase(Ops.begin()+Idx);
1585 Ops.erase(Ops.begin()+OtherIdx-1);
1586 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001587 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001588 }
1589 }
1590
1591 // Otherwise couldn't fold anything into this recurrence. Move onto the
1592 // next one.
1593 }
1594
1595 // Okay, it looks like we really DO need an add expr. Check to see if we
1596 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001597 FoldingSetNodeID ID;
1598 ID.AddInteger(scAddExpr);
1599 ID.AddInteger(Ops.size());
1600 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1601 ID.AddPointer(Ops[i]);
1602 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001603 SCEVAddExpr *S =
1604 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1605 if (!S) {
1606 S = SCEVAllocator.Allocate<SCEVAddExpr>();
1607 new (S) SCEVAddExpr(ID, Ops);
1608 UniqueSCEVs.InsertNode(S, IP);
1609 }
Dan Gohman3645b012009-10-09 00:10:36 +00001610 if (HasNUW) S->setHasNoUnsignedWrap(true);
1611 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001612 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001613}
1614
Dan Gohman6c0866c2009-05-24 23:45:28 +00001615/// getMulExpr - Get a canonical multiply expression, or something simpler if
1616/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001617const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1618 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001619 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001620 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001621#ifndef NDEBUG
1622 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1623 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1624 getEffectiveSCEVType(Ops[0]->getType()) &&
1625 "SCEVMulExpr operand types don't match!");
1626#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001627
Dan Gohmana10756e2010-01-21 02:09:26 +00001628 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1629 if (!HasNUW && HasNSW) {
1630 bool All = true;
1631 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1632 if (!isKnownNonNegative(Ops[i])) {
1633 All = false;
1634 break;
1635 }
1636 if (All) HasNUW = true;
1637 }
1638
Chris Lattner53e677a2004-04-02 20:23:17 +00001639 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001640 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001641
1642 // If there are any constants, fold them together.
1643 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001644 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001645
1646 // C1*(C2+V) -> C1*C2 + C1*V
1647 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001648 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001649 if (Add->getNumOperands() == 2 &&
1650 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001651 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1652 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001653
Chris Lattner53e677a2004-04-02 20:23:17 +00001654 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001655 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001656 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001657 ConstantInt *Fold = ConstantInt::get(getContext(),
1658 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001659 RHSC->getValue()->getValue());
1660 Ops[0] = getConstant(Fold);
1661 Ops.erase(Ops.begin()+1); // Erase the folded element
1662 if (Ops.size() == 1) return Ops[0];
1663 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001664 }
1665
1666 // If we are left with a constant one being multiplied, strip it off.
1667 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1668 Ops.erase(Ops.begin());
1669 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001670 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001671 // If we have a multiply of zero, it will always be zero.
1672 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001673 } else if (Ops[0]->isAllOnesValue()) {
1674 // If we have a mul by -1 of an add, try distributing the -1 among the
1675 // add operands.
1676 if (Ops.size() == 2)
1677 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1678 SmallVector<const SCEV *, 4> NewOps;
1679 bool AnyFolded = false;
1680 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1681 I != E; ++I) {
1682 const SCEV *Mul = getMulExpr(Ops[0], *I);
1683 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1684 NewOps.push_back(Mul);
1685 }
1686 if (AnyFolded)
1687 return getAddExpr(NewOps);
1688 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001689 }
1690 }
1691
1692 // Skip over the add expression until we get to a multiply.
1693 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1694 ++Idx;
1695
1696 if (Ops.size() == 1)
1697 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001698
Chris Lattner53e677a2004-04-02 20:23:17 +00001699 // If there are mul operands inline them all into this expression.
1700 if (Idx < Ops.size()) {
1701 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001702 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001703 // If we have an mul, expand the mul operands onto the end of the operands
1704 // list.
1705 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1706 Ops.erase(Ops.begin()+Idx);
1707 DeletedMul = true;
1708 }
1709
1710 // If we deleted at least one mul, we added operands to the end of the list,
1711 // and they are not necessarily sorted. Recurse to resort and resimplify
1712 // any operands we just aquired.
1713 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001714 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001715 }
1716
1717 // If there are any add recurrences in the operands list, see if any other
1718 // added values are loop invariant. If so, we can fold them into the
1719 // recurrence.
1720 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1721 ++Idx;
1722
1723 // Scan over all recurrences, trying to fold loop invariants into them.
1724 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1725 // Scan all of the other operands to this mul and add them to the vector if
1726 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001727 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001728 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001729 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1730 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1731 LIOps.push_back(Ops[i]);
1732 Ops.erase(Ops.begin()+i);
1733 --i; --e;
1734 }
1735
1736 // If we found some loop invariants, fold them into the recurrence.
1737 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001738 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001739 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001740 NewOps.reserve(AddRec->getNumOperands());
1741 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001742 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001743 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001744 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001745 } else {
1746 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001747 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001748 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001749 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001750 }
1751 }
1752
Dan Gohman355b4f32009-12-19 01:46:34 +00001753 // It's tempting to propagate the NSW flag here, but nsw multiplication
Dan Gohman59de33e2009-12-18 18:45:31 +00001754 // is not associative so this isn't necessarily safe.
Dan Gohmana10756e2010-01-21 02:09:26 +00001755 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1756 HasNUW && AddRec->hasNoUnsignedWrap(),
1757 /*HasNSW=*/false);
Chris Lattner53e677a2004-04-02 20:23:17 +00001758
1759 // If all of the other operands were loop invariant, we are done.
1760 if (Ops.size() == 1) return NewRec;
1761
1762 // Otherwise, multiply the folded AddRec by the non-liv parts.
1763 for (unsigned i = 0;; ++i)
1764 if (Ops[i] == AddRec) {
1765 Ops[i] = NewRec;
1766 break;
1767 }
Dan Gohman246b2562007-10-22 18:31:58 +00001768 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001769 }
1770
1771 // Okay, if there weren't any loop invariants to be folded, check to see if
1772 // there are multiple AddRec's with the same loop induction variable being
1773 // multiplied together. If so, we can fold them.
1774 for (unsigned OtherIdx = Idx+1;
1775 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1776 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001777 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001778 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1779 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001780 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001781 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001782 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001783 const SCEV *B = F->getStepRecurrence(*this);
1784 const SCEV *D = G->getStepRecurrence(*this);
1785 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001786 getMulExpr(G, B),
1787 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001788 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001789 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001790 if (Ops.size() == 2) return NewAddRec;
1791
1792 Ops.erase(Ops.begin()+Idx);
1793 Ops.erase(Ops.begin()+OtherIdx-1);
1794 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001795 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001796 }
1797 }
1798
1799 // Otherwise couldn't fold anything into this recurrence. Move onto the
1800 // next one.
1801 }
1802
1803 // Okay, it looks like we really DO need an mul expr. Check to see if we
1804 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001805 FoldingSetNodeID ID;
1806 ID.AddInteger(scMulExpr);
1807 ID.AddInteger(Ops.size());
1808 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1809 ID.AddPointer(Ops[i]);
1810 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001811 SCEVMulExpr *S =
1812 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1813 if (!S) {
1814 S = SCEVAllocator.Allocate<SCEVMulExpr>();
1815 new (S) SCEVMulExpr(ID, Ops);
1816 UniqueSCEVs.InsertNode(S, IP);
1817 }
Dan Gohman3645b012009-10-09 00:10:36 +00001818 if (HasNUW) S->setHasNoUnsignedWrap(true);
1819 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001820 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001821}
1822
Andreas Bolka8a11c982009-08-07 22:55:26 +00001823/// getUDivExpr - Get a canonical unsigned division expression, or something
1824/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001825const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1826 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001827 assert(getEffectiveSCEVType(LHS->getType()) ==
1828 getEffectiveSCEVType(RHS->getType()) &&
1829 "SCEVUDivExpr operand types don't match!");
1830
Dan Gohman622ed672009-05-04 22:02:23 +00001831 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001832 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001833 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001834 if (RHSC->isZero())
1835 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001836
Dan Gohman185cf032009-05-08 20:18:49 +00001837 // Determine if the division can be folded into the operands of
1838 // its operands.
1839 // TODO: Generalize this to non-constants by using known-bits information.
1840 const Type *Ty = LHS->getType();
1841 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1842 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1843 // For non-power-of-two values, effectively round the value up to the
1844 // nearest power of two.
1845 if (!RHSC->getValue()->getValue().isPowerOf2())
1846 ++MaxShiftAmt;
1847 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001848 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001849 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1850 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1851 if (const SCEVConstant *Step =
1852 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1853 if (!Step->getValue()->getValue()
1854 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001855 getZeroExtendExpr(AR, ExtTy) ==
1856 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1857 getZeroExtendExpr(Step, ExtTy),
1858 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001859 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001860 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1861 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1862 return getAddRecExpr(Operands, AR->getLoop());
1863 }
1864 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001865 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001866 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001867 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1868 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1869 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001870 // Find an operand that's safely divisible.
1871 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001872 const SCEV *Op = M->getOperand(i);
1873 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001874 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001875 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1876 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001877 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001878 Operands[i] = Div;
1879 return getMulExpr(Operands);
1880 }
1881 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001882 }
Dan Gohman185cf032009-05-08 20:18:49 +00001883 // (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 +00001884 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001885 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001886 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1887 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1888 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1889 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001890 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001891 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001892 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1893 break;
1894 Operands.push_back(Op);
1895 }
1896 if (Operands.size() == A->getNumOperands())
1897 return getAddExpr(Operands);
1898 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001899 }
Dan Gohman185cf032009-05-08 20:18:49 +00001900
1901 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001902 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001903 Constant *LHSCV = LHSC->getValue();
1904 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001905 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001906 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001907 }
1908 }
1909
Dan Gohman1c343752009-06-27 21:21:31 +00001910 FoldingSetNodeID ID;
1911 ID.AddInteger(scUDivExpr);
1912 ID.AddPointer(LHS);
1913 ID.AddPointer(RHS);
1914 void *IP = 0;
1915 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1916 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001917 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001918 UniqueSCEVs.InsertNode(S, IP);
1919 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001920}
1921
1922
Dan Gohman6c0866c2009-05-24 23:45:28 +00001923/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1924/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001925const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001926 const SCEV *Step, const Loop *L,
1927 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001928 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001929 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001930 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001931 if (StepChrec->getLoop() == L) {
1932 Operands.insert(Operands.end(), StepChrec->op_begin(),
1933 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001934 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001935 }
1936
1937 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001938 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001939}
1940
Dan Gohman6c0866c2009-05-24 23:45:28 +00001941/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1942/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001943const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001944ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001945 const Loop *L,
1946 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001947 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001948#ifndef NDEBUG
1949 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1950 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1951 getEffectiveSCEVType(Operands[0]->getType()) &&
1952 "SCEVAddRecExpr operand types don't match!");
1953#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001954
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001955 if (Operands.back()->isZero()) {
1956 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001957 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001958 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001959
Dan Gohmana10756e2010-01-21 02:09:26 +00001960 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1961 if (!HasNUW && HasNSW) {
1962 bool All = true;
1963 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1964 if (!isKnownNonNegative(Operands[i])) {
1965 All = false;
1966 break;
1967 }
1968 if (All) HasNUW = true;
1969 }
1970
Dan Gohmand9cc7492008-08-08 18:33:12 +00001971 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001972 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001973 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmana10756e2010-01-21 02:09:26 +00001974 if (L->contains(NestedLoop->getHeader()) ?
1975 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
1976 (!NestedLoop->contains(L->getHeader()) &&
1977 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001978 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001979 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001980 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001981 // AddRecs require their operands be loop-invariant with respect to their
1982 // loops. Don't perform this transformation if it would break this
1983 // requirement.
1984 bool AllInvariant = true;
1985 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1986 if (!Operands[i]->isLoopInvariant(L)) {
1987 AllInvariant = false;
1988 break;
1989 }
1990 if (AllInvariant) {
1991 NestedOperands[0] = getAddRecExpr(Operands, L);
1992 AllInvariant = true;
1993 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1994 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1995 AllInvariant = false;
1996 break;
1997 }
1998 if (AllInvariant)
1999 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002000 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002001 }
2002 // Reset Operands to its original state.
2003 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002004 }
2005 }
2006
Dan Gohman67847532010-01-19 22:27:22 +00002007 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2008 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002009 FoldingSetNodeID ID;
2010 ID.AddInteger(scAddRecExpr);
2011 ID.AddInteger(Operands.size());
2012 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2013 ID.AddPointer(Operands[i]);
2014 ID.AddPointer(L);
2015 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002016 SCEVAddRecExpr *S =
2017 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2018 if (!S) {
2019 S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
2020 new (S) SCEVAddRecExpr(ID, Operands, L);
2021 UniqueSCEVs.InsertNode(S, IP);
2022 }
Dan Gohman3645b012009-10-09 00:10:36 +00002023 if (HasNUW) S->setHasNoUnsignedWrap(true);
2024 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002025 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002026}
2027
Dan Gohman9311ef62009-06-24 14:49:00 +00002028const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2029 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002030 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002031 Ops.push_back(LHS);
2032 Ops.push_back(RHS);
2033 return getSMaxExpr(Ops);
2034}
2035
Dan Gohman0bba49c2009-07-07 17:06:11 +00002036const SCEV *
2037ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002038 assert(!Ops.empty() && "Cannot get empty smax!");
2039 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002040#ifndef NDEBUG
2041 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2042 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2043 getEffectiveSCEVType(Ops[0]->getType()) &&
2044 "SCEVSMaxExpr operand types don't match!");
2045#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002046
2047 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002048 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002049
2050 // If there are any constants, fold them together.
2051 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002052 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002053 ++Idx;
2054 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002055 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002056 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002057 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002058 APIntOps::smax(LHSC->getValue()->getValue(),
2059 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002060 Ops[0] = getConstant(Fold);
2061 Ops.erase(Ops.begin()+1); // Erase the folded element
2062 if (Ops.size() == 1) return Ops[0];
2063 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002064 }
2065
Dan Gohmane5aceed2009-06-24 14:46:22 +00002066 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002067 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2068 Ops.erase(Ops.begin());
2069 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002070 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2071 // If we have an smax with a constant maximum-int, it will always be
2072 // maximum-int.
2073 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002074 }
2075 }
2076
2077 if (Ops.size() == 1) return Ops[0];
2078
2079 // Find the first SMax
2080 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2081 ++Idx;
2082
2083 // Check to see if one of the operands is an SMax. If so, expand its operands
2084 // onto our operand list, and recurse to simplify.
2085 if (Idx < Ops.size()) {
2086 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002087 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002088 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
2089 Ops.erase(Ops.begin()+Idx);
2090 DeletedSMax = true;
2091 }
2092
2093 if (DeletedSMax)
2094 return getSMaxExpr(Ops);
2095 }
2096
2097 // Okay, check to see if the same value occurs in the operand list twice. If
2098 // so, delete one. Since we sorted the list, these values are required to
2099 // be adjacent.
2100 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2101 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
2102 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2103 --i; --e;
2104 }
2105
2106 if (Ops.size() == 1) return Ops[0];
2107
2108 assert(!Ops.empty() && "Reduced smax down to nothing!");
2109
Nick Lewycky3e630762008-02-20 06:48:22 +00002110 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002111 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002112 FoldingSetNodeID ID;
2113 ID.AddInteger(scSMaxExpr);
2114 ID.AddInteger(Ops.size());
2115 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2116 ID.AddPointer(Ops[i]);
2117 void *IP = 0;
2118 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2119 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002120 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002121 UniqueSCEVs.InsertNode(S, IP);
2122 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002123}
2124
Dan Gohman9311ef62009-06-24 14:49:00 +00002125const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2126 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002127 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002128 Ops.push_back(LHS);
2129 Ops.push_back(RHS);
2130 return getUMaxExpr(Ops);
2131}
2132
Dan Gohman0bba49c2009-07-07 17:06:11 +00002133const SCEV *
2134ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002135 assert(!Ops.empty() && "Cannot get empty umax!");
2136 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002137#ifndef NDEBUG
2138 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2139 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2140 getEffectiveSCEVType(Ops[0]->getType()) &&
2141 "SCEVUMaxExpr operand types don't match!");
2142#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002143
2144 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002145 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002146
2147 // If there are any constants, fold them together.
2148 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002149 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002150 ++Idx;
2151 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002152 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002153 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002154 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002155 APIntOps::umax(LHSC->getValue()->getValue(),
2156 RHSC->getValue()->getValue()));
2157 Ops[0] = getConstant(Fold);
2158 Ops.erase(Ops.begin()+1); // Erase the folded element
2159 if (Ops.size() == 1) return Ops[0];
2160 LHSC = cast<SCEVConstant>(Ops[0]);
2161 }
2162
Dan Gohmane5aceed2009-06-24 14:46:22 +00002163 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002164 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2165 Ops.erase(Ops.begin());
2166 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002167 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2168 // If we have an umax with a constant maximum-int, it will always be
2169 // maximum-int.
2170 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002171 }
2172 }
2173
2174 if (Ops.size() == 1) return Ops[0];
2175
2176 // Find the first UMax
2177 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2178 ++Idx;
2179
2180 // Check to see if one of the operands is a UMax. If so, expand its operands
2181 // onto our operand list, and recurse to simplify.
2182 if (Idx < Ops.size()) {
2183 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002184 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002185 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2186 Ops.erase(Ops.begin()+Idx);
2187 DeletedUMax = true;
2188 }
2189
2190 if (DeletedUMax)
2191 return getUMaxExpr(Ops);
2192 }
2193
2194 // Okay, check to see if the same value occurs in the operand list twice. If
2195 // so, delete one. Since we sorted the list, these values are required to
2196 // be adjacent.
2197 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2198 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2199 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2200 --i; --e;
2201 }
2202
2203 if (Ops.size() == 1) return Ops[0];
2204
2205 assert(!Ops.empty() && "Reduced umax down to nothing!");
2206
2207 // Okay, it looks like we really DO need a umax expr. Check to see if we
2208 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002209 FoldingSetNodeID ID;
2210 ID.AddInteger(scUMaxExpr);
2211 ID.AddInteger(Ops.size());
2212 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2213 ID.AddPointer(Ops[i]);
2214 void *IP = 0;
2215 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2216 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002217 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002218 UniqueSCEVs.InsertNode(S, IP);
2219 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002220}
2221
Dan Gohman9311ef62009-06-24 14:49:00 +00002222const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2223 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002224 // ~smax(~x, ~y) == smin(x, y).
2225 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2226}
2227
Dan Gohman9311ef62009-06-24 14:49:00 +00002228const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2229 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002230 // ~umax(~x, ~y) == umin(x, y)
2231 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2232}
2233
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002234const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2235 unsigned FieldNo) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00002236 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2237 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2238 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002239 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002240 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002241}
2242
2243const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +00002244 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2245 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2246 C = ConstantFoldConstantExpression(CE, TD);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002247 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002248 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002249}
2250
Dan Gohman0bba49c2009-07-07 17:06:11 +00002251const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002252 // Don't attempt to do anything other than create a SCEVUnknown object
2253 // here. createSCEV only calls getUnknown after checking for all other
2254 // interesting possibilities, and any other code that calls getUnknown
2255 // is doing so in order to hide a value from SCEV canonicalization.
2256
Dan Gohman1c343752009-06-27 21:21:31 +00002257 FoldingSetNodeID ID;
2258 ID.AddInteger(scUnknown);
2259 ID.AddPointer(V);
2260 void *IP = 0;
2261 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2262 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002263 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002264 UniqueSCEVs.InsertNode(S, IP);
2265 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002266}
2267
Chris Lattner53e677a2004-04-02 20:23:17 +00002268//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002269// Basic SCEV Analysis and PHI Idiom Recognition Code
2270//
2271
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002272/// isSCEVable - Test if values of the given type are analyzable within
2273/// the SCEV framework. This primarily includes integer types, and it
2274/// can optionally include pointer types if the ScalarEvolution class
2275/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002276bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002277 // Integers and pointers are always SCEVable.
2278 return Ty->isInteger() || isa<PointerType>(Ty);
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002279}
2280
2281/// getTypeSizeInBits - Return the size in bits of the specified type,
2282/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002283uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002284 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2285
2286 // If we have a TargetData, use it!
2287 if (TD)
2288 return TD->getTypeSizeInBits(Ty);
2289
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002290 // Integer types have fixed sizes.
2291 if (Ty->isInteger())
2292 return Ty->getPrimitiveSizeInBits();
2293
2294 // The only other support type is pointer. Without TargetData, conservatively
2295 // assume pointers are 64-bit.
2296 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2297 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002298}
2299
2300/// getEffectiveSCEVType - Return a type with the same bitwidth as
2301/// the given type and which represents how SCEV will treat the given
2302/// type, for which isSCEVable must return true. For pointer types,
2303/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002304const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002305 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2306
2307 if (Ty->isInteger())
2308 return Ty;
2309
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002310 // The only other support type is pointer.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002311 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002312 if (TD) return TD->getIntPtrType(getContext());
2313
2314 // Without TargetData, conservatively assume pointers are 64-bit.
2315 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002316}
Chris Lattner53e677a2004-04-02 20:23:17 +00002317
Dan Gohman0bba49c2009-07-07 17:06:11 +00002318const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002319 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002320}
2321
Chris Lattner53e677a2004-04-02 20:23:17 +00002322/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2323/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002324const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002325 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002326
Dan Gohman0bba49c2009-07-07 17:06:11 +00002327 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002328 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002329 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002330 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002331 return S;
2332}
2333
Dan Gohman6bbcba12009-06-24 00:54:57 +00002334/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002335/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002336const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002337 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002338 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002339}
2340
2341/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2342///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002343const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002344 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002345 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002346 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002347
2348 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002349 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002350 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002351 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002352}
2353
2354/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002355const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002356 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002357 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002358 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002359
2360 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002361 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002362 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002363 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002364 return getMinusSCEV(AllOnes, V);
2365}
2366
2367/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2368///
Dan Gohman9311ef62009-06-24 14:49:00 +00002369const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2370 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002371 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002372 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002373}
2374
2375/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2376/// input value to the specified type. If the type must be extended, it is zero
2377/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002378const SCEV *
2379ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002380 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002381 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002382 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2383 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002384 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002385 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002386 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002387 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002388 return getTruncateExpr(V, Ty);
2389 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002390}
2391
2392/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2393/// input value to the specified type. If the type must be extended, it is sign
2394/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002395const SCEV *
2396ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002397 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002398 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002399 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2400 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002401 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002402 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002403 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002404 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002405 return getTruncateExpr(V, Ty);
2406 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002407}
2408
Dan Gohman467c4302009-05-13 03:46:30 +00002409/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2410/// input value to the specified type. If the type must be extended, it is zero
2411/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002412const SCEV *
2413ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002414 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002415 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2416 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002417 "Cannot noop or zero extend with non-integer arguments!");
2418 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2419 "getNoopOrZeroExtend cannot truncate!");
2420 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2421 return V; // No conversion
2422 return getZeroExtendExpr(V, Ty);
2423}
2424
2425/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2426/// input value to the specified type. If the type must be extended, it is sign
2427/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002428const SCEV *
2429ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002430 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002431 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2432 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002433 "Cannot noop or sign extend with non-integer arguments!");
2434 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2435 "getNoopOrSignExtend cannot truncate!");
2436 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2437 return V; // No conversion
2438 return getSignExtendExpr(V, Ty);
2439}
2440
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002441/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2442/// the input value to the specified type. If the type must be extended,
2443/// it is extended with unspecified bits. The conversion must not be
2444/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002445const SCEV *
2446ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002447 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002448 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2449 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002450 "Cannot noop or any extend with non-integer arguments!");
2451 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2452 "getNoopOrAnyExtend cannot truncate!");
2453 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2454 return V; // No conversion
2455 return getAnyExtendExpr(V, Ty);
2456}
2457
Dan Gohman467c4302009-05-13 03:46:30 +00002458/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2459/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002460const SCEV *
2461ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002462 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002463 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2464 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002465 "Cannot truncate or noop with non-integer arguments!");
2466 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2467 "getTruncateOrNoop cannot extend!");
2468 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2469 return V; // No conversion
2470 return getTruncateExpr(V, Ty);
2471}
2472
Dan Gohmana334aa72009-06-22 00:31:57 +00002473/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2474/// the types using zero-extension, and then perform a umax operation
2475/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002476const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2477 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002478 const SCEV *PromotedLHS = LHS;
2479 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002480
2481 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2482 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2483 else
2484 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2485
2486 return getUMaxExpr(PromotedLHS, PromotedRHS);
2487}
2488
Dan Gohmanc9759e82009-06-22 15:03:27 +00002489/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2490/// the types using zero-extension, and then perform a umin operation
2491/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002492const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2493 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002494 const SCEV *PromotedLHS = LHS;
2495 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002496
2497 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2498 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2499 else
2500 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2501
2502 return getUMinExpr(PromotedLHS, PromotedRHS);
2503}
2504
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002505/// PushDefUseChildren - Push users of the given Instruction
2506/// onto the given Worklist.
2507static void
2508PushDefUseChildren(Instruction *I,
2509 SmallVectorImpl<Instruction *> &Worklist) {
2510 // Push the def-use children onto the Worklist stack.
2511 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2512 UI != UE; ++UI)
2513 Worklist.push_back(cast<Instruction>(UI));
2514}
2515
2516/// ForgetSymbolicValue - This looks up computed SCEV values for all
2517/// instructions that depend on the given instruction and removes them from
2518/// the Scalars map if they reference SymName. This is used during PHI
2519/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002520void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002521ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2522 SmallVector<Instruction *, 16> Worklist;
2523 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002524
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002525 SmallPtrSet<Instruction *, 8> Visited;
2526 Visited.insert(I);
2527 while (!Worklist.empty()) {
2528 Instruction *I = Worklist.pop_back_val();
2529 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002530
Dan Gohman5d984912009-12-18 01:14:11 +00002531 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002532 Scalars.find(static_cast<Value *>(I));
2533 if (It != Scalars.end()) {
2534 // Short-circuit the def-use traversal if the symbolic name
2535 // ceases to appear in expressions.
2536 if (!It->second->hasOperand(SymName))
2537 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002538
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002539 // SCEVUnknown for a PHI either means that it has an unrecognized
2540 // structure, or it's a PHI that's in the progress of being computed
2541 // by createNodeForPHI. In the former case, additional loop trip
2542 // count information isn't going to change anything. In the later
2543 // case, createNodeForPHI will perform the necessary updates on its
2544 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00002545 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2546 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002547 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002548 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002549 }
2550
2551 PushDefUseChildren(I, Worklist);
2552 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002553}
Chris Lattner53e677a2004-04-02 20:23:17 +00002554
2555/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2556/// a loop header, making it a potential recurrence, or it doesn't.
2557///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002558const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002559 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002560 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002561 if (L->getHeader() == PN->getParent()) {
2562 // If it lives in the loop header, it has two incoming values, one
2563 // from outside the loop, and one from inside.
2564 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2565 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002566
Chris Lattner53e677a2004-04-02 20:23:17 +00002567 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002568 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002569 assert(Scalars.find(PN) == Scalars.end() &&
2570 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002571 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002572
2573 // Using this symbolic name for the PHI, analyze the value coming around
2574 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002575 Value *BEValueV = PN->getIncomingValue(BackEdge);
2576 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002577
2578 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2579 // has a special value for the first iteration of the loop.
2580
2581 // If the value coming around the backedge is an add with the symbolic
2582 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002583 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002584 // If there is a single occurrence of the symbolic value, replace it
2585 // with a recurrence.
2586 unsigned FoundIndex = Add->getNumOperands();
2587 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2588 if (Add->getOperand(i) == SymbolicName)
2589 if (FoundIndex == e) {
2590 FoundIndex = i;
2591 break;
2592 }
2593
2594 if (FoundIndex != Add->getNumOperands()) {
2595 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002596 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002597 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2598 if (i != FoundIndex)
2599 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002600 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002601
2602 // This is not a valid addrec if the step amount is varying each
2603 // loop iteration, but is not itself an addrec in this loop.
2604 if (Accum->isLoopInvariant(L) ||
2605 (isa<SCEVAddRecExpr>(Accum) &&
2606 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002607 bool HasNUW = false;
2608 bool HasNSW = false;
2609
2610 // If the increment doesn't overflow, then neither the addrec nor
2611 // the post-increment will overflow.
2612 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2613 if (OBO->hasNoUnsignedWrap())
2614 HasNUW = true;
2615 if (OBO->hasNoSignedWrap())
2616 HasNSW = true;
2617 }
2618
Dan Gohman64a845e2009-06-24 04:48:43 +00002619 const SCEV *StartVal =
2620 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmana10756e2010-01-21 02:09:26 +00002621 const SCEV *PHISCEV =
2622 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002623
Dan Gohmana10756e2010-01-21 02:09:26 +00002624 // Since the no-wrap flags are on the increment, they apply to the
2625 // post-incremented value as well.
2626 if (Accum->isLoopInvariant(L))
2627 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2628 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002629
2630 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002631 // to be symbolic. We now need to go back and purge all of the
2632 // entries for the scalars that use the symbolic expression.
2633 ForgetSymbolicName(PN, SymbolicName);
2634 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002635 return PHISCEV;
2636 }
2637 }
Dan Gohman622ed672009-05-04 22:02:23 +00002638 } else if (const SCEVAddRecExpr *AddRec =
2639 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002640 // Otherwise, this could be a loop like this:
2641 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2642 // In this case, j = {1,+,1} and BEValue is j.
2643 // Because the other in-value of i (0) fits the evolution of BEValue
2644 // i really is an addrec evolution.
2645 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002646 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002647
2648 // If StartVal = j.start - j.stride, we can use StartVal as the
2649 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002650 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002651 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002652 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002653 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002654
2655 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002656 // to be symbolic. We now need to go back and purge all of the
2657 // entries for the scalars that use the symbolic expression.
2658 ForgetSymbolicName(PN, SymbolicName);
2659 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002660 return PHISCEV;
2661 }
2662 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002663 }
2664
2665 return SymbolicName;
2666 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002667
Dan Gohmana653fc52009-07-14 14:06:25 +00002668 // It's tempting to recognize PHIs with a unique incoming value, however
2669 // this leads passes like indvars to break LCSSA form. Fortunately, such
2670 // PHIs are rare, as instcombine zaps them.
2671
Chris Lattner53e677a2004-04-02 20:23:17 +00002672 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002673 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002674}
2675
Dan Gohman26466c02009-05-08 20:26:55 +00002676/// createNodeForGEP - Expand GEP instructions into add and multiply
2677/// operations. This allows them to be analyzed by regular SCEV code.
2678///
Dan Gohmand281ed22009-12-18 02:09:29 +00002679const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002680
Dan Gohmand281ed22009-12-18 02:09:29 +00002681 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002682 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002683 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002684 // Don't attempt to analyze GEPs over unsized objects.
2685 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2686 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002687 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002688 gep_type_iterator GTI = gep_type_begin(GEP);
2689 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2690 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002691 I != E; ++I) {
2692 Value *Index = *I;
2693 // Compute the (potentially symbolic) offset in bytes for this index.
2694 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2695 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002696 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002697 TotalOffset = getAddExpr(TotalOffset,
Dan Gohmand281ed22009-12-18 02:09:29 +00002698 getFieldOffsetExpr(STy, FieldNo),
2699 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002700 } else {
2701 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002702 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002703 if (!isa<PointerType>(LocalOffset->getType()))
2704 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002705 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002706 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohmand281ed22009-12-18 02:09:29 +00002707 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI),
2708 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2709 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2710 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002711 }
2712 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002713 return getAddExpr(getSCEV(Base), TotalOffset,
2714 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002715}
2716
Nick Lewycky83bb0052007-11-22 07:59:40 +00002717/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2718/// guaranteed to end in (at every loop iteration). It is, at the same time,
2719/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2720/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002721uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002722ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002723 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002724 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002725
Dan Gohman622ed672009-05-04 22:02:23 +00002726 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002727 return std::min(GetMinTrailingZeros(T->getOperand()),
2728 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002729
Dan Gohman622ed672009-05-04 22:02:23 +00002730 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002731 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2732 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2733 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002734 }
2735
Dan Gohman622ed672009-05-04 22:02:23 +00002736 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002737 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2738 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2739 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002740 }
2741
Dan Gohman622ed672009-05-04 22:02:23 +00002742 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002743 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002744 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002745 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002746 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002747 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002748 }
2749
Dan Gohman622ed672009-05-04 22:02:23 +00002750 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002751 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002752 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2753 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002754 for (unsigned i = 1, e = M->getNumOperands();
2755 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002756 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002757 BitWidth);
2758 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002759 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002760
Dan Gohman622ed672009-05-04 22:02:23 +00002761 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002762 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002763 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002764 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002765 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002766 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002767 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002768
Dan Gohman622ed672009-05-04 22:02:23 +00002769 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002770 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002771 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002772 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002773 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002774 return MinOpRes;
2775 }
2776
Dan Gohman622ed672009-05-04 22:02:23 +00002777 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002778 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002779 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002780 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002781 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002782 return MinOpRes;
2783 }
2784
Dan Gohman2c364ad2009-06-19 23:29:04 +00002785 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2786 // For a SCEVUnknown, ask ValueTracking.
2787 unsigned BitWidth = getTypeSizeInBits(U->getType());
2788 APInt Mask = APInt::getAllOnesValue(BitWidth);
2789 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2790 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2791 return Zeros.countTrailingOnes();
2792 }
2793
2794 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002795 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002796}
Chris Lattner53e677a2004-04-02 20:23:17 +00002797
Dan Gohman85b05a22009-07-13 21:35:55 +00002798/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2799///
2800ConstantRange
2801ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002802
2803 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002804 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002805
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002806 unsigned BitWidth = getTypeSizeInBits(S->getType());
2807 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2808
2809 // If the value has known zeros, the maximum unsigned value will have those
2810 // known zeros as well.
2811 uint32_t TZ = GetMinTrailingZeros(S);
2812 if (TZ != 0)
2813 ConservativeResult =
2814 ConstantRange(APInt::getMinValue(BitWidth),
2815 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2816
Dan Gohman85b05a22009-07-13 21:35:55 +00002817 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2818 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2819 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2820 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002821 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002822 }
2823
2824 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2825 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2826 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2827 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002828 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002829 }
2830
2831 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2832 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2833 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2834 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002835 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002836 }
2837
2838 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2839 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2840 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2841 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002842 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002843 }
2844
2845 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2846 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2847 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002848 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002849 }
2850
2851 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2852 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002853 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002854 }
2855
2856 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2857 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002858 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002859 }
2860
2861 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2862 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002863 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002864 }
2865
Dan Gohman85b05a22009-07-13 21:35:55 +00002866 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002867 // If there's no unsigned wrap, the value will never be less than its
2868 // initial value.
2869 if (AddRec->hasNoUnsignedWrap())
2870 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
2871 ConservativeResult =
2872 ConstantRange(C->getValue()->getValue(),
2873 APInt(getTypeSizeInBits(C->getType()), 0));
Dan Gohman85b05a22009-07-13 21:35:55 +00002874
2875 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002876 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002877 const Type *Ty = AddRec->getType();
2878 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002879 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
2880 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002881 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2882
2883 const SCEV *Start = AddRec->getStart();
2884 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2885
2886 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00002887 if (!AddRec->hasNoUnsignedWrap())
2888 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00002889
2890 ConstantRange StartRange = getUnsignedRange(Start);
2891 ConstantRange EndRange = getUnsignedRange(End);
2892 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2893 EndRange.getUnsignedMin());
2894 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2895 EndRange.getUnsignedMax());
2896 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00002897 return ConservativeResult;
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002898 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman85b05a22009-07-13 21:35:55 +00002899 }
2900 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002901
2902 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002903 }
2904
2905 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2906 // For a SCEVUnknown, ask ValueTracking.
2907 unsigned BitWidth = getTypeSizeInBits(U->getType());
2908 APInt Mask = APInt::getAllOnesValue(BitWidth);
2909 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2910 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002911 if (Ones == ~Zeros + 1)
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002912 return ConservativeResult;
2913 return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002914 }
2915
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002916 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002917}
2918
Dan Gohman85b05a22009-07-13 21:35:55 +00002919/// getSignedRange - Determine the signed range for a particular SCEV.
2920///
2921ConstantRange
2922ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002923
Dan Gohman85b05a22009-07-13 21:35:55 +00002924 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2925 return ConstantRange(C->getValue()->getValue());
2926
Dan Gohman52fddd32010-01-26 04:40:18 +00002927 unsigned BitWidth = getTypeSizeInBits(S->getType());
2928 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2929
2930 // If the value has known zeros, the maximum signed value will have those
2931 // known zeros as well.
2932 uint32_t TZ = GetMinTrailingZeros(S);
2933 if (TZ != 0)
2934 ConservativeResult =
2935 ConstantRange(APInt::getSignedMinValue(BitWidth),
2936 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
2937
Dan Gohman85b05a22009-07-13 21:35:55 +00002938 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2939 ConstantRange X = getSignedRange(Add->getOperand(0));
2940 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2941 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002942 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002943 }
2944
Dan Gohman85b05a22009-07-13 21:35:55 +00002945 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2946 ConstantRange X = getSignedRange(Mul->getOperand(0));
2947 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2948 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002949 return ConservativeResult.intersectWith(X);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002950 }
2951
Dan Gohman85b05a22009-07-13 21:35:55 +00002952 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2953 ConstantRange X = getSignedRange(SMax->getOperand(0));
2954 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2955 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002956 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002957 }
Dan Gohman62849c02009-06-24 01:05:09 +00002958
Dan Gohman85b05a22009-07-13 21:35:55 +00002959 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2960 ConstantRange X = getSignedRange(UMax->getOperand(0));
2961 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2962 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman52fddd32010-01-26 04:40:18 +00002963 return ConservativeResult.intersectWith(X);
Dan Gohman85b05a22009-07-13 21:35:55 +00002964 }
Dan Gohman62849c02009-06-24 01:05:09 +00002965
Dan Gohman85b05a22009-07-13 21:35:55 +00002966 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2967 ConstantRange X = getSignedRange(UDiv->getLHS());
2968 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman52fddd32010-01-26 04:40:18 +00002969 return ConservativeResult.intersectWith(X.udiv(Y));
Dan Gohman85b05a22009-07-13 21:35:55 +00002970 }
Dan Gohman62849c02009-06-24 01:05:09 +00002971
Dan Gohman85b05a22009-07-13 21:35:55 +00002972 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2973 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002974 return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002975 }
2976
2977 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2978 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002979 return ConservativeResult.intersectWith(X.signExtend(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002980 }
2981
2982 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2983 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman52fddd32010-01-26 04:40:18 +00002984 return ConservativeResult.intersectWith(X.truncate(BitWidth));
Dan Gohman85b05a22009-07-13 21:35:55 +00002985 }
2986
Dan Gohman85b05a22009-07-13 21:35:55 +00002987 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002988 // If there's no signed wrap, and all the operands have the same sign or
2989 // zero, the value won't ever change sign.
2990 if (AddRec->hasNoSignedWrap()) {
2991 bool AllNonNeg = true;
2992 bool AllNonPos = true;
2993 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
2994 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
2995 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
2996 }
Dan Gohmana10756e2010-01-21 02:09:26 +00002997 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00002998 ConservativeResult = ConservativeResult.intersectWith(
2999 ConstantRange(APInt(BitWidth, 0),
3000 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003001 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003002 ConservativeResult = ConservativeResult.intersectWith(
3003 ConstantRange(APInt::getSignedMinValue(BitWidth),
3004 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003005 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003006
3007 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003008 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003009 const Type *Ty = AddRec->getType();
3010 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003011 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3012 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003013 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3014
3015 const SCEV *Start = AddRec->getStart();
Dan Gohman85b05a22009-07-13 21:35:55 +00003016 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
3017
3018 // Check for overflow.
Dan Gohmana10756e2010-01-21 02:09:26 +00003019 if (!AddRec->hasNoSignedWrap())
3020 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003021
3022 ConstantRange StartRange = getSignedRange(Start);
3023 ConstantRange EndRange = getSignedRange(End);
3024 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3025 EndRange.getSignedMin());
3026 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3027 EndRange.getSignedMax());
3028 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmana10756e2010-01-21 02:09:26 +00003029 return ConservativeResult;
Dan Gohman52fddd32010-01-26 04:40:18 +00003030 return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
Dan Gohman62849c02009-06-24 01:05:09 +00003031 }
Dan Gohman62849c02009-06-24 01:05:09 +00003032 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003033
3034 return ConservativeResult;
Dan Gohman62849c02009-06-24 01:05:09 +00003035 }
3036
Dan Gohman2c364ad2009-06-19 23:29:04 +00003037 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3038 // For a SCEVUnknown, ask ValueTracking.
Dan Gohmana10756e2010-01-21 02:09:26 +00003039 if (!U->getValue()->getType()->isInteger() && !TD)
Dan Gohman52fddd32010-01-26 04:40:18 +00003040 return ConservativeResult;
Dan Gohman85b05a22009-07-13 21:35:55 +00003041 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3042 if (NS == 1)
Dan Gohman52fddd32010-01-26 04:40:18 +00003043 return ConservativeResult;
3044 return ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003045 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman52fddd32010-01-26 04:40:18 +00003046 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003047 }
3048
Dan Gohman52fddd32010-01-26 04:40:18 +00003049 return ConservativeResult;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003050}
3051
Chris Lattner53e677a2004-04-02 20:23:17 +00003052/// createSCEV - We know that there is no SCEV for the specified value.
3053/// Analyze the expression.
3054///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003055const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003056 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003057 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003058
Dan Gohman6c459a22008-06-22 19:56:46 +00003059 unsigned Opcode = Instruction::UserOp1;
3060 if (Instruction *I = dyn_cast<Instruction>(V))
3061 Opcode = I->getOpcode();
3062 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
3063 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003064 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3065 return getConstant(CI);
3066 else if (isa<ConstantPointerNull>(V))
3067 return getIntegerSCEV(0, V->getType());
3068 else if (isa<UndefValue>(V))
3069 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00003070 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3071 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003072 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003073 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003074
Dan Gohmanca178902009-07-17 20:47:02 +00003075 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003076 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00003077 case Instruction::Add:
3078 // Don't transfer the NSW and NUW bits from the Add instruction to the
3079 // Add expression, because the Instruction may be guarded by control
3080 // flow and the no-overflow bits may not be valid for the expression in
3081 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003082 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003083 getSCEV(U->getOperand(1)));
3084 case Instruction::Mul:
3085 // Don't transfer the NSW and NUW bits from the Mul instruction to the
3086 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003087 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00003088 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003089 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003090 return getUDivExpr(getSCEV(U->getOperand(0)),
3091 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003092 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003093 return getMinusSCEV(getSCEV(U->getOperand(0)),
3094 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003095 case Instruction::And:
3096 // For an expression like x&255 that merely masks off the high bits,
3097 // use zext(trunc(x)) as the SCEV expression.
3098 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003099 if (CI->isNullValue())
3100 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003101 if (CI->isAllOnesValue())
3102 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003103 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003104
3105 // Instcombine's ShrinkDemandedConstant may strip bits out of
3106 // constants, obscuring what would otherwise be a low-bits mask.
3107 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3108 // knew about to reconstruct a low-bits mask value.
3109 unsigned LZ = A.countLeadingZeros();
3110 unsigned BitWidth = A.getBitWidth();
3111 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3112 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3113 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3114
3115 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3116
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003117 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003118 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003119 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003120 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003121 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003122 }
3123 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003124
Dan Gohman6c459a22008-06-22 19:56:46 +00003125 case Instruction::Or:
3126 // If the RHS of the Or is a constant, we may have something like:
3127 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3128 // optimizations will transparently handle this case.
3129 //
3130 // In order for this transformation to be safe, the LHS must be of the
3131 // form X*(2^n) and the Or constant must be less than 2^n.
3132 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003133 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003134 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003135 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003136 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3137 // Build a plain add SCEV.
3138 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3139 // If the LHS of the add was an addrec and it has no-wrap flags,
3140 // transfer the no-wrap flags, since an or won't introduce a wrap.
3141 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3142 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3143 if (OldAR->hasNoUnsignedWrap())
3144 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3145 if (OldAR->hasNoSignedWrap())
3146 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3147 }
3148 return S;
3149 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003150 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003151 break;
3152 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003153 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003154 // If the RHS of the xor is a signbit, then this is just an add.
3155 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003156 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003157 return getAddExpr(getSCEV(U->getOperand(0)),
3158 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003159
3160 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003161 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003162 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003163
3164 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3165 // This is a variant of the check for xor with -1, and it handles
3166 // the case where instcombine has trimmed non-demanded bits out
3167 // of an xor with -1.
3168 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3169 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3170 if (BO->getOpcode() == Instruction::And &&
3171 LCI->getValue() == CI->getValue())
3172 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003173 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003174 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003175 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003176 const Type *Z0Ty = Z0->getType();
3177 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3178
3179 // If C is a low-bits mask, the zero extend is zerving to
3180 // mask off the high bits. Complement the operand and
3181 // re-apply the zext.
3182 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3183 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3184
3185 // If C is a single bit, it may be in the sign-bit position
3186 // before the zero-extend. In this case, represent the xor
3187 // using an add, which is equivalent, and re-apply the zext.
3188 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3189 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3190 Trunc.isSignBit())
3191 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3192 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003193 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003194 }
3195 break;
3196
3197 case Instruction::Shl:
3198 // Turn shift left of a constant amount into a multiply.
3199 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3200 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003201 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003202 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003203 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003204 }
3205 break;
3206
Nick Lewycky01eaf802008-07-07 06:15:49 +00003207 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003208 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003209 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3210 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003211 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003212 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003213 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003214 }
3215 break;
3216
Dan Gohman4ee29af2009-04-21 02:26:00 +00003217 case Instruction::AShr:
3218 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3219 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3220 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3221 if (L->getOpcode() == Instruction::Shl &&
3222 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003223 unsigned BitWidth = getTypeSizeInBits(U->getType());
3224 uint64_t Amt = BitWidth - CI->getZExtValue();
3225 if (Amt == BitWidth)
3226 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3227 if (Amt > BitWidth)
3228 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003229 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003230 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003231 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003232 U->getType());
3233 }
3234 break;
3235
Dan Gohman6c459a22008-06-22 19:56:46 +00003236 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003237 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003238
3239 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003240 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003241
3242 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003243 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003244
3245 case Instruction::BitCast:
3246 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003247 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003248 return getSCEV(U->getOperand(0));
3249 break;
3250
Dan Gohmanf2411742009-07-20 17:43:30 +00003251 // It's tempting to handle inttoptr and ptrtoint, however this can
3252 // lead to pointer expressions which cannot be expanded to GEPs
3253 // (because they may overflow). For now, the only pointer-typed
3254 // expressions we handle are GEPs and address literals.
Dan Gohman2d1be872009-04-16 03:18:22 +00003255
Dan Gohman26466c02009-05-08 20:26:55 +00003256 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003257 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003258
Dan Gohman6c459a22008-06-22 19:56:46 +00003259 case Instruction::PHI:
3260 return createNodeForPHI(cast<PHINode>(U));
3261
3262 case Instruction::Select:
3263 // This could be a smax or umax that was lowered earlier.
3264 // Try to recover it.
3265 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3266 Value *LHS = ICI->getOperand(0);
3267 Value *RHS = ICI->getOperand(1);
3268 switch (ICI->getPredicate()) {
3269 case ICmpInst::ICMP_SLT:
3270 case ICmpInst::ICMP_SLE:
3271 std::swap(LHS, RHS);
3272 // fall through
3273 case ICmpInst::ICMP_SGT:
3274 case ICmpInst::ICMP_SGE:
3275 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003276 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003277 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003278 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003279 break;
3280 case ICmpInst::ICMP_ULT:
3281 case ICmpInst::ICMP_ULE:
3282 std::swap(LHS, RHS);
3283 // fall through
3284 case ICmpInst::ICMP_UGT:
3285 case ICmpInst::ICMP_UGE:
3286 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003287 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003288 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003289 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003290 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003291 case ICmpInst::ICMP_NE:
3292 // n != 0 ? n : 1 -> umax(n, 1)
3293 if (LHS == U->getOperand(1) &&
3294 isa<ConstantInt>(U->getOperand(2)) &&
3295 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3296 isa<ConstantInt>(RHS) &&
3297 cast<ConstantInt>(RHS)->isZero())
3298 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3299 break;
3300 case ICmpInst::ICMP_EQ:
3301 // n == 0 ? 1 : n -> umax(n, 1)
3302 if (LHS == U->getOperand(2) &&
3303 isa<ConstantInt>(U->getOperand(1)) &&
3304 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3305 isa<ConstantInt>(RHS) &&
3306 cast<ConstantInt>(RHS)->isZero())
3307 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3308 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003309 default:
3310 break;
3311 }
3312 }
3313
3314 default: // We cannot analyze this expression.
3315 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003316 }
3317
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003318 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003319}
3320
3321
3322
3323//===----------------------------------------------------------------------===//
3324// Iteration Count Computation Code
3325//
3326
Dan Gohman46bdfb02009-02-24 18:55:53 +00003327/// getBackedgeTakenCount - If the specified loop has a predictable
3328/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3329/// object. The backedge-taken count is the number of times the loop header
3330/// will be branched to from within the loop. This is one less than the
3331/// trip count of the loop, since it doesn't count the first iteration,
3332/// when the header is branched to from outside the loop.
3333///
3334/// Note that it is not valid to call this method on a loop without a
3335/// loop-invariant backedge-taken count (see
3336/// hasLoopInvariantBackedgeTakenCount).
3337///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003338const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003339 return getBackedgeTakenInfo(L).Exact;
3340}
3341
3342/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3343/// return the least SCEV value that is known never to be less than the
3344/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003345const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003346 return getBackedgeTakenInfo(L).Max;
3347}
3348
Dan Gohman59ae6b92009-07-08 19:23:34 +00003349/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3350/// onto the given Worklist.
3351static void
3352PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3353 BasicBlock *Header = L->getHeader();
3354
3355 // Push all Loop-header PHIs onto the Worklist stack.
3356 for (BasicBlock::iterator I = Header->begin();
3357 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3358 Worklist.push_back(PN);
3359}
3360
Dan Gohmana1af7572009-04-30 20:47:05 +00003361const ScalarEvolution::BackedgeTakenInfo &
3362ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003363 // Initially insert a CouldNotCompute for this loop. If the insertion
3364 // succeeds, procede to actually compute a backedge-taken count and
3365 // update the value. The temporary CouldNotCompute value tells SCEV
3366 // code elsewhere that it shouldn't attempt to request a new
3367 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003368 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003369 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3370 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003371 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3372 if (BECount.Exact != getCouldNotCompute()) {
3373 assert(BECount.Exact->isLoopInvariant(L) &&
3374 BECount.Max->isLoopInvariant(L) &&
3375 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003376 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003377
Dan Gohman01ecca22009-04-27 20:16:15 +00003378 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003379 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003380 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003381 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003382 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003383 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003384 if (isa<PHINode>(L->getHeader()->begin()))
3385 // Only count loops that have phi nodes as not being computable.
3386 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003387 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003388
3389 // Now that we know more about the trip count for this loop, forget any
3390 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003391 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003392 // information. This is similar to the code in forgetLoop, except that
3393 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003394 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003395 SmallVector<Instruction *, 16> Worklist;
3396 PushLoopPHIs(L, Worklist);
3397
3398 SmallPtrSet<Instruction *, 8> Visited;
3399 while (!Worklist.empty()) {
3400 Instruction *I = Worklist.pop_back_val();
3401 if (!Visited.insert(I)) continue;
3402
Dan Gohman5d984912009-12-18 01:14:11 +00003403 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003404 Scalars.find(static_cast<Value *>(I));
3405 if (It != Scalars.end()) {
3406 // SCEVUnknown for a PHI either means that it has an unrecognized
3407 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003408 // by createNodeForPHI. In the former case, additional loop trip
3409 // count information isn't going to change anything. In the later
3410 // case, createNodeForPHI will perform the necessary updates on its
3411 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003412 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3413 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003414 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003415 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003416 if (PHINode *PN = dyn_cast<PHINode>(I))
3417 ConstantEvolutionLoopExitValue.erase(PN);
3418 }
3419
3420 PushDefUseChildren(I, Worklist);
3421 }
3422 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003423 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003424 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003425}
3426
Dan Gohman4c7279a2009-10-31 15:04:55 +00003427/// forgetLoop - This method should be called by the client when it has
3428/// changed a loop in a way that may effect ScalarEvolution's ability to
3429/// compute a trip count, or if the loop is deleted.
3430void ScalarEvolution::forgetLoop(const Loop *L) {
3431 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003432 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003433
Dan Gohman4c7279a2009-10-31 15:04:55 +00003434 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003435 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003436 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003437
Dan Gohman59ae6b92009-07-08 19:23:34 +00003438 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003439 while (!Worklist.empty()) {
3440 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003441 if (!Visited.insert(I)) continue;
3442
Dan Gohman5d984912009-12-18 01:14:11 +00003443 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003444 Scalars.find(static_cast<Value *>(I));
3445 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003446 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003447 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003448 if (PHINode *PN = dyn_cast<PHINode>(I))
3449 ConstantEvolutionLoopExitValue.erase(PN);
3450 }
3451
3452 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003453 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003454}
3455
Dan Gohman46bdfb02009-02-24 18:55:53 +00003456/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3457/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003458ScalarEvolution::BackedgeTakenInfo
3459ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003460 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003461 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003462
Dan Gohmana334aa72009-06-22 00:31:57 +00003463 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003464 const SCEV *BECount = getCouldNotCompute();
3465 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003466 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003467 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3468 BackedgeTakenInfo NewBTI =
3469 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003470
Dan Gohman1c343752009-06-27 21:21:31 +00003471 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003472 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003473 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003474 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003475 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003476 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003477 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003478 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003479 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003480 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003481 }
Dan Gohman1c343752009-06-27 21:21:31 +00003482 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003483 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003484 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003485 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003486 }
3487
3488 return BackedgeTakenInfo(BECount, MaxBECount);
3489}
3490
3491/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3492/// of the specified loop will execute if it exits via the specified block.
3493ScalarEvolution::BackedgeTakenInfo
3494ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3495 BasicBlock *ExitingBlock) {
3496
3497 // Okay, we've chosen an exiting block. See what condition causes us to
3498 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003499 //
3500 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003501 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003502 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003503 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003504
Chris Lattner8b0e3602007-01-07 02:24:26 +00003505 // At this point, we know we have a conditional branch that determines whether
3506 // the loop is exited. However, we don't know if the branch is executed each
3507 // time through the loop. If not, then the execution count of the branch will
3508 // not be equal to the trip count of the loop.
3509 //
3510 // Currently we check for this by checking to see if the Exit branch goes to
3511 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003512 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003513 // loop header. This is common for un-rotated loops.
3514 //
3515 // If both of those tests fail, walk up the unique predecessor chain to the
3516 // header, stopping if there is an edge that doesn't exit the loop. If the
3517 // header is reached, the execution count of the branch will be equal to the
3518 // trip count of the loop.
3519 //
3520 // More extensive analysis could be done to handle more cases here.
3521 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003522 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003523 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003524 ExitBr->getParent() != L->getHeader()) {
3525 // The simple checks failed, try climbing the unique predecessor chain
3526 // up to the header.
3527 bool Ok = false;
3528 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3529 BasicBlock *Pred = BB->getUniquePredecessor();
3530 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003531 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003532 TerminatorInst *PredTerm = Pred->getTerminator();
3533 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3534 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3535 if (PredSucc == BB)
3536 continue;
3537 // If the predecessor has a successor that isn't BB and isn't
3538 // outside the loop, assume the worst.
3539 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003540 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003541 }
3542 if (Pred == L->getHeader()) {
3543 Ok = true;
3544 break;
3545 }
3546 BB = Pred;
3547 }
3548 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003549 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003550 }
3551
3552 // Procede to the next level to examine the exit condition expression.
3553 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3554 ExitBr->getSuccessor(0),
3555 ExitBr->getSuccessor(1));
3556}
3557
3558/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3559/// backedge of the specified loop will execute if its exit condition
3560/// were a conditional branch of ExitCond, TBB, and FBB.
3561ScalarEvolution::BackedgeTakenInfo
3562ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3563 Value *ExitCond,
3564 BasicBlock *TBB,
3565 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003566 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003567 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3568 if (BO->getOpcode() == Instruction::And) {
3569 // Recurse on the operands of the and.
3570 BackedgeTakenInfo BTI0 =
3571 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3572 BackedgeTakenInfo BTI1 =
3573 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003574 const SCEV *BECount = getCouldNotCompute();
3575 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003576 if (L->contains(TBB)) {
3577 // Both conditions must be true for the loop to continue executing.
3578 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003579 if (BTI0.Exact == getCouldNotCompute() ||
3580 BTI1.Exact == getCouldNotCompute())
3581 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003582 else
3583 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003584 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003585 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003586 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003587 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003588 else
3589 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003590 } else {
3591 // Both conditions must be true for the loop to exit.
3592 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003593 if (BTI0.Exact != getCouldNotCompute() &&
3594 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003595 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003596 if (BTI0.Max != getCouldNotCompute() &&
3597 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003598 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3599 }
3600
3601 return BackedgeTakenInfo(BECount, MaxBECount);
3602 }
3603 if (BO->getOpcode() == Instruction::Or) {
3604 // Recurse on the operands of the or.
3605 BackedgeTakenInfo BTI0 =
3606 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3607 BackedgeTakenInfo BTI1 =
3608 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003609 const SCEV *BECount = getCouldNotCompute();
3610 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003611 if (L->contains(FBB)) {
3612 // Both conditions must be false for the loop to continue executing.
3613 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003614 if (BTI0.Exact == getCouldNotCompute() ||
3615 BTI1.Exact == getCouldNotCompute())
3616 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003617 else
3618 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003619 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003620 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003621 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003622 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003623 else
3624 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003625 } else {
3626 // Both conditions must be false for the loop to exit.
3627 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003628 if (BTI0.Exact != getCouldNotCompute() &&
3629 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003630 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003631 if (BTI0.Max != getCouldNotCompute() &&
3632 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003633 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3634 }
3635
3636 return BackedgeTakenInfo(BECount, MaxBECount);
3637 }
3638 }
3639
3640 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3641 // Procede to the next level to examine the icmp.
3642 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3643 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644
Eli Friedman361e54d2009-05-09 12:32:42 +00003645 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003646 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3647}
3648
3649/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3650/// backedge of the specified loop will execute if its exit condition
3651/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3652ScalarEvolution::BackedgeTakenInfo
3653ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3654 ICmpInst *ExitCond,
3655 BasicBlock *TBB,
3656 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003657
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 // If the condition was exit on true, convert the condition to exit on false
3659 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003660 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003662 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003663 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003664
3665 // Handle common loops like: for (X = "string"; *X; ++X)
3666 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3667 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003668 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003669 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003670 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3671 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3672 return BackedgeTakenInfo(ItCnt,
3673 isa<SCEVConstant>(ItCnt) ? ItCnt :
3674 getConstant(APInt::getMaxValue(BitWidth)-1));
3675 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003676 }
3677
Dan Gohman0bba49c2009-07-07 17:06:11 +00003678 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3679 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003680
3681 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003682 LHS = getSCEVAtScope(LHS, L);
3683 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003684
Dan Gohman64a845e2009-06-24 04:48:43 +00003685 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003686 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003687 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3688 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003689 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003690 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003691 }
3692
Chris Lattner53e677a2004-04-02 20:23:17 +00003693 // If we have a comparison of a chrec against a constant, try to use value
3694 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003695 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3696 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003697 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003698 // Form the constant range.
3699 ConstantRange CompRange(
3700 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003701
Dan Gohman0bba49c2009-07-07 17:06:11 +00003702 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003703 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003704 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003705
Chris Lattner53e677a2004-04-02 20:23:17 +00003706 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003708 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003709 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003710 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003711 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003712 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003713 case ICmpInst::ICMP_EQ: { // while (X == Y)
3714 // Convert to: while (X-Y == 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003715 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003716 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003717 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003718 }
3719 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003720 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3721 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003722 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003723 }
3724 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003725 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3726 getNotSCEV(RHS), L, true);
3727 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003728 break;
3729 }
3730 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003731 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3732 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003733 break;
3734 }
3735 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003736 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3737 getNotSCEV(RHS), L, false);
3738 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003739 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003740 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003741 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003742#if 0
David Greene25e0e872009-12-23 22:18:14 +00003743 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003744 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00003745 dbgs() << "[unsigned] ";
3746 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003747 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003749#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003750 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003751 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003752 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003753 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003754}
3755
Chris Lattner673e02b2004-10-12 01:49:27 +00003756static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003757EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3758 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003759 const SCEV *InVal = SE.getConstant(C);
3760 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003761 assert(isa<SCEVConstant>(Val) &&
3762 "Evaluation of SCEV at constant didn't fold correctly?");
3763 return cast<SCEVConstant>(Val)->getValue();
3764}
3765
3766/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3767/// and a GEP expression (missing the pointer index) indexing into it, return
3768/// the addressed element of the initializer or null if the index expression is
3769/// invalid.
3770static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003771GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003772 const std::vector<ConstantInt*> &Indices) {
3773 Constant *Init = GV->getInitializer();
3774 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003775 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003776 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3777 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3778 Init = cast<Constant>(CS->getOperand(Idx));
3779 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3780 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3781 Init = cast<Constant>(CA->getOperand(Idx));
3782 } else if (isa<ConstantAggregateZero>(Init)) {
3783 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3784 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003785 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003786 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3787 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003788 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003789 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003790 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003791 }
3792 return 0;
3793 } else {
3794 return 0; // Unknown initializer type
3795 }
3796 }
3797 return Init;
3798}
3799
Dan Gohman46bdfb02009-02-24 18:55:53 +00003800/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3801/// 'icmp op load X, cst', try to see if we can compute the backedge
3802/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003803const SCEV *
3804ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3805 LoadInst *LI,
3806 Constant *RHS,
3807 const Loop *L,
3808 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003809 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003810
3811 // Check to see if the loaded pointer is a getelementptr of a global.
3812 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003813 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003814
3815 // Make sure that it is really a constant global we are gepping, with an
3816 // initializer, and make sure the first IDX is really 0.
3817 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003818 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003819 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3820 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003821 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003822
3823 // Okay, we allow one non-constant index into the GEP instruction.
3824 Value *VarIdx = 0;
3825 std::vector<ConstantInt*> Indexes;
3826 unsigned VarIdxNum = 0;
3827 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3828 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3829 Indexes.push_back(CI);
3830 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003831 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003832 VarIdx = GEP->getOperand(i);
3833 VarIdxNum = i-2;
3834 Indexes.push_back(0);
3835 }
3836
3837 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3838 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003839 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003840 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003841
3842 // We can only recognize very limited forms of loop index expressions, in
3843 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003844 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003845 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3846 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3847 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003848 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003849
3850 unsigned MaxSteps = MaxBruteForceIterations;
3851 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003852 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003853 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003854 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003855
3856 // Form the GEP offset.
3857 Indexes[VarIdxNum] = Val;
3858
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003859 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003860 if (Result == 0) break; // Cannot compute!
3861
3862 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003863 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003864 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003865 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003866#if 0
David Greene25e0e872009-12-23 22:18:14 +00003867 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003868 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3869 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003870#endif
3871 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003872 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003873 }
3874 }
Dan Gohman1c343752009-06-27 21:21:31 +00003875 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003876}
3877
3878
Chris Lattner3221ad02004-04-17 22:58:41 +00003879/// CanConstantFold - Return true if we can constant fold an instruction of the
3880/// specified type, assuming that all operands were constants.
3881static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003882 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003883 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3884 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003885
Chris Lattner3221ad02004-04-17 22:58:41 +00003886 if (const CallInst *CI = dyn_cast<CallInst>(I))
3887 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003888 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003889 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003890}
3891
Chris Lattner3221ad02004-04-17 22:58:41 +00003892/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3893/// in the loop that V is derived from. We allow arbitrary operations along the
3894/// way, but the operands of an operation must either be constants or a value
3895/// derived from a constant PHI. If this expression does not fit with these
3896/// constraints, return null.
3897static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3898 // If this is not an instruction, or if this is an instruction outside of the
3899 // loop, it can't be derived from a loop PHI.
3900 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00003901 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003902
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003903 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003904 if (L->getHeader() == I->getParent())
3905 return PN;
3906 else
3907 // We don't currently keep track of the control flow needed to evaluate
3908 // PHIs, so we cannot handle PHIs inside of loops.
3909 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003910 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003911
3912 // If we won't be able to constant fold this expression even if the operands
3913 // are constants, return early.
3914 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003915
Chris Lattner3221ad02004-04-17 22:58:41 +00003916 // Otherwise, we can evaluate this instruction if all of its operands are
3917 // constant or derived from a PHI node themselves.
3918 PHINode *PHI = 0;
3919 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3920 if (!(isa<Constant>(I->getOperand(Op)) ||
3921 isa<GlobalValue>(I->getOperand(Op)))) {
3922 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3923 if (P == 0) return 0; // Not evolving from PHI
3924 if (PHI == 0)
3925 PHI = P;
3926 else if (PHI != P)
3927 return 0; // Evolving from multiple different PHIs.
3928 }
3929
3930 // This is a expression evolving from a constant PHI!
3931 return PHI;
3932}
3933
3934/// EvaluateExpression - Given an expression that passes the
3935/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3936/// in the loop has the value PHIVal. If we can't fold this expression for some
3937/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003938static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
3939 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003940 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003941 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003942 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003943 Instruction *I = cast<Instruction>(V);
3944
3945 std::vector<Constant*> Operands;
3946 Operands.resize(I->getNumOperands());
3947
3948 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003949 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003950 if (Operands[i] == 0) return 0;
3951 }
3952
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003953 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00003954 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003955 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00003956 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003957 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003958}
3959
3960/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3961/// in the header of its containing loop, we know the loop executes a
3962/// constant number of times, and the PHI node is just a recurrence
3963/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003964Constant *
3965ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00003966 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00003967 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003968 std::map<PHINode*, Constant*>::iterator I =
3969 ConstantEvolutionLoopExitValue.find(PN);
3970 if (I != ConstantEvolutionLoopExitValue.end())
3971 return I->second;
3972
Dan Gohman46bdfb02009-02-24 18:55:53 +00003973 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003974 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3975
3976 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3977
3978 // Since the loop is canonicalized, the PHI node must have two entries. One
3979 // entry must be a constant (coming in from outside of the loop), and the
3980 // second must be derived from the same PHI.
3981 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3982 Constant *StartCST =
3983 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3984 if (StartCST == 0)
3985 return RetVal = 0; // Must be a constant.
3986
3987 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3988 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3989 if (PN2 != PN)
3990 return RetVal = 0; // Not derived from same PHI.
3991
3992 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003993 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003994 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003995
Dan Gohman46bdfb02009-02-24 18:55:53 +00003996 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003997 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003998 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3999 if (IterationNum == NumIterations)
4000 return RetVal = PHIVal; // Got exit value!
4001
4002 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004003 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004004 if (NextPHI == PHIVal)
4005 return RetVal = NextPHI; // Stopped evolving!
4006 if (NextPHI == 0)
4007 return 0; // Couldn't evaluate!
4008 PHIVal = NextPHI;
4009 }
4010}
4011
Dan Gohman07ad19b2009-07-27 16:09:48 +00004012/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004013/// constant number of times (the condition evolves only from constants),
4014/// try to evaluate a few iterations of the loop until we get the exit
4015/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004016/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004017const SCEV *
4018ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4019 Value *Cond,
4020 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004021 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004022 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004023
4024 // Since the loop is canonicalized, the PHI node must have two entries. One
4025 // entry must be a constant (coming in from outside of the loop), and the
4026 // second must be derived from the same PHI.
4027 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4028 Constant *StartCST =
4029 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004030 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004031
4032 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
4033 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004034 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004035
4036 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4037 // the loop symbolically to determine when the condition gets a value of
4038 // "ExitWhen".
4039 unsigned IterationNum = 0;
4040 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4041 for (Constant *PHIVal = StartCST;
4042 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004043 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004044 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004045
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004046 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004047 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004048
Reid Spencere8019bb2007-03-01 07:25:48 +00004049 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004050 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004051 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004052 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004053
Chris Lattner3221ad02004-04-17 22:58:41 +00004054 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004055 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004056 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004057 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004058 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004059 }
4060
4061 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004062 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004063}
4064
Dan Gohmane7125f42009-09-03 15:00:26 +00004065/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004066/// at the specified scope in the program. The L value specifies a loop
4067/// nest to evaluate the expression at, where null is the top-level or a
4068/// specified loop is immediately inside of the loop.
4069///
4070/// This method can be used to compute the exit value for a variable defined
4071/// in a loop by querying what the value will hold in the parent loop.
4072///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004073/// In the case that a relevant loop exit value cannot be computed, the
4074/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004075const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004076 // Check to see if we've folded this expression at this loop before.
4077 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4078 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4079 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4080 if (!Pair.second)
4081 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004082
Dan Gohman42214892009-08-31 21:15:23 +00004083 // Otherwise compute it.
4084 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004085 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004086 return C;
4087}
4088
4089const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004090 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004091
Nick Lewycky3e630762008-02-20 06:48:22 +00004092 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004093 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004094 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004095 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004096 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004097 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4098 if (PHINode *PN = dyn_cast<PHINode>(I))
4099 if (PN->getParent() == LI->getHeader()) {
4100 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004101 // to see if the loop that contains it has a known backedge-taken
4102 // count. If so, we may be able to force computation of the exit
4103 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004104 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004105 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004106 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004107 // Okay, we know how many times the containing loop executes. If
4108 // this is a constant evolving PHI node, get the final value at
4109 // the specified iteration number.
4110 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004111 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004112 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004113 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004114 }
4115 }
4116
Reid Spencer09906f32006-12-04 21:33:23 +00004117 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004118 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004119 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004120 // result. This is particularly useful for computing loop exit values.
4121 if (CanConstantFold(I)) {
4122 std::vector<Constant*> Operands;
4123 Operands.reserve(I->getNumOperands());
4124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4125 Value *Op = I->getOperand(i);
4126 if (Constant *C = dyn_cast<Constant>(Op)) {
4127 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004128 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004129 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004130 // non-integer and non-pointer, don't even try to analyze them
4131 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004132 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004133 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004134
Dan Gohman5d984912009-12-18 01:14:11 +00004135 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004136 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004137 Constant *C = SC->getValue();
4138 if (C->getType() != Op->getType())
4139 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4140 Op->getType(),
4141 false),
4142 C, Op->getType());
4143 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004144 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004145 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4146 if (C->getType() != Op->getType())
4147 C =
4148 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4149 Op->getType(),
4150 false),
4151 C, Op->getType());
4152 Operands.push_back(C);
4153 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004154 return V;
4155 } else {
4156 return V;
4157 }
4158 }
4159 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004160
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004161 Constant *C;
4162 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4163 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004164 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004165 else
4166 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004167 &Operands[0], Operands.size(), TD);
Dan Gohman09987962009-06-29 21:31:18 +00004168 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004169 }
4170 }
4171
4172 // This is some other type of SCEVUnknown, just return it.
4173 return V;
4174 }
4175
Dan Gohman622ed672009-05-04 22:02:23 +00004176 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004177 // Avoid performing the look-up in the common case where the specified
4178 // expression has no loop-variant portions.
4179 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004180 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004181 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004182 // Okay, at least one of these operands is loop variant but might be
4183 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004184 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4185 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004186 NewOps.push_back(OpAtScope);
4187
4188 for (++i; i != e; ++i) {
4189 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004190 NewOps.push_back(OpAtScope);
4191 }
4192 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004193 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004194 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004195 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004196 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004197 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004198 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004199 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004200 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004201 }
4202 }
4203 // If we got here, all operands are loop invariant.
4204 return Comm;
4205 }
4206
Dan Gohman622ed672009-05-04 22:02:23 +00004207 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004208 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4209 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004210 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4211 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004212 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004213 }
4214
4215 // If this is a loop recurrence for a loop that does not contain L, then we
4216 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004217 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004218 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004219 // To evaluate this recurrence, we need to know how many times the AddRec
4220 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004221 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004222 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004223
Eli Friedmanb42a6262008-08-04 23:49:06 +00004224 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004225 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004226 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004227 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004228 }
4229
Dan Gohman622ed672009-05-04 22:02:23 +00004230 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004231 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004232 if (Op == Cast->getOperand())
4233 return Cast; // must be loop invariant
4234 return getZeroExtendExpr(Op, Cast->getType());
4235 }
4236
Dan Gohman622ed672009-05-04 22:02:23 +00004237 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004238 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004239 if (Op == Cast->getOperand())
4240 return Cast; // must be loop invariant
4241 return getSignExtendExpr(Op, Cast->getType());
4242 }
4243
Dan Gohman622ed672009-05-04 22:02:23 +00004244 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004245 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004246 if (Op == Cast->getOperand())
4247 return Cast; // must be loop invariant
4248 return getTruncateExpr(Op, Cast->getType());
4249 }
4250
Torok Edwinc23197a2009-07-14 16:55:14 +00004251 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004252 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004253}
4254
Dan Gohman66a7e852009-05-08 20:38:54 +00004255/// getSCEVAtScope - This is a convenience function which does
4256/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004257const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004258 return getSCEVAtScope(getSCEV(V), L);
4259}
4260
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004261/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4262/// following equation:
4263///
4264/// A * X = B (mod N)
4265///
4266/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4267/// A and B isn't important.
4268///
4269/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004270static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004271 ScalarEvolution &SE) {
4272 uint32_t BW = A.getBitWidth();
4273 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4274 assert(A != 0 && "A must be non-zero.");
4275
4276 // 1. D = gcd(A, N)
4277 //
4278 // The gcd of A and N may have only one prime factor: 2. The number of
4279 // trailing zeros in A is its multiplicity
4280 uint32_t Mult2 = A.countTrailingZeros();
4281 // D = 2^Mult2
4282
4283 // 2. Check if B is divisible by D.
4284 //
4285 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4286 // is not less than multiplicity of this prime factor for D.
4287 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004288 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004289
4290 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4291 // modulo (N / D).
4292 //
4293 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4294 // bit width during computations.
4295 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4296 APInt Mod(BW + 1, 0);
4297 Mod.set(BW - Mult2); // Mod = N / D
4298 APInt I = AD.multiplicativeInverse(Mod);
4299
4300 // 4. Compute the minimum unsigned root of the equation:
4301 // I * (B / D) mod (N / D)
4302 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4303
4304 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4305 // bits.
4306 return SE.getConstant(Result.trunc(BW));
4307}
Chris Lattner53e677a2004-04-02 20:23:17 +00004308
4309/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4310/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4311/// might be the same) or two SCEVCouldNotCompute objects.
4312///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004313static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004314SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004315 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004316 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4317 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4318 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004319
Chris Lattner53e677a2004-04-02 20:23:17 +00004320 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004321 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004322 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004323 return std::make_pair(CNC, CNC);
4324 }
4325
Reid Spencere8019bb2007-03-01 07:25:48 +00004326 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004327 const APInt &L = LC->getValue()->getValue();
4328 const APInt &M = MC->getValue()->getValue();
4329 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004330 APInt Two(BitWidth, 2);
4331 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004332
Dan Gohman64a845e2009-06-24 04:48:43 +00004333 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004334 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004335 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004336 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4337 // The B coefficient is M-N/2
4338 APInt B(M);
4339 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004340
Reid Spencere8019bb2007-03-01 07:25:48 +00004341 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004342 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004343
Reid Spencere8019bb2007-03-01 07:25:48 +00004344 // Compute the B^2-4ac term.
4345 APInt SqrtTerm(B);
4346 SqrtTerm *= B;
4347 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004348
Reid Spencere8019bb2007-03-01 07:25:48 +00004349 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4350 // integer value or else APInt::sqrt() will assert.
4351 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004352
Dan Gohman64a845e2009-06-24 04:48:43 +00004353 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004354 // The divisions must be performed as signed divisions.
4355 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004356 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004357 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004358 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004359 return std::make_pair(CNC, CNC);
4360 }
4361
Owen Andersone922c022009-07-22 00:24:57 +00004362 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004363
4364 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004365 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004366 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004367 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004368
Dan Gohman64a845e2009-06-24 04:48:43 +00004369 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004370 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004371 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004372}
4373
4374/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004375/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004376const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004377 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004378 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004379 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004380 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004381 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004382 }
4383
Dan Gohman35738ac2009-05-04 22:30:44 +00004384 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004385 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004386 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004387
4388 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004389 // If this is an affine expression, the execution count of this branch is
4390 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004391 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004392 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004393 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004394 // equivalent to:
4395 //
4396 // Step*N = -Start (mod 2^BW)
4397 //
4398 // where BW is the common bit width of Start and Step.
4399
Chris Lattner53e677a2004-04-02 20:23:17 +00004400 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004401 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4402 L->getParentLoop());
4403 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4404 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004405
Dan Gohman622ed672009-05-04 22:02:23 +00004406 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004407 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004408
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004409 // First, handle unitary steps.
4410 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004411 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004412 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4413 return Start; // N = Start (as unsigned)
4414
4415 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004416 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004417 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004418 -StartC->getValue()->getValue(),
4419 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004420 }
Chris Lattner42a75512007-01-15 02:27:26 +00004421 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004422 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4423 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004424 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004425 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004426 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4427 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004428 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004429#if 0
David Greene25e0e872009-12-23 22:18:14 +00004430 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004431 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004432#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004433 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004434 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004435 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004436 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004437 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004438 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004439
Chris Lattner53e677a2004-04-02 20:23:17 +00004440 // We can only use this value if the chrec ends up with an exact zero
4441 // value at this index. When solving for "X*X != 5", for example, we
4442 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004443 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004444 if (Val->isZero())
4445 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004446 }
4447 }
4448 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004449
Dan Gohman1c343752009-06-27 21:21:31 +00004450 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004451}
4452
4453/// HowFarToNonZero - Return the number of times a backedge checking the
4454/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004455/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004456const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004457 // Loops that look like: while (X == 0) are very strange indeed. We don't
4458 // handle them yet except for the trivial case. This could be expanded in the
4459 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004460
Chris Lattner53e677a2004-04-02 20:23:17 +00004461 // If the value is a constant, check to see if it is known to be non-zero
4462 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004463 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004464 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004465 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004466 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004467 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004468
Chris Lattner53e677a2004-04-02 20:23:17 +00004469 // We could implement others, but I really doubt anyone writes loops like
4470 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004471 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004472}
4473
Dan Gohman859b4822009-05-18 15:36:09 +00004474/// getLoopPredecessor - If the given loop's header has exactly one unique
4475/// predecessor outside the loop, return it. Otherwise return null.
4476///
4477BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4478 BasicBlock *Header = L->getHeader();
4479 BasicBlock *Pred = 0;
4480 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4481 PI != E; ++PI)
4482 if (!L->contains(*PI)) {
4483 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4484 Pred = *PI;
4485 }
4486 return Pred;
4487}
4488
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004489/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4490/// (which may not be an immediate predecessor) which has exactly one
4491/// successor from which BB is reachable, or null if no such block is
4492/// found.
4493///
4494BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004495ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004496 // If the block has a unique predecessor, then there is no path from the
4497 // predecessor to the block that does not go through the direct edge
4498 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004499 if (BasicBlock *Pred = BB->getSinglePredecessor())
4500 return Pred;
4501
4502 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004503 // If the header has a unique predecessor outside the loop, it must be
4504 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004505 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004506 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004507
4508 return 0;
4509}
4510
Dan Gohman763bad12009-06-20 00:35:32 +00004511/// HasSameValue - SCEV structural equivalence is usually sufficient for
4512/// testing whether two expressions are equal, however for the purposes of
4513/// looking for a condition guarding a loop, it can be useful to be a little
4514/// more general, since a front-end may have replicated the controlling
4515/// expression.
4516///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004517static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004518 // Quick check to see if they are the same SCEV.
4519 if (A == B) return true;
4520
4521 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4522 // two different instructions with the same value. Check for this case.
4523 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4524 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4525 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4526 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004527 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004528 return true;
4529
4530 // Otherwise assume they may have a different value.
4531 return false;
4532}
4533
Dan Gohman85b05a22009-07-13 21:35:55 +00004534bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4535 return getSignedRange(S).getSignedMax().isNegative();
4536}
4537
4538bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4539 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4540}
4541
4542bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4543 return !getSignedRange(S).getSignedMin().isNegative();
4544}
4545
4546bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4547 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4548}
4549
4550bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4551 return isKnownNegative(S) || isKnownPositive(S);
4552}
4553
4554bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4555 const SCEV *LHS, const SCEV *RHS) {
4556
4557 if (HasSameValue(LHS, RHS))
4558 return ICmpInst::isTrueWhenEqual(Pred);
4559
4560 switch (Pred) {
4561 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004562 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004563 break;
4564 case ICmpInst::ICMP_SGT:
4565 Pred = ICmpInst::ICMP_SLT;
4566 std::swap(LHS, RHS);
4567 case ICmpInst::ICMP_SLT: {
4568 ConstantRange LHSRange = getSignedRange(LHS);
4569 ConstantRange RHSRange = getSignedRange(RHS);
4570 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4571 return true;
4572 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4573 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004574 break;
4575 }
4576 case ICmpInst::ICMP_SGE:
4577 Pred = ICmpInst::ICMP_SLE;
4578 std::swap(LHS, RHS);
4579 case ICmpInst::ICMP_SLE: {
4580 ConstantRange LHSRange = getSignedRange(LHS);
4581 ConstantRange RHSRange = getSignedRange(RHS);
4582 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4583 return true;
4584 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4585 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004586 break;
4587 }
4588 case ICmpInst::ICMP_UGT:
4589 Pred = ICmpInst::ICMP_ULT;
4590 std::swap(LHS, RHS);
4591 case ICmpInst::ICMP_ULT: {
4592 ConstantRange LHSRange = getUnsignedRange(LHS);
4593 ConstantRange RHSRange = getUnsignedRange(RHS);
4594 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4595 return true;
4596 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4597 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004598 break;
4599 }
4600 case ICmpInst::ICMP_UGE:
4601 Pred = ICmpInst::ICMP_ULE;
4602 std::swap(LHS, RHS);
4603 case ICmpInst::ICMP_ULE: {
4604 ConstantRange LHSRange = getUnsignedRange(LHS);
4605 ConstantRange RHSRange = getUnsignedRange(RHS);
4606 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4607 return true;
4608 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4609 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004610 break;
4611 }
4612 case ICmpInst::ICMP_NE: {
4613 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4614 return true;
4615 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4616 return true;
4617
4618 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4619 if (isKnownNonZero(Diff))
4620 return true;
4621 break;
4622 }
4623 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004624 // The check at the top of the function catches the case where
4625 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004626 break;
4627 }
4628 return false;
4629}
4630
4631/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4632/// protected by a conditional between LHS and RHS. This is used to
4633/// to eliminate casts.
4634bool
4635ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4636 ICmpInst::Predicate Pred,
4637 const SCEV *LHS, const SCEV *RHS) {
4638 // Interpret a null as meaning no loop, where there is obviously no guard
4639 // (interprocedural conditions notwithstanding).
4640 if (!L) return true;
4641
4642 BasicBlock *Latch = L->getLoopLatch();
4643 if (!Latch)
4644 return false;
4645
4646 BranchInst *LoopContinuePredicate =
4647 dyn_cast<BranchInst>(Latch->getTerminator());
4648 if (!LoopContinuePredicate ||
4649 LoopContinuePredicate->isUnconditional())
4650 return false;
4651
Dan Gohman0f4b2852009-07-21 23:03:19 +00004652 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4653 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004654}
4655
4656/// isLoopGuardedByCond - Test whether entry to the loop is protected
4657/// by a conditional between LHS and RHS. This is used to help avoid max
4658/// expressions in loop trip counts, and to eliminate casts.
4659bool
4660ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4661 ICmpInst::Predicate Pred,
4662 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004663 // Interpret a null as meaning no loop, where there is obviously no guard
4664 // (interprocedural conditions notwithstanding).
4665 if (!L) return false;
4666
Dan Gohman859b4822009-05-18 15:36:09 +00004667 BasicBlock *Predecessor = getLoopPredecessor(L);
4668 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004669
Dan Gohman859b4822009-05-18 15:36:09 +00004670 // Starting at the loop predecessor, climb up the predecessor chain, as long
4671 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004672 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004673 for (; Predecessor;
4674 PredecessorDest = Predecessor,
4675 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004676
4677 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004678 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004679 if (!LoopEntryPredicate ||
4680 LoopEntryPredicate->isUnconditional())
4681 continue;
4682
Dan Gohman0f4b2852009-07-21 23:03:19 +00004683 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4684 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004685 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004686 }
4687
Dan Gohman38372182008-08-12 20:17:31 +00004688 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004689}
4690
Dan Gohman0f4b2852009-07-21 23:03:19 +00004691/// isImpliedCond - Test whether the condition described by Pred, LHS,
4692/// and RHS is true whenever the given Cond value evaluates to true.
4693bool ScalarEvolution::isImpliedCond(Value *CondValue,
4694 ICmpInst::Predicate Pred,
4695 const SCEV *LHS, const SCEV *RHS,
4696 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004697 // Recursivly handle And and Or conditions.
4698 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4699 if (BO->getOpcode() == Instruction::And) {
4700 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004701 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4702 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004703 } else if (BO->getOpcode() == Instruction::Or) {
4704 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004705 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4706 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004707 }
4708 }
4709
4710 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4711 if (!ICI) return false;
4712
Dan Gohman85b05a22009-07-13 21:35:55 +00004713 // Bail if the ICmp's operands' types are wider than the needed type
4714 // before attempting to call getSCEV on them. This avoids infinite
4715 // recursion, since the analysis of widening casts can require loop
4716 // exit condition information for overflow checking, which would
4717 // lead back here.
4718 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004719 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004720 return false;
4721
Dan Gohman0f4b2852009-07-21 23:03:19 +00004722 // Now that we found a conditional branch that dominates the loop, check to
4723 // see if it is the comparison we are looking for.
4724 ICmpInst::Predicate FoundPred;
4725 if (Inverse)
4726 FoundPred = ICI->getInversePredicate();
4727 else
4728 FoundPred = ICI->getPredicate();
4729
4730 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4731 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004732
4733 // Balance the types. The case where FoundLHS' type is wider than
4734 // LHS' type is checked for above.
4735 if (getTypeSizeInBits(LHS->getType()) >
4736 getTypeSizeInBits(FoundLHS->getType())) {
4737 if (CmpInst::isSigned(Pred)) {
4738 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4739 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4740 } else {
4741 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4742 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4743 }
4744 }
4745
Dan Gohman0f4b2852009-07-21 23:03:19 +00004746 // Canonicalize the query to match the way instcombine will have
4747 // canonicalized the comparison.
4748 // First, put a constant operand on the right.
4749 if (isa<SCEVConstant>(LHS)) {
4750 std::swap(LHS, RHS);
4751 Pred = ICmpInst::getSwappedPredicate(Pred);
4752 }
4753 // Then, canonicalize comparisons with boundary cases.
4754 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4755 const APInt &RA = RC->getValue()->getValue();
4756 switch (Pred) {
4757 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4758 case ICmpInst::ICMP_EQ:
4759 case ICmpInst::ICMP_NE:
4760 break;
4761 case ICmpInst::ICMP_UGE:
4762 if ((RA - 1).isMinValue()) {
4763 Pred = ICmpInst::ICMP_NE;
4764 RHS = getConstant(RA - 1);
4765 break;
4766 }
4767 if (RA.isMaxValue()) {
4768 Pred = ICmpInst::ICMP_EQ;
4769 break;
4770 }
4771 if (RA.isMinValue()) return true;
4772 break;
4773 case ICmpInst::ICMP_ULE:
4774 if ((RA + 1).isMaxValue()) {
4775 Pred = ICmpInst::ICMP_NE;
4776 RHS = getConstant(RA + 1);
4777 break;
4778 }
4779 if (RA.isMinValue()) {
4780 Pred = ICmpInst::ICMP_EQ;
4781 break;
4782 }
4783 if (RA.isMaxValue()) return true;
4784 break;
4785 case ICmpInst::ICMP_SGE:
4786 if ((RA - 1).isMinSignedValue()) {
4787 Pred = ICmpInst::ICMP_NE;
4788 RHS = getConstant(RA - 1);
4789 break;
4790 }
4791 if (RA.isMaxSignedValue()) {
4792 Pred = ICmpInst::ICMP_EQ;
4793 break;
4794 }
4795 if (RA.isMinSignedValue()) return true;
4796 break;
4797 case ICmpInst::ICMP_SLE:
4798 if ((RA + 1).isMaxSignedValue()) {
4799 Pred = ICmpInst::ICMP_NE;
4800 RHS = getConstant(RA + 1);
4801 break;
4802 }
4803 if (RA.isMinSignedValue()) {
4804 Pred = ICmpInst::ICMP_EQ;
4805 break;
4806 }
4807 if (RA.isMaxSignedValue()) return true;
4808 break;
4809 case ICmpInst::ICMP_UGT:
4810 if (RA.isMinValue()) {
4811 Pred = ICmpInst::ICMP_NE;
4812 break;
4813 }
4814 if ((RA + 1).isMaxValue()) {
4815 Pred = ICmpInst::ICMP_EQ;
4816 RHS = getConstant(RA + 1);
4817 break;
4818 }
4819 if (RA.isMaxValue()) return false;
4820 break;
4821 case ICmpInst::ICMP_ULT:
4822 if (RA.isMaxValue()) {
4823 Pred = ICmpInst::ICMP_NE;
4824 break;
4825 }
4826 if ((RA - 1).isMinValue()) {
4827 Pred = ICmpInst::ICMP_EQ;
4828 RHS = getConstant(RA - 1);
4829 break;
4830 }
4831 if (RA.isMinValue()) return false;
4832 break;
4833 case ICmpInst::ICMP_SGT:
4834 if (RA.isMinSignedValue()) {
4835 Pred = ICmpInst::ICMP_NE;
4836 break;
4837 }
4838 if ((RA + 1).isMaxSignedValue()) {
4839 Pred = ICmpInst::ICMP_EQ;
4840 RHS = getConstant(RA + 1);
4841 break;
4842 }
4843 if (RA.isMaxSignedValue()) return false;
4844 break;
4845 case ICmpInst::ICMP_SLT:
4846 if (RA.isMaxSignedValue()) {
4847 Pred = ICmpInst::ICMP_NE;
4848 break;
4849 }
4850 if ((RA - 1).isMinSignedValue()) {
4851 Pred = ICmpInst::ICMP_EQ;
4852 RHS = getConstant(RA - 1);
4853 break;
4854 }
4855 if (RA.isMinSignedValue()) return false;
4856 break;
4857 }
4858 }
4859
4860 // Check to see if we can make the LHS or RHS match.
4861 if (LHS == FoundRHS || RHS == FoundLHS) {
4862 if (isa<SCEVConstant>(RHS)) {
4863 std::swap(FoundLHS, FoundRHS);
4864 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4865 } else {
4866 std::swap(LHS, RHS);
4867 Pred = ICmpInst::getSwappedPredicate(Pred);
4868 }
4869 }
4870
4871 // Check whether the found predicate is the same as the desired predicate.
4872 if (FoundPred == Pred)
4873 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4874
4875 // Check whether swapping the found predicate makes it the same as the
4876 // desired predicate.
4877 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4878 if (isa<SCEVConstant>(RHS))
4879 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4880 else
4881 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4882 RHS, LHS, FoundLHS, FoundRHS);
4883 }
4884
4885 // Check whether the actual condition is beyond sufficient.
4886 if (FoundPred == ICmpInst::ICMP_EQ)
4887 if (ICmpInst::isTrueWhenEqual(Pred))
4888 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4889 return true;
4890 if (Pred == ICmpInst::ICMP_NE)
4891 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4892 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4893 return true;
4894
4895 // Otherwise assume the worst.
4896 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004897}
4898
Dan Gohman0f4b2852009-07-21 23:03:19 +00004899/// isImpliedCondOperands - Test whether the condition described by Pred,
4900/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4901/// and FoundRHS is true.
4902bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4903 const SCEV *LHS, const SCEV *RHS,
4904 const SCEV *FoundLHS,
4905 const SCEV *FoundRHS) {
4906 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4907 FoundLHS, FoundRHS) ||
4908 // ~x < ~y --> x > y
4909 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4910 getNotSCEV(FoundRHS),
4911 getNotSCEV(FoundLHS));
4912}
4913
4914/// isImpliedCondOperandsHelper - Test whether the condition described by
4915/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4916/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004917bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004918ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4919 const SCEV *LHS, const SCEV *RHS,
4920 const SCEV *FoundLHS,
4921 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004922 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004923 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4924 case ICmpInst::ICMP_EQ:
4925 case ICmpInst::ICMP_NE:
4926 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4927 return true;
4928 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004929 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004930 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004931 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4932 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4933 return true;
4934 break;
4935 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004936 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004937 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4938 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4939 return true;
4940 break;
4941 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004942 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004943 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4944 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4945 return true;
4946 break;
4947 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004948 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004949 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4950 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4951 return true;
4952 break;
4953 }
4954
4955 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004956}
4957
Dan Gohman51f53b72009-06-21 23:46:38 +00004958/// getBECount - Subtract the end and start values and divide by the step,
4959/// rounding up, to get the number of times the backedge is executed. Return
4960/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004961const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004962 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00004963 const SCEV *Step,
4964 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00004965 assert(!isKnownNegative(Step) &&
4966 "This code doesn't handle negative strides yet!");
4967
Dan Gohman51f53b72009-06-21 23:46:38 +00004968 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004969 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4970 const SCEV *Diff = getMinusSCEV(End, Start);
4971 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004972
4973 // Add an adjustment to the difference between End and Start so that
4974 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004975 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004976
Dan Gohman1f96e672009-09-17 18:05:20 +00004977 if (!NoWrap) {
4978 // Check Add for unsigned overflow.
4979 // TODO: More sophisticated things could be done here.
4980 const Type *WideTy = IntegerType::get(getContext(),
4981 getTypeSizeInBits(Ty) + 1);
4982 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4983 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4984 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4985 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4986 return getCouldNotCompute();
4987 }
Dan Gohman51f53b72009-06-21 23:46:38 +00004988
4989 return getUDivExpr(Add, Step);
4990}
4991
Chris Lattnerdb25de42005-08-15 23:33:51 +00004992/// HowManyLessThans - Return the number of times a backedge containing the
4993/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004994/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004995ScalarEvolution::BackedgeTakenInfo
4996ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4997 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004998 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004999 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005000
Dan Gohman35738ac2009-05-04 22:30:44 +00005001 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005002 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005003 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005004
Dan Gohman1f96e672009-09-17 18:05:20 +00005005 // Check to see if we have a flag which makes analysis easy.
5006 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5007 AddRec->hasNoUnsignedWrap();
5008
Chris Lattnerdb25de42005-08-15 23:33:51 +00005009 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005010 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005011 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005012
Dan Gohman52fddd32010-01-26 04:40:18 +00005013 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005014 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005015 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005016 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005017 } else if (isKnownPositive(Step)) {
5018 // Test whether a positive iteration iteration can step past the limit
5019 // value and past the maximum value for its type in a single step.
5020 // Note that it's not sufficient to check NoWrap here, because even
5021 // though the value after a wrap is undefined, it's not undefined
5022 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005023 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005024 // iterate at least until the iteration where the wrapping occurs.
5025 const SCEV *One = getIntegerSCEV(1, Step->getType());
5026 if (isSigned) {
5027 APInt Max = APInt::getSignedMaxValue(BitWidth);
5028 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5029 .slt(getSignedRange(RHS).getSignedMax()))
5030 return getCouldNotCompute();
5031 } else {
5032 APInt Max = APInt::getMaxValue(BitWidth);
5033 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5034 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5035 return getCouldNotCompute();
5036 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005037 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005038 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005039 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005040
Dan Gohmana1af7572009-04-30 20:47:05 +00005041 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5042 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5043 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005044 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005045
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005046 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005047 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005048
Dan Gohmana1af7572009-04-30 20:47:05 +00005049 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005050 const SCEV *MinStart = getConstant(isSigned ?
5051 getSignedRange(Start).getSignedMin() :
5052 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005053
Dan Gohmana1af7572009-04-30 20:47:05 +00005054 // If we know that the condition is true in order to enter the loop,
5055 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005056 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5057 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005058 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00005059 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00005060 isSigned ? ICmpInst::ICMP_SLT :
5061 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00005062 getMinusSCEV(Start, Step), RHS))
5063 End = isSigned ? getSMaxExpr(RHS, Start)
5064 : getUMaxExpr(RHS, Start);
5065
5066 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005067 const SCEV *MaxEnd = getConstant(isSigned ?
5068 getSignedRange(End).getSignedMax() :
5069 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005070
Dan Gohman52fddd32010-01-26 04:40:18 +00005071 // If MaxEnd is within a step of the maximum integer value in its type,
5072 // adjust it down to the minimum value which would produce the same effect.
5073 // This allows the subsequent ceiling divison of (N+(step-1))/step to
5074 // compute the correct value.
5075 const SCEV *StepMinusOne = getMinusSCEV(Step,
5076 getIntegerSCEV(1, Step->getType()));
5077 MaxEnd = isSigned ?
5078 getSMinExpr(MaxEnd,
5079 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5080 StepMinusOne)) :
5081 getUMinExpr(MaxEnd,
5082 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5083 StepMinusOne));
5084
Dan Gohmana1af7572009-04-30 20:47:05 +00005085 // Finally, we subtract these two values and divide, rounding up, to get
5086 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005087 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005088
5089 // The maximum backedge count is similar, except using the minimum start
5090 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005091 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005092
5093 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005094 }
5095
Dan Gohman1c343752009-06-27 21:21:31 +00005096 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005097}
5098
Chris Lattner53e677a2004-04-02 20:23:17 +00005099/// getNumIterationsInRange - Return the number of iterations of this loop that
5100/// produce values in the specified constant range. Another way of looking at
5101/// this is that it returns the first iteration number where the value is not in
5102/// the condition, thus computing the exit count. If the iteration count can't
5103/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005104const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005105 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005106 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005107 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005108
5109 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005110 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005111 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005112 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005113 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005114 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005115 if (const SCEVAddRecExpr *ShiftedAddRec =
5116 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005117 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005118 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005119 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005120 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005121 }
5122
5123 // The only time we can solve this is when we have all constant indices.
5124 // Otherwise, we cannot determine the overflow conditions.
5125 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5126 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005127 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005128
5129
5130 // Okay at this point we know that all elements of the chrec are constants and
5131 // that the start element is zero.
5132
5133 // First check to see if the range contains zero. If not, the first
5134 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005135 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005136 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005137 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005138
Chris Lattner53e677a2004-04-02 20:23:17 +00005139 if (isAffine()) {
5140 // If this is an affine expression then we have this situation:
5141 // Solve {0,+,A} in Range === Ax in Range
5142
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005143 // We know that zero is in the range. If A is positive then we know that
5144 // the upper value of the range must be the first possible exit value.
5145 // If A is negative then the lower of the range is the last possible loop
5146 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005147 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005148 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5149 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005150
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005151 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005152 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005153 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005154
5155 // Evaluate at the exit value. If we really did fall out of the valid
5156 // range, then we computed our trip count, otherwise wrap around or other
5157 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005158 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005159 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005160 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005161
5162 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005163 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005164 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005165 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005166 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005167 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005168 } else if (isQuadratic()) {
5169 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5170 // quadratic equation to solve it. To do this, we must frame our problem in
5171 // terms of figuring out when zero is crossed, instead of when
5172 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005173 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005174 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005175 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005176
5177 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005178 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005179 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005180 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5181 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005182 if (R1) {
5183 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005184 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005185 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005186 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005187 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005188 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005189
Chris Lattner53e677a2004-04-02 20:23:17 +00005190 // Make sure the root is not off by one. The returned iteration should
5191 // not be in the range, but the previous one should be. When solving
5192 // for "X*X < 5", for example, we should not return a root of 2.
5193 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005194 R1->getValue(),
5195 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005196 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005197 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005198 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005199 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005200
Dan Gohman246b2562007-10-22 18:31:58 +00005201 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005202 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005203 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005204 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005205 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005206
Chris Lattner53e677a2004-04-02 20:23:17 +00005207 // If R1 was not in the range, then it is a good return value. Make
5208 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005209 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005210 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005211 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005212 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005213 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005214 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005215 }
5216 }
5217 }
5218
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005219 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005220}
5221
5222
5223
5224//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005225// SCEVCallbackVH Class Implementation
5226//===----------------------------------------------------------------------===//
5227
Dan Gohman1959b752009-05-19 19:22:47 +00005228void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005229 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005230 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5231 SE->ConstantEvolutionLoopExitValue.erase(PN);
5232 SE->Scalars.erase(getValPtr());
5233 // this now dangles!
5234}
5235
Dan Gohman1959b752009-05-19 19:22:47 +00005236void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005237 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005238
5239 // Forget all the expressions associated with users of the old value,
5240 // so that future queries will recompute the expressions using the new
5241 // value.
5242 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005243 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005244 Value *Old = getValPtr();
5245 bool DeleteOld = false;
5246 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5247 UI != UE; ++UI)
5248 Worklist.push_back(*UI);
5249 while (!Worklist.empty()) {
5250 User *U = Worklist.pop_back_val();
5251 // Deleting the Old value will cause this to dangle. Postpone
5252 // that until everything else is done.
5253 if (U == Old) {
5254 DeleteOld = true;
5255 continue;
5256 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005257 if (!Visited.insert(U))
5258 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005259 if (PHINode *PN = dyn_cast<PHINode>(U))
5260 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005261 SE->Scalars.erase(U);
5262 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5263 UI != UE; ++UI)
5264 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005265 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005266 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005267 if (DeleteOld) {
5268 if (PHINode *PN = dyn_cast<PHINode>(Old))
5269 SE->ConstantEvolutionLoopExitValue.erase(PN);
5270 SE->Scalars.erase(Old);
5271 // this now dangles!
5272 }
5273 // this may dangle!
5274}
5275
Dan Gohman1959b752009-05-19 19:22:47 +00005276ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005277 : CallbackVH(V), SE(se) {}
5278
5279//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005280// ScalarEvolution Class Implementation
5281//===----------------------------------------------------------------------===//
5282
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005283ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005284 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005285}
5286
Chris Lattner53e677a2004-04-02 20:23:17 +00005287bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005288 this->F = &F;
5289 LI = &getAnalysis<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005290 DT = &getAnalysis<DominatorTree>();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005291 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005292 return false;
5293}
5294
5295void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005296 Scalars.clear();
5297 BackedgeTakenCounts.clear();
5298 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005299 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005300 UniqueSCEVs.clear();
5301 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005302}
5303
5304void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5305 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005306 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005307 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005308}
5309
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005310bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005311 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005312}
5313
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005314static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005315 const Loop *L) {
5316 // Print all inner loops first
5317 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5318 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005319
Dan Gohman30733292010-01-09 18:17:45 +00005320 OS << "Loop ";
5321 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5322 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005323
Dan Gohman5d984912009-12-18 01:14:11 +00005324 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005325 L->getExitBlocks(ExitBlocks);
5326 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005327 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005328
Dan Gohman46bdfb02009-02-24 18:55:53 +00005329 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5330 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005331 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005332 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005333 }
5334
Dan Gohman30733292010-01-09 18:17:45 +00005335 OS << "\n"
5336 "Loop ";
5337 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5338 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005339
5340 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5341 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5342 } else {
5343 OS << "Unpredictable max backedge-taken count. ";
5344 }
5345
5346 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005347}
5348
Dan Gohman5d984912009-12-18 01:14:11 +00005349void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005350 // ScalarEvolution's implementaiton of the print method is to print
5351 // out SCEV values of all instructions that are interesting. Doing
5352 // this potentially causes it to create new SCEV objects though,
5353 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005354 // observable from outside the class though, so casting away the
5355 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005356 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005357
Dan Gohman30733292010-01-09 18:17:45 +00005358 OS << "Classifying expressions for: ";
5359 WriteAsOperand(OS, F, /*PrintType=*/false);
5360 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005361 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005362 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005363 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005364 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005365 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005366 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005367
Dan Gohman0c689c52009-06-19 17:49:54 +00005368 const Loop *L = LI->getLoopFor((*I).getParent());
5369
Dan Gohman0bba49c2009-07-07 17:06:11 +00005370 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005371 if (AtUse != SV) {
5372 OS << " --> ";
5373 AtUse->print(OS);
5374 }
5375
5376 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005377 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005378 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005379 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005380 OS << "<<Unknown>>";
5381 } else {
5382 OS << *ExitValue;
5383 }
5384 }
5385
Chris Lattner53e677a2004-04-02 20:23:17 +00005386 OS << "\n";
5387 }
5388
Dan Gohman30733292010-01-09 18:17:45 +00005389 OS << "Determining loop execution counts for: ";
5390 WriteAsOperand(OS, F, /*PrintType=*/false);
5391 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005392 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5393 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005394}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005395