blob: 8b7d8f2740f9f1b8b3ef03b299079c5d3df57c8a [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"
Duncan Sandsa0c52442010-11-17 04:18:45 +000072#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000073#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000074#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000076#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000077#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000078#include "llvm/Support/ConstantRange.h"
David Greene63c94632009-12-23 22:58:38 +000079#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000080#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000081#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000082#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000083#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000084#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000085#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000086#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000087#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000088#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000089using namespace llvm;
90
Chris Lattner3b27d682006-12-19 22:30:33 +000091STATISTIC(NumArrayLenItCounts,
92 "Number of trip counts computed with array length");
93STATISTIC(NumTripCountsComputed,
94 "Number of loops with predictable loop counts");
95STATISTIC(NumTripCountsNotComputed,
96 "Number of loops without predictable loop counts");
97STATISTIC(NumBruteForceTripCountsComputed,
98 "Number of loops with trip counts computed by force");
99
Dan Gohman844731a2008-05-13 00:00:25 +0000100static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000101MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
102 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000103 "symbolically execute a constant "
104 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000105 cl::init(100));
106
Owen Anderson2ab36d32010-10-12 19:48:12 +0000107INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
108 "Scalar Evolution Analysis", false, true)
109INITIALIZE_PASS_DEPENDENCY(LoopInfo)
110INITIALIZE_PASS_DEPENDENCY(DominatorTree)
111INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
Owen Andersonce665bd2010-10-07 22:25:06 +0000112 "Scalar Evolution Analysis", false, true)
Devang Patel19974732007-05-03 01:11:54 +0000113char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000114
115//===----------------------------------------------------------------------===//
116// SCEV class definitions
117//===----------------------------------------------------------------------===//
118
119//===----------------------------------------------------------------------===//
120// Implementation of the SCEV class.
121//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000122
Chris Lattner53e677a2004-04-02 20:23:17 +0000123SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000124
Chris Lattner53e677a2004-04-02 20:23:17 +0000125void SCEV::dump() const {
David Greene25e0e872009-12-23 22:18:14 +0000126 print(dbgs());
127 dbgs() << '\n';
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000128}
129
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000130bool SCEV::isZero() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isZero();
133 return false;
134}
135
Dan Gohman70a1fe72009-05-18 15:22:39 +0000136bool SCEV::isOne() const {
137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
138 return SC->getValue()->isOne();
139 return false;
140}
Chris Lattner53e677a2004-04-02 20:23:17 +0000141
Dan Gohman4d289bf2009-06-24 00:30:26 +0000142bool SCEV::isAllOnesValue() const {
143 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
144 return SC->getValue()->isAllOnesValue();
145 return false;
146}
147
Owen Anderson753ad612009-06-22 21:57:23 +0000148SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman3bf63762010-06-18 19:54:20 +0000149 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000150
Chris Lattner53e677a2004-04-02 20:23:17 +0000151const 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
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000156bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
157 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
158 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000159}
160
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000161void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000162 OS << "***COULDNOTCOMPUTE***";
163}
164
165bool SCEVCouldNotCompute::classof(const SCEV *S) {
166 return S->getSCEVType() == scCouldNotCompute;
167}
168
Dan Gohman0bba49c2009-07-07 17:06:11 +0000169const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000170 FoldingSetNodeID ID;
171 ID.AddInteger(scConstant);
172 ID.AddPointer(V);
173 void *IP = 0;
174 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3bf63762010-06-18 19:54:20 +0000175 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohman1c343752009-06-27 21:21:31 +0000176 UniqueSCEVs.InsertNode(S, IP);
177 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178}
Chris Lattner53e677a2004-04-02 20:23:17 +0000179
Dan Gohman0bba49c2009-07-07 17:06:11 +0000180const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000181 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000182}
183
Dan Gohman0bba49c2009-07-07 17:06:11 +0000184const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000185ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Dan Gohmana560fd22010-04-21 16:04:04 +0000186 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
187 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000188}
189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000191
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000192void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193 WriteAsOperand(OS, V, false);
194}
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Dan Gohman3bf63762010-06-18 19:54:20 +0000196SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000197 unsigned SCEVTy, const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000198 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000199
Dan Gohman3bf63762010-06-18 19:54:20 +0000200SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000201 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000202 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000203 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
204 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206}
Chris Lattner53e677a2004-04-02 20:23:17 +0000207
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000208void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000209 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210}
211
Dan Gohman3bf63762010-06-18 19:54:20 +0000212SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000213 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000214 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000215 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
216 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218}
219
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000220void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000221 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000222}
223
Dan Gohman3bf63762010-06-18 19:54:20 +0000224SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Dan Gohmanc050fd92009-07-13 20:50:19 +0000225 const SCEV *op, const Type *ty)
Dan Gohman3bf63762010-06-18 19:54:20 +0000226 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands1df98592010-02-16 11:11:14 +0000227 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
228 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000229 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000230}
231
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000232void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000233 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000234}
235
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000236void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000237 const char *OpStr = getOperationStr();
Dan Gohmana5145c82010-04-16 15:03:25 +0000238 OS << "(";
239 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
240 OS << **I;
Oscar Fuentesee56c422010-08-02 06:00:15 +0000241 if (llvm::next(I) != E)
Dan Gohmana5145c82010-04-16 15:03:25 +0000242 OS << OpStr;
243 }
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000244 OS << ")";
245}
246
Dan Gohman2f199f92010-08-16 16:21:27 +0000247bool SCEVNAryExpr::hasOperand(const SCEV *O) const {
248 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
249 const SCEV *S = *I;
250 if (O == S || S->hasOperand(O))
251 return true;
252 }
253 return false;
254}
255
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000256void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000257 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000258}
259
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000260const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000261 // In most cases the types of LHS and RHS will be the same, but in some
262 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
263 // depend on the type for correctness, but handling types carefully can
264 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
265 // a pointer type than the RHS, so use the RHS' type here.
266 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000267}
268
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000269void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000270 OS << "{" << *Operands[0];
Dan Gohmanf9e64722010-03-18 01:17:13 +0000271 for (unsigned i = 1, e = NumOperands; i != e; ++i)
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000272 OS << ",+," << *Operands[i];
Dan Gohman30733292010-01-09 18:17:45 +0000273 OS << "}<";
274 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
275 OS << ">";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000276}
Chris Lattner53e677a2004-04-02 20:23:17 +0000277
Dan Gohmanab37f502010-08-02 23:49:30 +0000278void SCEVUnknown::deleted() {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000279 // Clear this SCEVUnknown from various maps.
Dan Gohmanab37f502010-08-02 23:49:30 +0000280 SE->ValuesAtScopes.erase(this);
Dan Gohman6678e7b2010-11-17 02:44:44 +0000281 SE->UnsignedRanges.erase(this);
282 SE->SignedRanges.erase(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000283
284 // Remove this SCEVUnknown from the uniquing map.
285 SE->UniqueSCEVs.RemoveNode(this);
286
287 // Release the value.
288 setValPtr(0);
289}
290
291void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman6678e7b2010-11-17 02:44:44 +0000292 // Clear this SCEVUnknown from various maps.
Dan Gohmanab37f502010-08-02 23:49:30 +0000293 SE->ValuesAtScopes.erase(this);
Dan Gohman6678e7b2010-11-17 02:44:44 +0000294 SE->UnsignedRanges.erase(this);
295 SE->SignedRanges.erase(this);
Dan Gohmanab37f502010-08-02 23:49:30 +0000296
297 // Remove this SCEVUnknown from the uniquing map.
298 SE->UniqueSCEVs.RemoveNode(this);
299
300 // Update this SCEVUnknown to point to the new value. This is needed
301 // because there may still be outstanding SCEVs which still point to
302 // this SCEVUnknown.
303 setValPtr(New);
304}
305
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000306const Type *SCEVUnknown::getType() const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000307 return getValue()->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000308}
Chris Lattner53e677a2004-04-02 20:23:17 +0000309
Dan Gohman0f5efe52010-01-28 02:15:55 +0000310bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000311 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000312 if (VCE->getOpcode() == Instruction::PtrToInt)
313 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000314 if (CE->getOpcode() == Instruction::GetElementPtr &&
315 CE->getOperand(0)->isNullValue() &&
316 CE->getNumOperands() == 2)
317 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
318 if (CI->isOne()) {
319 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
320 ->getElementType();
321 return true;
322 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000323
324 return false;
325}
326
327bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000328 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman0f5efe52010-01-28 02:15:55 +0000329 if (VCE->getOpcode() == Instruction::PtrToInt)
330 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman8db08df2010-02-02 01:38:49 +0000331 if (CE->getOpcode() == Instruction::GetElementPtr &&
332 CE->getOperand(0)->isNullValue()) {
333 const Type *Ty =
334 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
335 if (const StructType *STy = dyn_cast<StructType>(Ty))
336 if (!STy->isPacked() &&
337 CE->getNumOperands() == 3 &&
338 CE->getOperand(1)->isNullValue()) {
339 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
340 if (CI->isOne() &&
341 STy->getNumElements() == 2 &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000342 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman8db08df2010-02-02 01:38:49 +0000343 AllocTy = STy->getElementType(1);
344 return true;
345 }
346 }
347 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000348
349 return false;
350}
351
Dan Gohman4f8eea82010-02-01 18:27:38 +0000352bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
Dan Gohmanab37f502010-08-02 23:49:30 +0000353 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohman4f8eea82010-02-01 18:27:38 +0000354 if (VCE->getOpcode() == Instruction::PtrToInt)
355 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
356 if (CE->getOpcode() == Instruction::GetElementPtr &&
357 CE->getNumOperands() == 3 &&
358 CE->getOperand(0)->isNullValue() &&
359 CE->getOperand(1)->isNullValue()) {
360 const Type *Ty =
361 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
362 // Ignore vector types here so that ScalarEvolutionExpander doesn't
363 // emit getelementptrs that index into vectors.
Duncan Sands1df98592010-02-16 11:11:14 +0000364 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000365 CTy = Ty;
366 FieldNo = CE->getOperand(2);
367 return true;
368 }
369 }
370
371 return false;
372}
373
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000374void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000375 const Type *AllocTy;
376 if (isSizeOf(AllocTy)) {
377 OS << "sizeof(" << *AllocTy << ")";
378 return;
379 }
380 if (isAlignOf(AllocTy)) {
381 OS << "alignof(" << *AllocTy << ")";
382 return;
383 }
384
Dan Gohman4f8eea82010-02-01 18:27:38 +0000385 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000386 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000387 if (isOffsetOf(CTy, FieldNo)) {
388 OS << "offsetof(" << *CTy << ", ";
Dan Gohman0f5efe52010-01-28 02:15:55 +0000389 WriteAsOperand(OS, FieldNo, false);
390 OS << ")";
391 return;
392 }
393
394 // Otherwise just print it normally.
Dan Gohmanab37f502010-08-02 23:49:30 +0000395 WriteAsOperand(OS, getValue(), false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000396}
397
Chris Lattner8d741b82004-06-20 06:23:15 +0000398//===----------------------------------------------------------------------===//
399// SCEV Utilities
400//===----------------------------------------------------------------------===//
401
402namespace {
403 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
404 /// than the complexity of the RHS. This comparator is used to canonicalize
405 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000406 class SCEVComplexityCompare {
Dan Gohman9f1fb422010-08-13 20:17:27 +0000407 const LoopInfo *const LI;
Dan Gohman72861302009-05-07 14:39:04 +0000408 public:
Dan Gohmane72079a2010-07-23 21:18:55 +0000409 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman72861302009-05-07 14:39:04 +0000410
Dan Gohman67ef74e2010-08-27 15:26:01 +0000411 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000412 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman67ef74e2010-08-27 15:26:01 +0000413 return compare(LHS, RHS) < 0;
414 }
415
416 // Return negative, zero, or positive, if LHS is less than, equal to, or
417 // greater than RHS, respectively. A three-way result allows recursive
418 // comparisons to be more efficient.
419 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000420 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
421 if (LHS == RHS)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000422 return 0;
Dan Gohman42214892009-08-31 21:15:23 +0000423
Dan Gohman72861302009-05-07 14:39:04 +0000424 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman304a7a62010-07-23 21:20:52 +0000425 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
426 if (LType != RType)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000427 return (int)LType - (int)RType;
Dan Gohman72861302009-05-07 14:39:04 +0000428
Dan Gohman3bf63762010-06-18 19:54:20 +0000429 // Aside from the getSCEVType() ordering, the particular ordering
430 // isn't very important except that it's beneficial to be consistent,
431 // so that (a + b) and (b + a) don't end up as different expressions.
Dan Gohman67ef74e2010-08-27 15:26:01 +0000432 switch (LType) {
433 case scUnknown: {
434 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000435 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000436
437 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
438 // not as complete as it could be.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000439 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman3bf63762010-06-18 19:54:20 +0000440
441 // Order pointer values after integer values. This helps SCEVExpander
442 // form GEPs.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000443 bool LIsPointer = LV->getType()->isPointerTy(),
444 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman304a7a62010-07-23 21:20:52 +0000445 if (LIsPointer != RIsPointer)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000446 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman3bf63762010-06-18 19:54:20 +0000447
448 // Compare getValueID values.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000449 unsigned LID = LV->getValueID(),
450 RID = RV->getValueID();
Dan Gohman304a7a62010-07-23 21:20:52 +0000451 if (LID != RID)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000452 return (int)LID - (int)RID;
Dan Gohman3bf63762010-06-18 19:54:20 +0000453
454 // Sort arguments by their position.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000455 if (const Argument *LA = dyn_cast<Argument>(LV)) {
456 const Argument *RA = cast<Argument>(RV);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000457 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
458 return (int)LArgNo - (int)RArgNo;
Dan Gohman3bf63762010-06-18 19:54:20 +0000459 }
460
Dan Gohman67ef74e2010-08-27 15:26:01 +0000461 // For instructions, compare their loop depth, and their operand
462 // count. This is pretty loose.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000463 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
464 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman3bf63762010-06-18 19:54:20 +0000465
466 // Compare loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000467 const BasicBlock *LParent = LInst->getParent(),
468 *RParent = RInst->getParent();
469 if (LParent != RParent) {
470 unsigned LDepth = LI->getLoopDepth(LParent),
471 RDepth = LI->getLoopDepth(RParent);
472 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000473 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000474 }
Dan Gohman3bf63762010-06-18 19:54:20 +0000475
476 // Compare the number of operands.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000477 unsigned LNumOps = LInst->getNumOperands(),
478 RNumOps = RInst->getNumOperands();
Dan Gohman67ef74e2010-08-27 15:26:01 +0000479 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000480 }
481
Dan Gohman67ef74e2010-08-27 15:26:01 +0000482 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000483 }
484
Dan Gohman67ef74e2010-08-27 15:26:01 +0000485 case scConstant: {
486 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000487 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000488
489 // Compare constant values.
Dan Gohmane28d7922010-08-16 16:25:35 +0000490 const APInt &LA = LC->getValue()->getValue();
491 const APInt &RA = RC->getValue()->getValue();
492 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman304a7a62010-07-23 21:20:52 +0000493 if (LBitWidth != RBitWidth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000494 return (int)LBitWidth - (int)RBitWidth;
495 return LA.ult(RA) ? -1 : 1;
Dan Gohman3bf63762010-06-18 19:54:20 +0000496 }
497
Dan Gohman67ef74e2010-08-27 15:26:01 +0000498 case scAddRecExpr: {
499 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000500 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000501
502 // Compare addrec loop depths.
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000503 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
504 if (LLoop != RLoop) {
505 unsigned LDepth = LLoop->getLoopDepth(),
506 RDepth = RLoop->getLoopDepth();
507 if (LDepth != RDepth)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000508 return (int)LDepth - (int)RDepth;
Dan Gohman0ad2c7a2010-08-13 21:24:58 +0000509 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000510
511 // Addrec complexity grows with operand count.
512 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
513 if (LNumOps != RNumOps)
514 return (int)LNumOps - (int)RNumOps;
515
516 // Lexicographically compare.
517 for (unsigned i = 0; i != LNumOps; ++i) {
518 long X = compare(LA->getOperand(i), RA->getOperand(i));
519 if (X != 0)
520 return X;
521 }
522
523 return 0;
Dan Gohman3bf63762010-06-18 19:54:20 +0000524 }
525
Dan Gohman67ef74e2010-08-27 15:26:01 +0000526 case scAddExpr:
527 case scMulExpr:
528 case scSMaxExpr:
529 case scUMaxExpr: {
530 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000531 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000532
533 // Lexicographically compare n-ary expressions.
Dan Gohman304a7a62010-07-23 21:20:52 +0000534 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
535 for (unsigned i = 0; i != LNumOps; ++i) {
536 if (i >= RNumOps)
Dan Gohman67ef74e2010-08-27 15:26:01 +0000537 return 1;
538 long X = compare(LC->getOperand(i), RC->getOperand(i));
539 if (X != 0)
540 return X;
Dan Gohman3bf63762010-06-18 19:54:20 +0000541 }
Dan Gohman67ef74e2010-08-27 15:26:01 +0000542 return (int)LNumOps - (int)RNumOps;
Dan Gohman3bf63762010-06-18 19:54:20 +0000543 }
544
Dan Gohman67ef74e2010-08-27 15:26:01 +0000545 case scUDivExpr: {
546 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000547 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000548
549 // Lexicographically compare udiv expressions.
550 long X = compare(LC->getLHS(), RC->getLHS());
551 if (X != 0)
552 return X;
553 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman3bf63762010-06-18 19:54:20 +0000554 }
555
Dan Gohman67ef74e2010-08-27 15:26:01 +0000556 case scTruncate:
557 case scZeroExtend:
558 case scSignExtend: {
559 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman3bf63762010-06-18 19:54:20 +0000560 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman67ef74e2010-08-27 15:26:01 +0000561
562 // Compare cast expressions by operand.
563 return compare(LC->getOperand(), RC->getOperand());
564 }
565
566 default:
567 break;
Dan Gohman3bf63762010-06-18 19:54:20 +0000568 }
569
570 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman67ef74e2010-08-27 15:26:01 +0000571 return 0;
Chris Lattner8d741b82004-06-20 06:23:15 +0000572 }
573 };
574}
575
576/// GroupByComplexity - Given a list of SCEV objects, order them by their
577/// complexity, and group objects of the same complexity together by value.
578/// When this routine is finished, we know that any duplicates in the vector are
579/// consecutive and that complexity is monotonically increasing.
580///
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000581/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattner8d741b82004-06-20 06:23:15 +0000582/// results from this routine. In other words, we don't want the results of
583/// this to depend on where the addresses of various SCEV objects happened to
584/// land in memory.
585///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000586static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000587 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000588 if (Ops.size() < 2) return; // Noop
589 if (Ops.size() == 2) {
590 // This is the common case, which also happens to be trivially simple.
591 // Special case it.
Dan Gohmanc6a8e992010-08-29 15:07:13 +0000592 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
593 if (SCEVComplexityCompare(LI)(RHS, LHS))
594 std::swap(LHS, RHS);
Chris Lattner8d741b82004-06-20 06:23:15 +0000595 return;
596 }
597
Dan Gohman3bf63762010-06-18 19:54:20 +0000598 // Do the rough sort by complexity.
599 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
600
601 // Now that we are sorted by complexity, group elements of the same
602 // complexity. Note that this is, at worst, N^2, but the vector is likely to
603 // be extremely short in practice. Note that we take this approach because we
604 // do not want to depend on the addresses of the objects we are grouping.
605 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
606 const SCEV *S = Ops[i];
607 unsigned Complexity = S->getSCEVType();
608
609 // If there are any objects of the same complexity and same value as this
610 // one, group them.
611 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
612 if (Ops[j] == S) { // Found a duplicate.
613 // Move it to immediately after i'th element.
614 std::swap(Ops[i+1], Ops[j]);
615 ++i; // no need to rescan it.
616 if (i == e-2) return; // Done!
617 }
618 }
619 }
Chris Lattner8d741b82004-06-20 06:23:15 +0000620}
621
Chris Lattner53e677a2004-04-02 20:23:17 +0000622
Chris Lattner53e677a2004-04-02 20:23:17 +0000623
624//===----------------------------------------------------------------------===//
625// Simple SCEV method implementations
626//===----------------------------------------------------------------------===//
627
Eli Friedmanb42a6262008-08-04 23:49:06 +0000628/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000629/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000630static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000631 ScalarEvolution &SE,
632 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000633 // Handle the simplest case efficiently.
634 if (K == 1)
635 return SE.getTruncateOrZeroExtend(It, ResultTy);
636
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000637 // We are using the following formula for BC(It, K):
638 //
639 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
640 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000641 // Suppose, W is the bitwidth of the return value. We must be prepared for
642 // overflow. Hence, we must assure that the result of our computation is
643 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
644 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000645 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000646 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000647 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000648 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
649 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000650 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000651 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000652 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000653 // This formula is trivially equivalent to the previous formula. However,
654 // this formula can be implemented much more efficiently. The trick is that
655 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
656 // arithmetic. To do exact division in modular arithmetic, all we have
657 // to do is multiply by the inverse. Therefore, this step can be done at
658 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000659 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000660 // The next issue is how to safely do the division by 2^T. The way this
661 // is done is by doing the multiplication step at a width of at least W + T
662 // bits. This way, the bottom W+T bits of the product are accurate. Then,
663 // when we perform the division by 2^T (which is equivalent to a right shift
664 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
665 // truncated out after the division by 2^T.
666 //
667 // In comparison to just directly using the first formula, this technique
668 // is much more efficient; using the first formula requires W * K bits,
669 // but this formula less than W + K bits. Also, the first formula requires
670 // a division step, whereas this formula only requires multiplies and shifts.
671 //
672 // It doesn't matter whether the subtraction step is done in the calculation
673 // width or the input iteration count's width; if the subtraction overflows,
674 // the result must be zero anyway. We prefer here to do it in the width of
675 // the induction variable because it helps a lot for certain cases; CodeGen
676 // isn't smart enough to ignore the overflow, which leads to much less
677 // efficient code if the width of the subtraction is wider than the native
678 // register width.
679 //
680 // (It's possible to not widen at all by pulling out factors of 2 before
681 // the multiplication; for example, K=2 can be calculated as
682 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
683 // extra arithmetic, so it's not an obvious win, and it gets
684 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000685
Eli Friedmanb42a6262008-08-04 23:49:06 +0000686 // Protection from insane SCEVs; this bound is conservative,
687 // but it probably doesn't matter.
688 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000689 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000690
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000691 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000692
Eli Friedmanb42a6262008-08-04 23:49:06 +0000693 // Calculate K! / 2^T and T; we divide out the factors of two before
694 // multiplying for calculating K! / 2^T to avoid overflow.
695 // Other overflow doesn't matter because we only care about the bottom
696 // W bits of the result.
697 APInt OddFactorial(W, 1);
698 unsigned T = 1;
699 for (unsigned i = 3; i <= K; ++i) {
700 APInt Mult(W, i);
701 unsigned TwoFactors = Mult.countTrailingZeros();
702 T += TwoFactors;
703 Mult = Mult.lshr(TwoFactors);
704 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000705 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000706
Eli Friedmanb42a6262008-08-04 23:49:06 +0000707 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000708 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000709
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000710 // Calculate 2^T, at width T+W.
Eli Friedmanb42a6262008-08-04 23:49:06 +0000711 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
712
713 // Calculate the multiplicative inverse of K! / 2^T;
714 // this multiplication factor will perform the exact division by
715 // K! / 2^T.
716 APInt Mod = APInt::getSignedMinValue(W+1);
717 APInt MultiplyFactor = OddFactorial.zext(W+1);
718 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
719 MultiplyFactor = MultiplyFactor.trunc(W);
720
721 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000722 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
723 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000724 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000725 for (unsigned i = 1; i != K; ++i) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000726 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000727 Dividend = SE.getMulExpr(Dividend,
728 SE.getTruncateOrZeroExtend(S, CalculationTy));
729 }
730
731 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000732 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000733
734 // Truncate the result, and divide by K! / 2^T.
735
736 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
737 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000738}
739
Chris Lattner53e677a2004-04-02 20:23:17 +0000740/// evaluateAtIteration - Return the value of this chain of recurrences at
741/// the specified iteration number. We can evaluate this recurrence by
742/// multiplying each element in the chain by the binomial coefficient
743/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
744///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000745/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000746///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000747/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000748///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000749const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000750 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000751 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000752 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000753 // The computation is correct in the face of overflow provided that the
754 // multiplication is performed _after_ the evaluation of the binomial
755 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000756 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000757 if (isa<SCEVCouldNotCompute>(Coeff))
758 return Coeff;
759
760 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000761 }
762 return Result;
763}
764
Chris Lattner53e677a2004-04-02 20:23:17 +0000765//===----------------------------------------------------------------------===//
766// SCEV Expression folder implementations
767//===----------------------------------------------------------------------===//
768
Dan Gohman0bba49c2009-07-07 17:06:11 +0000769const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000770 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000771 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000772 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000773 assert(isSCEVable(Ty) &&
774 "This is not a conversion to a SCEVable type!");
775 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000776
Dan Gohmanc050fd92009-07-13 20:50:19 +0000777 FoldingSetNodeID ID;
778 ID.AddInteger(scTruncate);
779 ID.AddPointer(Op);
780 ID.AddPointer(Ty);
781 void *IP = 0;
782 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
783
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000784 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000785 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000786 return getConstant(
Dan Gohman1faa8822010-06-24 16:33:38 +0000787 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(),
788 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000789
Dan Gohman20900ca2009-04-22 16:20:48 +0000790 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000791 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000792 return getTruncateExpr(ST->getOperand(), Ty);
793
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000794 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000795 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000796 return getTruncateOrSignExtend(SS->getOperand(), Ty);
797
798 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000799 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000800 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
801
Dan Gohman6864db62009-06-18 16:24:47 +0000802 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000803 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000804 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000805 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000806 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
807 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000808 }
809
Dan Gohmanf53462d2010-07-15 20:02:11 +0000810 // As a special case, fold trunc(undef) to undef. We don't want to
811 // know too much about SCEVUnknowns, but this special case is handy
812 // and harmless.
813 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
814 if (isa<UndefValue>(U->getValue()))
815 return getSCEV(UndefValue::get(Ty));
816
Dan Gohman420ab912010-06-25 18:47:08 +0000817 // The cast wasn't folded; create an explicit cast node. We can reuse
818 // the existing insert position since if we get here, we won't have
819 // made any changes which would invalidate it.
Dan Gohman95531882010-03-18 18:49:47 +0000820 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
821 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000822 UniqueSCEVs.InsertNode(S, IP);
823 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000824}
825
Dan Gohman0bba49c2009-07-07 17:06:11 +0000826const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000827 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000828 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000829 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000830 assert(isSCEVable(Ty) &&
831 "This is not a conversion to a SCEVable type!");
832 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000833
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000834 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000835 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
836 return getConstant(
837 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(),
838 getEffectiveSCEVType(Ty))));
Chris Lattner53e677a2004-04-02 20:23:17 +0000839
Dan Gohman20900ca2009-04-22 16:20:48 +0000840 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000841 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000842 return getZeroExtendExpr(SZ->getOperand(), Ty);
843
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000844 // Before doing any expensive analysis, check to see if we've already
845 // computed a SCEV for this Op and Ty.
846 FoldingSetNodeID ID;
847 ID.AddInteger(scZeroExtend);
848 ID.AddPointer(Op);
849 ID.AddPointer(Ty);
850 void *IP = 0;
851 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
852
Dan Gohman01ecca22009-04-27 20:16:15 +0000853 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000854 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000855 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000856 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000857 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000858 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000859 const SCEV *Start = AR->getStart();
860 const SCEV *Step = AR->getStepRecurrence(*this);
861 unsigned BitWidth = getTypeSizeInBits(AR->getType());
862 const Loop *L = AR->getLoop();
863
Dan Gohmaneb490a72009-07-25 01:22:26 +0000864 // If we have special knowledge that this addrec won't overflow,
865 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000866 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000867 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
868 getZeroExtendExpr(Step, Ty),
869 L);
870
Dan Gohman01ecca22009-04-27 20:16:15 +0000871 // Check whether the backedge-taken count is SCEVCouldNotCompute.
872 // Note that this serves two purposes: It filters out loops that are
873 // simply not analyzable, and it covers the case where this code is
874 // being called from within backedge-taken count analysis, such that
875 // attempting to ask for the backedge-taken count would likely result
876 // in infinite recursion. In the later case, the analysis code will
877 // cope with a conservative value, and it will take care to purge
878 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000879 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000880 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000881 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000882 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000883
884 // Check whether the backedge-taken count can be losslessly casted to
885 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000886 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000887 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000888 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000889 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
890 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000891 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000892 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +0000893 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000894 const SCEV *Add = getAddExpr(Start, ZMul);
895 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000896 getAddExpr(getZeroExtendExpr(Start, WideTy),
897 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
898 getZeroExtendExpr(Step, WideTy)));
899 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000900 // Return the expression with the addrec on the outside.
901 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
902 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000903 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000904
905 // Similar to above, only this time treat the step value as signed.
906 // This covers loops that count down.
Dan Gohman8f767d92010-02-24 19:31:06 +0000907 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohmanac70cea2009-04-29 22:28:28 +0000908 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000909 OperandExtendedAdd =
910 getAddExpr(getZeroExtendExpr(Start, WideTy),
911 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
912 getSignExtendExpr(Step, WideTy)));
913 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000914 // Return the expression with the addrec on the outside.
915 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
916 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000917 L);
918 }
919
920 // If the backedge is guarded by a comparison with the pre-inc value
921 // the addrec is safe. Also, if the entry is guarded by a comparison
922 // with the start value and the backedge is guarded by a comparison
923 // with the post-inc value, the addrec is safe.
924 if (isKnownPositive(Step)) {
925 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
926 getUnsignedRange(Step).getUnsignedMax());
927 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000928 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000929 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
930 AR->getPostIncExpr(*this), N)))
931 // Return the expression with the addrec on the outside.
932 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
933 getZeroExtendExpr(Step, Ty),
934 L);
935 } else if (isKnownNegative(Step)) {
936 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
937 getSignedRange(Step).getSignedMin());
Dan Gohmanc0ed0092010-05-04 01:11:15 +0000938 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
939 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +0000940 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
941 AR->getPostIncExpr(*this), N)))
942 // Return the expression with the addrec on the outside.
943 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
944 getSignExtendExpr(Step, Ty),
945 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000946 }
947 }
948 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000949
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000950 // The cast wasn't folded; create an explicit cast node.
951 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000952 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +0000953 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
954 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000955 UniqueSCEVs.InsertNode(S, IP);
956 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000957}
958
Dan Gohman0bba49c2009-07-07 17:06:11 +0000959const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000960 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000961 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000962 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000963 assert(isSCEVable(Ty) &&
964 "This is not a conversion to a SCEVable type!");
965 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000966
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000967 // Fold if the operand is constant.
Dan Gohmaneaf6cf22010-06-24 16:47:03 +0000968 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
969 return getConstant(
970 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(),
971 getEffectiveSCEVType(Ty))));
Dan Gohmand19534a2007-06-15 14:38:12 +0000972
Dan Gohman20900ca2009-04-22 16:20:48 +0000973 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000974 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000975 return getSignExtendExpr(SS->getOperand(), Ty);
976
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000977 // Before doing any expensive analysis, check to see if we've already
978 // computed a SCEV for this Op and Ty.
979 FoldingSetNodeID ID;
980 ID.AddInteger(scSignExtend);
981 ID.AddPointer(Op);
982 ID.AddPointer(Ty);
983 void *IP = 0;
984 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
985
Dan Gohman01ecca22009-04-27 20:16:15 +0000986 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000987 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000988 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000989 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000990 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000991 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000992 const SCEV *Start = AR->getStart();
993 const SCEV *Step = AR->getStepRecurrence(*this);
994 unsigned BitWidth = getTypeSizeInBits(AR->getType());
995 const Loop *L = AR->getLoop();
996
Dan Gohmaneb490a72009-07-25 01:22:26 +0000997 // If we have special knowledge that this addrec won't overflow,
998 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000999 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +00001000 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1001 getSignExtendExpr(Step, Ty),
1002 L);
1003
Dan Gohman01ecca22009-04-27 20:16:15 +00001004 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1005 // Note that this serves two purposes: It filters out loops that are
1006 // simply not analyzable, and it covers the case where this code is
1007 // being called from within backedge-taken count analysis, such that
1008 // attempting to ask for the backedge-taken count would likely result
1009 // in infinite recursion. In the later case, the analysis code will
1010 // cope with a conservative value, and it will take care to purge
1011 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +00001012 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +00001013 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +00001014 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +00001015 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +00001016
1017 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +00001018 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001019 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +00001020 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001021 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +00001022 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1023 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001024 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +00001025 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman8f767d92010-02-24 19:31:06 +00001026 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001027 const SCEV *Add = getAddExpr(Start, SMul);
1028 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +00001029 getAddExpr(getSignExtendExpr(Start, WideTy),
1030 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1031 getSignExtendExpr(Step, WideTy)));
1032 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +00001033 // Return the expression with the addrec on the outside.
1034 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1035 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +00001036 L);
Dan Gohman850f7912009-07-16 17:34:36 +00001037
1038 // Similar to above, only this time treat the step value as unsigned.
1039 // This covers loops that count up with an unsigned step.
Dan Gohman8f767d92010-02-24 19:31:06 +00001040 const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
Dan Gohman850f7912009-07-16 17:34:36 +00001041 Add = getAddExpr(Start, UMul);
1042 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001043 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001044 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1045 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001046 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001047 // Return the expression with the addrec on the outside.
1048 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1049 getZeroExtendExpr(Step, Ty),
1050 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001051 }
1052
1053 // If the backedge is guarded by a comparison with the pre-inc value
1054 // the addrec is safe. Also, if the entry is guarded by a comparison
1055 // with the start value and the backedge is guarded by a comparison
1056 // with the post-inc value, the addrec is safe.
1057 if (isKnownPositive(Step)) {
1058 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1059 getSignedRange(Step).getSignedMax());
1060 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001061 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001062 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1063 AR->getPostIncExpr(*this), N)))
1064 // Return the expression with the addrec on the outside.
1065 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1066 getSignExtendExpr(Step, Ty),
1067 L);
1068 } else if (isKnownNegative(Step)) {
1069 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1070 getSignedRange(Step).getSignedMin());
1071 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +00001072 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
Dan Gohman85b05a22009-07-13 21:35:55 +00001073 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1074 AR->getPostIncExpr(*this), N)))
1075 // Return the expression with the addrec on the outside.
1076 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1077 getSignExtendExpr(Step, Ty),
1078 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001079 }
1080 }
1081 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001082
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001083 // The cast wasn't folded; create an explicit cast node.
1084 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001085 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman95531882010-03-18 18:49:47 +00001086 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1087 Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001088 UniqueSCEVs.InsertNode(S, IP);
1089 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001090}
1091
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001092/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1093/// unspecified bits out to the given type.
1094///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001095const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001096 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001097 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1098 "This is not an extending conversion!");
1099 assert(isSCEVable(Ty) &&
1100 "This is not a conversion to a SCEVable type!");
1101 Ty = getEffectiveSCEVType(Ty);
1102
1103 // Sign-extend negative constants.
1104 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1105 if (SC->getValue()->getValue().isNegative())
1106 return getSignExtendExpr(Op, Ty);
1107
1108 // Peel off a truncate cast.
1109 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001110 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001111 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1112 return getAnyExtendExpr(NewOp, Ty);
1113 return getTruncateOrNoop(NewOp, Ty);
1114 }
1115
1116 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001117 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001118 if (!isa<SCEVZeroExtendExpr>(ZExt))
1119 return ZExt;
1120
1121 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001122 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001123 if (!isa<SCEVSignExtendExpr>(SExt))
1124 return SExt;
1125
Dan Gohmana10756e2010-01-21 02:09:26 +00001126 // Force the cast to be folded into the operands of an addrec.
1127 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1128 SmallVector<const SCEV *, 4> Ops;
1129 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
1130 I != E; ++I)
1131 Ops.push_back(getAnyExtendExpr(*I, Ty));
1132 return getAddRecExpr(Ops, AR->getLoop());
1133 }
1134
Dan Gohmanf53462d2010-07-15 20:02:11 +00001135 // As a special case, fold anyext(undef) to undef. We don't want to
1136 // know too much about SCEVUnknowns, but this special case is handy
1137 // and harmless.
1138 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Op))
1139 if (isa<UndefValue>(U->getValue()))
1140 return getSCEV(UndefValue::get(Ty));
1141
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001142 // If the expression is obviously signed, use the sext cast value.
1143 if (isa<SCEVSMaxExpr>(Op))
1144 return SExt;
1145
1146 // Absent any other information, use the zext cast value.
1147 return ZExt;
1148}
1149
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001150/// CollectAddOperandsWithScales - Process the given Ops list, which is
1151/// a list of operands to be added under the given scale, update the given
1152/// map. This is a helper function for getAddRecExpr. As an example of
1153/// what it does, given a sequence of operands that would form an add
1154/// expression like this:
1155///
1156/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1157///
1158/// where A and B are constants, update the map with these values:
1159///
1160/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1161///
1162/// and add 13 + A*B*29 to AccumulatedConstant.
1163/// This will allow getAddRecExpr to produce this:
1164///
1165/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1166///
1167/// This form often exposes folding opportunities that are hidden in
1168/// the original operand list.
1169///
1170/// Return true iff it appears that any interesting folding opportunities
1171/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1172/// the common case where no interesting opportunities are present, and
1173/// is also used as a check to avoid infinite recursion.
1174///
1175static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001176CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1177 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001178 APInt &AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001179 const SCEV *const *Ops, size_t NumOperands,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001180 const APInt &Scale,
1181 ScalarEvolution &SE) {
1182 bool Interesting = false;
1183
Dan Gohmane0f0c7b2010-06-18 19:12:32 +00001184 // Iterate over the add operands. They are sorted, with constants first.
1185 unsigned i = 0;
1186 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1187 ++i;
1188 // Pull a buried constant out to the outside.
1189 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1190 Interesting = true;
1191 AccumulatedConstant += Scale * C->getValue()->getValue();
1192 }
1193
1194 // Next comes everything else. We're especially interested in multiplies
1195 // here, but they're in the middle, so just visit the rest with one loop.
1196 for (; i != NumOperands; ++i) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001197 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1198 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1199 APInt NewScale =
1200 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1201 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1202 // A multiplication of a constant with another add; recurse.
Dan Gohmanf9e64722010-03-18 01:17:13 +00001203 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001204 Interesting |=
1205 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001206 Add->op_begin(), Add->getNumOperands(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001207 NewScale, SE);
1208 } else {
1209 // A multiplication of a constant with some other value. Update
1210 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001211 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1212 const SCEV *Key = SE.getMulExpr(MulOps);
1213 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001214 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001215 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001216 NewOps.push_back(Pair.first->first);
1217 } else {
1218 Pair.first->second += NewScale;
1219 // The map already had an entry for this value, which may indicate
1220 // a folding opportunity.
1221 Interesting = true;
1222 }
1223 }
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001224 } else {
1225 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001226 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001227 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001228 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001229 NewOps.push_back(Pair.first->first);
1230 } else {
1231 Pair.first->second += Scale;
1232 // The map already had an entry for this value, which may indicate
1233 // a folding opportunity.
1234 Interesting = true;
1235 }
1236 }
1237 }
1238
1239 return Interesting;
1240}
1241
1242namespace {
1243 struct APIntCompare {
1244 bool operator()(const APInt &LHS, const APInt &RHS) const {
1245 return LHS.ult(RHS);
1246 }
1247 };
1248}
1249
Dan Gohman6c0866c2009-05-24 23:45:28 +00001250/// getAddExpr - Get a canonical add expression, or something simpler if
1251/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001252const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1253 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001254 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001255 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001256#ifndef NDEBUG
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001257 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001258 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc72f0c82010-06-18 19:09:27 +00001259 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001260 "SCEVAddExpr operand types don't match!");
1261#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001262
Dan Gohmana10756e2010-01-21 02:09:26 +00001263 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1264 if (!HasNUW && HasNSW) {
1265 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001266 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1267 E = Ops.end(); I != E; ++I)
1268 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001269 All = false;
1270 break;
1271 }
1272 if (All) HasNUW = true;
1273 }
1274
Chris Lattner53e677a2004-04-02 20:23:17 +00001275 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001276 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001277
1278 // If there are any constants, fold them together.
1279 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001280 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001281 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001282 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001283 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001284 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001285 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1286 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001287 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001288 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001289 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001290 }
1291
1292 // If we are left with a constant zero being added, strip it off.
Dan Gohmanbca091d2010-04-12 23:08:18 +00001293 if (LHSC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001294 Ops.erase(Ops.begin());
1295 --Idx;
1296 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001297
Dan Gohmanbca091d2010-04-12 23:08:18 +00001298 if (Ops.size() == 1) return Ops[0];
1299 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001300
Dan Gohman68ff7762010-08-27 21:39:59 +00001301 // Okay, check to see if the same value occurs in the operand list more than
1302 // once. If so, merge them together into an multiply expression. Since we
1303 // sorted the list, these values are required to be adjacent.
Chris Lattner53e677a2004-04-02 20:23:17 +00001304 const Type *Ty = Ops[0]->getType();
Dan Gohmandc7692b2010-08-12 14:46:54 +00001305 bool FoundMatch = false;
Dan Gohman68ff7762010-08-27 21:39:59 +00001306 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattner53e677a2004-04-02 20:23:17 +00001307 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman68ff7762010-08-27 21:39:59 +00001308 // Scan ahead to count how many equal operands there are.
1309 unsigned Count = 2;
1310 while (i+Count != e && Ops[i+Count] == Ops[i])
1311 ++Count;
1312 // Merge the values into a multiply.
1313 const SCEV *Scale = getConstant(Ty, Count);
1314 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1315 if (Ops.size() == Count)
Chris Lattner53e677a2004-04-02 20:23:17 +00001316 return Mul;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001317 Ops[i] = Mul;
Dan Gohman68ff7762010-08-27 21:39:59 +00001318 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohman5bb307d2010-08-28 00:39:27 +00001319 --i; e -= Count - 1;
Dan Gohmandc7692b2010-08-12 14:46:54 +00001320 FoundMatch = true;
Chris Lattner53e677a2004-04-02 20:23:17 +00001321 }
Dan Gohmandc7692b2010-08-12 14:46:54 +00001322 if (FoundMatch)
1323 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001324
Dan Gohman728c7f32009-05-08 21:03:19 +00001325 // Check for truncates. If all the operands are truncated from the same
1326 // type, see if factoring out the truncate would permit the result to be
1327 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1328 // if the contents of the resulting outer trunc fold to something simple.
1329 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1330 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1331 const Type *DstType = Trunc->getType();
1332 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001333 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001334 bool Ok = true;
1335 // Check all the operands to see if they can be represented in the
1336 // source type of the truncate.
1337 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1338 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1339 if (T->getOperand()->getType() != SrcType) {
1340 Ok = false;
1341 break;
1342 }
1343 LargeOps.push_back(T->getOperand());
1344 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001345 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001346 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001347 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001348 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1349 if (const SCEVTruncateExpr *T =
1350 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1351 if (T->getOperand()->getType() != SrcType) {
1352 Ok = false;
1353 break;
1354 }
1355 LargeMulOps.push_back(T->getOperand());
1356 } else if (const SCEVConstant *C =
1357 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanc6863982010-04-23 01:51:29 +00001358 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman728c7f32009-05-08 21:03:19 +00001359 } else {
1360 Ok = false;
1361 break;
1362 }
1363 }
1364 if (Ok)
1365 LargeOps.push_back(getMulExpr(LargeMulOps));
1366 } else {
1367 Ok = false;
1368 break;
1369 }
1370 }
1371 if (Ok) {
1372 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001373 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001374 // If it folds to something simple, use it. Otherwise, don't.
1375 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1376 return getTruncateExpr(Fold, DstType);
1377 }
1378 }
1379
1380 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001381 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1382 ++Idx;
1383
1384 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001385 if (Idx < Ops.size()) {
1386 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001387 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001388 // If we have an add, expand the add operands onto the end of the operands
1389 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001390 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001391 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001392 DeletedAdd = true;
1393 }
1394
1395 // If we deleted at least one add, we added operands to the end of the list,
1396 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001397 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001398 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001399 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001400 }
1401
1402 // Skip over the add expression until we get to a multiply.
1403 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1404 ++Idx;
1405
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001406 // Check to see if there are any folding opportunities present with
1407 // operands multiplied by constant values.
1408 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1409 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001410 DenseMap<const SCEV *, APInt> M;
1411 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001412 APInt AccumulatedConstant(BitWidth, 0);
1413 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohmanf9e64722010-03-18 01:17:13 +00001414 Ops.data(), Ops.size(),
1415 APInt(BitWidth, 1), *this)) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001416 // Some interesting folding opportunity is present, so its worthwhile to
1417 // re-generate the operands list. Group the operands by constant scale,
1418 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001419 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Dan Gohman8d9c7a62010-08-16 16:30:01 +00001420 for (SmallVector<const SCEV *, 8>::const_iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001421 E = NewOps.end(); I != E; ++I)
1422 MulOpLists[M.find(*I)->second].push_back(*I);
1423 // Re-generate the operands list.
1424 Ops.clear();
1425 if (AccumulatedConstant != 0)
1426 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001427 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1428 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001429 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001430 Ops.push_back(getMulExpr(getConstant(I->first),
1431 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001432 if (Ops.empty())
Dan Gohmandeff6212010-05-03 22:09:21 +00001433 return getConstant(Ty, 0);
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001434 if (Ops.size() == 1)
1435 return Ops[0];
1436 return getAddExpr(Ops);
1437 }
1438 }
1439
Chris Lattner53e677a2004-04-02 20:23:17 +00001440 // If we are adding something to a multiply expression, make sure the
1441 // something is not already an operand of the multiply. If so, merge it into
1442 // the multiply.
1443 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001444 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001445 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001446 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman918e76b2010-08-12 14:52:55 +00001447 if (isa<SCEVConstant>(MulOpSCEV))
1448 continue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001449 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman918e76b2010-08-12 14:52:55 +00001450 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001451 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001452 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001453 if (Mul->getNumOperands() != 2) {
1454 // If the multiply has more than two operands, we must get the
1455 // Y*Z term.
Dan Gohman18959912010-08-16 16:57:24 +00001456 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1457 Mul->op_begin()+MulOp);
1458 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001459 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 }
Dan Gohmandeff6212010-05-03 22:09:21 +00001461 const SCEV *One = getConstant(Ty, 1);
Dan Gohman58a85b92010-08-13 20:17:14 +00001462 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman918e76b2010-08-12 14:52:55 +00001463 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001464 if (Ops.size() == 2) return OuterMul;
1465 if (AddOp < Idx) {
1466 Ops.erase(Ops.begin()+AddOp);
1467 Ops.erase(Ops.begin()+Idx-1);
1468 } else {
1469 Ops.erase(Ops.begin()+Idx);
1470 Ops.erase(Ops.begin()+AddOp-1);
1471 }
1472 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001473 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001475
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 // Check this multiply against other multiplies being added together.
1477 for (unsigned OtherMulIdx = Idx+1;
1478 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1479 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001480 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001481 // If MulOp occurs in OtherMul, we can fold the two multiplies
1482 // together.
1483 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1484 OMulOp != e; ++OMulOp)
1485 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1486 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001487 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001488 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001489 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001490 Mul->op_begin()+MulOp);
1491 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001492 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001494 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001495 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001496 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman18959912010-08-16 16:57:24 +00001497 OtherMul->op_begin()+OMulOp);
1498 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001499 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001500 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001501 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1502 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001503 if (Ops.size() == 2) return OuterMul;
Dan Gohman90b5f252010-08-31 22:50:31 +00001504 Ops.erase(Ops.begin()+Idx);
1505 Ops.erase(Ops.begin()+OtherMulIdx-1);
1506 Ops.push_back(OuterMul);
1507 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 }
1509 }
1510 }
1511 }
1512
1513 // If there are any add recurrences in the operands list, see if any other
1514 // added values are loop invariant. If so, we can fold them into the
1515 // recurrence.
1516 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1517 ++Idx;
1518
1519 // Scan over all recurrences, trying to fold loop invariants into them.
1520 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1521 // Scan all of the other operands to this add and add them to the vector if
1522 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001523 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001524 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanbca091d2010-04-12 23:08:18 +00001525 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001526 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001527 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001528 LIOps.push_back(Ops[i]);
1529 Ops.erase(Ops.begin()+i);
1530 --i; --e;
1531 }
1532
1533 // If we found some loop invariants, fold them into the recurrence.
1534 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001535 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001536 LIOps.push_back(AddRec->getStart());
1537
Dan Gohman0bba49c2009-07-07 17:06:11 +00001538 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman3a5d4092009-12-18 03:57:04 +00001539 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001540 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001541
Dan Gohmanb9f96512010-06-30 07:16:37 +00001542 // Build the new addrec. Propagate the NUW and NSW flags if both the
1543 // outer add and the inner addrec are guaranteed to have no overflow.
1544 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop,
1545 HasNUW && AddRec->hasNoUnsignedWrap(),
1546 HasNSW && AddRec->hasNoSignedWrap());
Dan Gohman59de33e2009-12-18 18:45:31 +00001547
Chris Lattner53e677a2004-04-02 20:23:17 +00001548 // If all of the other operands were loop invariant, we are done.
1549 if (Ops.size() == 1) return NewRec;
1550
1551 // Otherwise, add the folded AddRec by the non-liv parts.
1552 for (unsigned i = 0;; ++i)
1553 if (Ops[i] == AddRec) {
1554 Ops[i] = NewRec;
1555 break;
1556 }
Dan Gohman246b2562007-10-22 18:31:58 +00001557 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001558 }
1559
1560 // Okay, if there weren't any loop invariants to be folded, check to see if
1561 // there are multiple AddRec's with the same loop induction variable being
1562 // added together. If so, we can fold them.
1563 for (unsigned OtherIdx = Idx+1;
Dan Gohman32527152010-08-27 20:45:56 +00001564 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1565 ++OtherIdx)
1566 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1567 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
1568 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
1569 AddRec->op_end());
1570 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1571 ++OtherIdx)
Dan Gohman30cbc862010-08-29 14:53:34 +00001572 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohman32527152010-08-27 20:45:56 +00001573 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman30cbc862010-08-29 14:53:34 +00001574 if (OtherAddRec->getLoop() == AddRecLoop) {
1575 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
1576 i != e; ++i) {
Dan Gohman32527152010-08-27 20:45:56 +00001577 if (i >= AddRecOps.size()) {
Dan Gohman30cbc862010-08-29 14:53:34 +00001578 AddRecOps.append(OtherAddRec->op_begin()+i,
1579 OtherAddRec->op_end());
Dan Gohman32527152010-08-27 20:45:56 +00001580 break;
1581 }
Dan Gohman30cbc862010-08-29 14:53:34 +00001582 AddRecOps[i] = getAddExpr(AddRecOps[i],
1583 OtherAddRec->getOperand(i));
Dan Gohman32527152010-08-27 20:45:56 +00001584 }
1585 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattner53e677a2004-04-02 20:23:17 +00001586 }
Dan Gohman32527152010-08-27 20:45:56 +00001587 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop);
1588 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 }
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);
Dan Gohman1c343752009-06-27 21:21:31 +00001599 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1600 ID.AddPointer(Ops[i]);
1601 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001602 SCEVAddExpr *S =
1603 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1604 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001605 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1606 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001607 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
1608 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001609 UniqueSCEVs.InsertNode(S, IP);
1610 }
Dan Gohman3645b012009-10-09 00:10:36 +00001611 if (HasNUW) S->setHasNoUnsignedWrap(true);
1612 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001613 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001614}
1615
Dan Gohman6c0866c2009-05-24 23:45:28 +00001616/// getMulExpr - Get a canonical multiply expression, or something simpler if
1617/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001618const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1619 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana10756e2010-01-21 02:09:26 +00001621 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001622#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001623 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001624 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001625 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001626 "SCEVMulExpr operand types don't match!");
1627#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001628
Dan Gohmana10756e2010-01-21 02:09:26 +00001629 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1630 if (!HasNUW && HasNSW) {
1631 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001632 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1633 E = Ops.end(); I != E; ++I)
1634 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001635 All = false;
1636 break;
1637 }
1638 if (All) HasNUW = true;
1639 }
1640
Chris Lattner53e677a2004-04-02 20:23:17 +00001641 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001642 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001643
1644 // If there are any constants, fold them together.
1645 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001646 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001647
1648 // C1*(C2+V) -> C1*C2 + C1*V
1649 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001650 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001651 if (Add->getNumOperands() == 2 &&
1652 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001653 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1654 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001655
Chris Lattner53e677a2004-04-02 20:23:17 +00001656 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001657 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001658 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001659 ConstantInt *Fold = ConstantInt::get(getContext(),
1660 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001661 RHSC->getValue()->getValue());
1662 Ops[0] = getConstant(Fold);
1663 Ops.erase(Ops.begin()+1); // Erase the folded element
1664 if (Ops.size() == 1) return Ops[0];
1665 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001666 }
1667
1668 // If we are left with a constant one being multiplied, strip it off.
1669 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1670 Ops.erase(Ops.begin());
1671 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001672 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001673 // If we have a multiply of zero, it will always be zero.
1674 return Ops[0];
Dan Gohmana10756e2010-01-21 02:09:26 +00001675 } else if (Ops[0]->isAllOnesValue()) {
1676 // If we have a mul by -1 of an add, try distributing the -1 among the
1677 // add operands.
1678 if (Ops.size() == 2)
1679 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
1680 SmallVector<const SCEV *, 4> NewOps;
1681 bool AnyFolded = false;
1682 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1683 I != E; ++I) {
1684 const SCEV *Mul = getMulExpr(Ops[0], *I);
1685 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
1686 NewOps.push_back(Mul);
1687 }
1688 if (AnyFolded)
1689 return getAddExpr(NewOps);
1690 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001691 }
Dan Gohman3ab13122010-04-13 16:49:23 +00001692
1693 if (Ops.size() == 1)
1694 return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001695 }
1696
1697 // Skip over the add expression until we get to a multiply.
1698 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1699 ++Idx;
1700
Chris Lattner53e677a2004-04-02 20:23:17 +00001701 // If there are mul operands inline them all into this expression.
1702 if (Idx < Ops.size()) {
1703 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001704 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001705 // If we have an mul, expand the mul operands onto the end of the operands
1706 // list.
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00001708 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001709 DeletedMul = true;
1710 }
1711
1712 // If we deleted at least one mul, we added operands to the end of the list,
1713 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001714 // any operands we just acquired.
Chris Lattner53e677a2004-04-02 20:23:17 +00001715 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001716 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001717 }
1718
1719 // If there are any add recurrences in the operands list, see if any other
1720 // added values are loop invariant. If so, we can fold them into the
1721 // recurrence.
1722 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1723 ++Idx;
1724
1725 // Scan over all recurrences, trying to fold loop invariants into them.
1726 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1727 // Scan all of the other operands to this mul and add them to the vector if
1728 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001729 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001730 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f32ae32010-08-29 14:55:19 +00001731 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattner53e677a2004-04-02 20:23:17 +00001732 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001733 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001734 LIOps.push_back(Ops[i]);
1735 Ops.erase(Ops.begin()+i);
1736 --i; --e;
1737 }
1738
1739 // If we found some loop invariants, fold them into the recurrence.
1740 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001741 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001742 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001743 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman27ed6a42010-06-17 23:34:09 +00001744 const SCEV *Scale = getMulExpr(LIOps);
1745 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1746 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001747
Dan Gohmanb9f96512010-06-30 07:16:37 +00001748 // Build the new addrec. Propagate the NUW and NSW flags if both the
1749 // outer mul and the inner addrec are guaranteed to have no overflow.
Dan Gohman0f32ae32010-08-29 14:55:19 +00001750 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop,
Dan Gohmana10756e2010-01-21 02:09:26 +00001751 HasNUW && AddRec->hasNoUnsignedWrap(),
Dan Gohmanb9f96512010-06-30 07:16:37 +00001752 HasNSW && AddRec->hasNoSignedWrap());
Chris Lattner53e677a2004-04-02 20:23:17 +00001753
1754 // If all of the other operands were loop invariant, we are done.
1755 if (Ops.size() == 1) return NewRec;
1756
1757 // Otherwise, multiply the folded AddRec by the non-liv parts.
1758 for (unsigned i = 0;; ++i)
1759 if (Ops[i] == AddRec) {
1760 Ops[i] = NewRec;
1761 break;
1762 }
Dan Gohman246b2562007-10-22 18:31:58 +00001763 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001764 }
1765
1766 // Okay, if there weren't any loop invariants to be folded, check to see if
1767 // there are multiple AddRec's with the same loop induction variable being
1768 // multiplied together. If so, we can fold them.
1769 for (unsigned OtherIdx = Idx+1;
Dan Gohman6a0c1252010-08-31 22:52:12 +00001770 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1771 ++OtherIdx)
1772 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
1773 // F * G, where F = {A,+,B}<L> and G = {C,+,D}<L> -->
1774 // {A*C,+,F*D + G*B + B*D}<L>
1775 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
1776 ++OtherIdx)
1777 if (const SCEVAddRecExpr *OtherAddRec =
1778 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
1779 if (OtherAddRec->getLoop() == AddRecLoop) {
1780 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1781 const SCEV *NewStart = getMulExpr(F->getStart(), G->getStart());
1782 const SCEV *B = F->getStepRecurrence(*this);
1783 const SCEV *D = G->getStepRecurrence(*this);
1784 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
1785 getMulExpr(G, B),
1786 getMulExpr(B, D));
1787 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
1788 F->getLoop());
1789 if (Ops.size() == 2) return NewAddRec;
1790 Ops[Idx] = AddRec = cast<SCEVAddRecExpr>(NewAddRec);
1791 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
1792 }
1793 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001794 }
1795
1796 // Otherwise couldn't fold anything into this recurrence. Move onto the
1797 // next one.
1798 }
1799
1800 // Okay, it looks like we really DO need an mul expr. Check to see if we
1801 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001802 FoldingSetNodeID ID;
1803 ID.AddInteger(scMulExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00001804 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1805 ID.AddPointer(Ops[i]);
1806 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00001807 SCEVMulExpr *S =
1808 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1809 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001810 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
1811 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00001812 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
1813 O, Ops.size());
Dan Gohmana10756e2010-01-21 02:09:26 +00001814 UniqueSCEVs.InsertNode(S, IP);
1815 }
Dan Gohman3645b012009-10-09 00:10:36 +00001816 if (HasNUW) S->setHasNoUnsignedWrap(true);
1817 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001818 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001819}
1820
Andreas Bolka8a11c982009-08-07 22:55:26 +00001821/// getUDivExpr - Get a canonical unsigned division expression, or something
1822/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001823const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1824 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001825 assert(getEffectiveSCEVType(LHS->getType()) ==
1826 getEffectiveSCEVType(RHS->getType()) &&
1827 "SCEVUDivExpr operand types don't match!");
1828
Dan Gohman622ed672009-05-04 22:02:23 +00001829 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001830 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001831 return LHS; // X udiv 1 --> x
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001832 // If the denominator is zero, the result of the udiv is undefined. Don't
1833 // try to analyze it, because the resolution chosen here may differ from
1834 // the resolution chosen in other parts of the compiler.
1835 if (!RHSC->getValue()->isZero()) {
1836 // Determine if the division can be folded into the operands of
1837 // its operands.
1838 // TODO: Generalize this to non-constants by using known-bits information.
1839 const Type *Ty = LHS->getType();
1840 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmanddd3a882010-08-04 19:52:50 +00001841 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001842 // For non-power-of-two values, effectively round the value up to the
1843 // nearest power of two.
1844 if (!RHSC->getValue()->getValue().isPowerOf2())
1845 ++MaxShiftAmt;
1846 const IntegerType *ExtTy =
1847 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
1848 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1849 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1850 if (const SCEVConstant *Step =
1851 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1852 if (!Step->getValue()->getValue()
1853 .urem(RHSC->getValue()->getValue()) &&
1854 getZeroExtendExpr(AR, ExtTy) ==
1855 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1856 getZeroExtendExpr(Step, ExtTy),
1857 AR->getLoop())) {
1858 SmallVector<const SCEV *, 4> Operands;
1859 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1860 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1861 return getAddRecExpr(Operands, AR->getLoop());
Dan Gohman185cf032009-05-08 20:18:49 +00001862 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001863 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1864 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1865 SmallVector<const SCEV *, 4> Operands;
1866 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1867 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1868 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
1869 // Find an operand that's safely divisible.
1870 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1871 const SCEV *Op = M->getOperand(i);
1872 const SCEV *Div = getUDivExpr(Op, RHSC);
1873 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1874 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
1875 M->op_end());
1876 Operands[i] = Div;
1877 return getMulExpr(Operands);
1878 }
1879 }
Dan Gohman185cf032009-05-08 20:18:49 +00001880 }
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001881 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1882 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1883 SmallVector<const SCEV *, 4> Operands;
1884 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1885 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1886 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1887 Operands.clear();
1888 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1889 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
1890 if (isa<SCEVUDivExpr>(Op) ||
1891 getMulExpr(Op, RHS) != A->getOperand(i))
1892 break;
1893 Operands.push_back(Op);
1894 }
1895 if (Operands.size() == A->getNumOperands())
1896 return getAddExpr(Operands);
1897 }
1898 }
Dan Gohman185cf032009-05-08 20:18:49 +00001899
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00001900 // Fold if both operands are constant.
1901 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1902 Constant *LHSCV = LHSC->getValue();
1903 Constant *RHSCV = RHSC->getValue();
1904 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1905 RHSCV)));
1906 }
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;
Dan Gohman95531882010-03-18 18:49:47 +00001916 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
1917 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) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001932 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001933 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001934 }
1935
1936 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001937 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001938}
1939
Dan Gohman6c0866c2009-05-24 23:45:28 +00001940/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1941/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001942const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001943ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001944 const Loop *L,
1945 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001946 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001947#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00001948 const Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00001949 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00001950 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00001951 "SCEVAddRecExpr operand types don't match!");
Dan Gohman203a7232010-11-17 20:48:38 +00001952 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001953 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohman203a7232010-11-17 20:48:38 +00001954 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001955#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001956
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001957 if (Operands.back()->isZero()) {
1958 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001959 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001960 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001961
Dan Gohmanbc028532010-02-19 18:49:22 +00001962 // It's tempting to want to call getMaxBackedgeTakenCount count here and
1963 // use that information to infer NUW and NSW flags. However, computing a
1964 // BE count requires calling getAddRecExpr, so we may not yet have a
1965 // meaningful BE count at this point (and if we don't, we'd be stuck
1966 // with a SCEVCouldNotCompute as the cached BE count).
1967
Dan Gohmana10756e2010-01-21 02:09:26 +00001968 // If HasNSW is true and all the operands are non-negative, infer HasNUW.
1969 if (!HasNUW && HasNSW) {
1970 bool All = true;
Dan Gohman2d16fc52010-08-16 16:27:53 +00001971 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
1972 E = Operands.end(); I != E; ++I)
1973 if (!isKnownNonNegative(*I)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001974 All = false;
1975 break;
1976 }
1977 if (All) HasNUW = true;
1978 }
1979
Dan Gohmand9cc7492008-08-08 18:33:12 +00001980 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001981 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001982 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman9cba9782010-08-13 20:23:25 +00001983 if (L->contains(NestedLoop) ?
Dan Gohmana10756e2010-01-21 02:09:26 +00001984 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman9cba9782010-08-13 20:23:25 +00001985 (!NestedLoop->contains(L) &&
Dan Gohmana10756e2010-01-21 02:09:26 +00001986 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001987 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001988 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001989 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001990 // AddRecs require their operands be loop-invariant with respect to their
1991 // loops. Don't perform this transformation if it would break this
1992 // requirement.
1993 bool AllInvariant = true;
1994 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001995 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00001996 AllInvariant = false;
1997 break;
1998 }
1999 if (AllInvariant) {
2000 NestedOperands[0] = getAddRecExpr(Operands, L);
2001 AllInvariant = true;
2002 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohman17ead4f2010-11-17 21:23:15 +00002003 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohman9a80b452009-06-26 22:36:20 +00002004 AllInvariant = false;
2005 break;
2006 }
2007 if (AllInvariant)
2008 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00002009 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00002010 }
2011 // Reset Operands to its original state.
2012 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00002013 }
2014 }
2015
Dan Gohman67847532010-01-19 22:27:22 +00002016 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2017 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002018 FoldingSetNodeID ID;
2019 ID.AddInteger(scAddRecExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002020 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2021 ID.AddPointer(Operands[i]);
2022 ID.AddPointer(L);
2023 void *IP = 0;
Dan Gohmana10756e2010-01-21 02:09:26 +00002024 SCEVAddRecExpr *S =
2025 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2026 if (!S) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00002027 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2028 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002029 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2030 O, Operands.size(), L);
Dan Gohmana10756e2010-01-21 02:09:26 +00002031 UniqueSCEVs.InsertNode(S, IP);
2032 }
Dan Gohman3645b012009-10-09 00:10:36 +00002033 if (HasNUW) S->setHasNoUnsignedWrap(true);
2034 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00002035 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00002036}
2037
Dan Gohman9311ef62009-06-24 14:49:00 +00002038const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2039 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002040 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002041 Ops.push_back(LHS);
2042 Ops.push_back(RHS);
2043 return getSMaxExpr(Ops);
2044}
2045
Dan Gohman0bba49c2009-07-07 17:06:11 +00002046const SCEV *
2047ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002048 assert(!Ops.empty() && "Cannot get empty smax!");
2049 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002050#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002051 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002052 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002053 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002054 "SCEVSMaxExpr operand types don't match!");
2055#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002056
2057 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002058 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002059
2060 // If there are any constants, fold them together.
2061 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002062 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002063 ++Idx;
2064 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002065 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002066 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002067 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002068 APIntOps::smax(LHSC->getValue()->getValue(),
2069 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00002070 Ops[0] = getConstant(Fold);
2071 Ops.erase(Ops.begin()+1); // Erase the folded element
2072 if (Ops.size() == 1) return Ops[0];
2073 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002074 }
2075
Dan Gohmane5aceed2009-06-24 14:46:22 +00002076 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002077 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2078 Ops.erase(Ops.begin());
2079 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002080 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2081 // If we have an smax with a constant maximum-int, it will always be
2082 // maximum-int.
2083 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002084 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002085
Dan Gohman3ab13122010-04-13 16:49:23 +00002086 if (Ops.size() == 1) return Ops[0];
2087 }
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002088
2089 // Find the first SMax
2090 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2091 ++Idx;
2092
2093 // Check to see if one of the operands is an SMax. If so, expand its operands
2094 // onto our operand list, and recurse to simplify.
2095 if (Idx < Ops.size()) {
2096 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002097 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002098 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002099 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002100 DeletedSMax = true;
2101 }
2102
2103 if (DeletedSMax)
2104 return getSMaxExpr(Ops);
2105 }
2106
2107 // Okay, check to see if the same value occurs in the operand list twice. If
2108 // so, delete one. Since we sorted the list, these values are required to
2109 // be adjacent.
2110 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002111 // X smax Y smax Y --> X smax Y
2112 // X smax Y --> X, if X is always greater than Y
2113 if (Ops[i] == Ops[i+1] ||
2114 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2115 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2116 --i; --e;
2117 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002118 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2119 --i; --e;
2120 }
2121
2122 if (Ops.size() == 1) return Ops[0];
2123
2124 assert(!Ops.empty() && "Reduced smax down to nothing!");
2125
Nick Lewycky3e630762008-02-20 06:48:22 +00002126 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002127 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002128 FoldingSetNodeID ID;
2129 ID.AddInteger(scSMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002130 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2131 ID.AddPointer(Ops[i]);
2132 void *IP = 0;
2133 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002134 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2135 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002136 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2137 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002138 UniqueSCEVs.InsertNode(S, IP);
2139 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002140}
2141
Dan Gohman9311ef62009-06-24 14:49:00 +00002142const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2143 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002144 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00002145 Ops.push_back(LHS);
2146 Ops.push_back(RHS);
2147 return getUMaxExpr(Ops);
2148}
2149
Dan Gohman0bba49c2009-07-07 17:06:11 +00002150const SCEV *
2151ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002152 assert(!Ops.empty() && "Cannot get empty umax!");
2153 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002154#ifndef NDEBUG
Dan Gohmanc4f77982010-08-16 16:13:54 +00002155 const Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmanf78a9782009-05-18 15:44:58 +00002156 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanc4f77982010-08-16 16:13:54 +00002157 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmanf78a9782009-05-18 15:44:58 +00002158 "SCEVUMaxExpr operand types don't match!");
2159#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002160
2161 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002162 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002163
2164 // If there are any constants, fold them together.
2165 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002166 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002167 ++Idx;
2168 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002169 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002170 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002171 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002172 APIntOps::umax(LHSC->getValue()->getValue(),
2173 RHSC->getValue()->getValue()));
2174 Ops[0] = getConstant(Fold);
2175 Ops.erase(Ops.begin()+1); // Erase the folded element
2176 if (Ops.size() == 1) return Ops[0];
2177 LHSC = cast<SCEVConstant>(Ops[0]);
2178 }
2179
Dan Gohmane5aceed2009-06-24 14:46:22 +00002180 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002181 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2182 Ops.erase(Ops.begin());
2183 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002184 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2185 // If we have an umax with a constant maximum-int, it will always be
2186 // maximum-int.
2187 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002188 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002189
Dan Gohman3ab13122010-04-13 16:49:23 +00002190 if (Ops.size() == 1) return Ops[0];
2191 }
Nick Lewycky3e630762008-02-20 06:48:22 +00002192
2193 // Find the first UMax
2194 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2195 ++Idx;
2196
2197 // Check to see if one of the operands is a UMax. If so, expand its operands
2198 // onto our operand list, and recurse to simplify.
2199 if (Idx < Ops.size()) {
2200 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002201 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002202 Ops.erase(Ops.begin()+Idx);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002203 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky3e630762008-02-20 06:48:22 +00002204 DeletedUMax = true;
2205 }
2206
2207 if (DeletedUMax)
2208 return getUMaxExpr(Ops);
2209 }
2210
2211 // Okay, check to see if the same value occurs in the operand list twice. If
2212 // so, delete one. Since we sorted the list, these values are required to
2213 // be adjacent.
2214 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman28287792010-04-13 16:51:03 +00002215 // X umax Y umax Y --> X umax Y
2216 // X umax Y --> X, if X is always greater than Y
2217 if (Ops[i] == Ops[i+1] ||
2218 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2219 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2220 --i; --e;
2221 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002222 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2223 --i; --e;
2224 }
2225
2226 if (Ops.size() == 1) return Ops[0];
2227
2228 assert(!Ops.empty() && "Reduced umax down to nothing!");
2229
2230 // Okay, it looks like we really DO need a umax expr. Check to see if we
2231 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002232 FoldingSetNodeID ID;
2233 ID.AddInteger(scUMaxExpr);
Dan Gohman1c343752009-06-27 21:21:31 +00002234 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2235 ID.AddPointer(Ops[i]);
2236 void *IP = 0;
2237 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohmanf9e64722010-03-18 01:17:13 +00002238 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2239 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman95531882010-03-18 18:49:47 +00002240 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2241 O, Ops.size());
Dan Gohman1c343752009-06-27 21:21:31 +00002242 UniqueSCEVs.InsertNode(S, IP);
2243 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002244}
2245
Dan Gohman9311ef62009-06-24 14:49:00 +00002246const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2247 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002248 // ~smax(~x, ~y) == smin(x, y).
2249 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2250}
2251
Dan Gohman9311ef62009-06-24 14:49:00 +00002252const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2253 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002254 // ~umax(~x, ~y) == umin(x, y)
2255 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2256}
2257
Dan Gohman4f8eea82010-02-01 18:27:38 +00002258const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002259 // If we have TargetData, we can bypass creating a target-independent
2260 // constant expression and then folding it back into a ConstantInt.
2261 // This is just a compile-time optimization.
2262 if (TD)
2263 return getConstant(TD->getIntPtrType(getContext()),
2264 TD->getTypeAllocSize(AllocTy));
2265
Dan Gohman4f8eea82010-02-01 18:27:38 +00002266 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2267 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002268 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2269 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002270 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2271 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2272}
2273
2274const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
2275 Constant *C = ConstantExpr::getAlignOf(AllocTy);
2276 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002277 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2278 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002279 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2280 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2281}
2282
2283const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
2284 unsigned FieldNo) {
Dan Gohman6ab10f62010-04-12 23:03:26 +00002285 // If we have TargetData, we can bypass creating a target-independent
2286 // constant expression and then folding it back into a ConstantInt.
2287 // This is just a compile-time optimization.
2288 if (TD)
2289 return getConstant(TD->getIntPtrType(getContext()),
2290 TD->getStructLayout(STy)->getElementOffset(FieldNo));
2291
Dan Gohman0f5efe52010-01-28 02:15:55 +00002292 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2293 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002294 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2295 C = Folded;
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002296 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002297 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002298}
2299
Dan Gohman4f8eea82010-02-01 18:27:38 +00002300const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
2301 Constant *FieldNo) {
2302 Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
Dan Gohman0f5efe52010-01-28 02:15:55 +00002303 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Dan Gohman70001222010-05-28 16:12:08 +00002304 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD))
2305 C = Folded;
Dan Gohman4f8eea82010-02-01 18:27:38 +00002306 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
Dan Gohman0f5efe52010-01-28 02:15:55 +00002307 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002308}
2309
Dan Gohman0bba49c2009-07-07 17:06:11 +00002310const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002311 // Don't attempt to do anything other than create a SCEVUnknown object
2312 // here. createSCEV only calls getUnknown after checking for all other
2313 // interesting possibilities, and any other code that calls getUnknown
2314 // is doing so in order to hide a value from SCEV canonicalization.
2315
Dan Gohman1c343752009-06-27 21:21:31 +00002316 FoldingSetNodeID ID;
2317 ID.AddInteger(scUnknown);
2318 ID.AddPointer(V);
2319 void *IP = 0;
Dan Gohmanab37f502010-08-02 23:49:30 +00002320 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
2321 assert(cast<SCEVUnknown>(S)->getValue() == V &&
2322 "Stale SCEVUnknown in uniquing map!");
2323 return S;
2324 }
2325 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
2326 FirstUnknown);
2327 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohman1c343752009-06-27 21:21:31 +00002328 UniqueSCEVs.InsertNode(S, IP);
2329 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002330}
2331
Chris Lattner53e677a2004-04-02 20:23:17 +00002332//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002333// Basic SCEV Analysis and PHI Idiom Recognition Code
2334//
2335
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002336/// isSCEVable - Test if values of the given type are analyzable within
2337/// the SCEV framework. This primarily includes integer types, and it
2338/// can optionally include pointer types if the ScalarEvolution class
2339/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002340bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002341 // Integers and pointers are always SCEVable.
Duncan Sands1df98592010-02-16 11:11:14 +00002342 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002343}
2344
2345/// getTypeSizeInBits - Return the size in bits of the specified type,
2346/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002347uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002348 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2349
2350 // If we have a TargetData, use it!
2351 if (TD)
2352 return TD->getTypeSizeInBits(Ty);
2353
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002354 // Integer types have fixed sizes.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002355 if (Ty->isIntegerTy())
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002356 return Ty->getPrimitiveSizeInBits();
2357
2358 // The only other support type is pointer. Without TargetData, conservatively
2359 // assume pointers are 64-bit.
Duncan Sands1df98592010-02-16 11:11:14 +00002360 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002361 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002362}
2363
2364/// getEffectiveSCEVType - Return a type with the same bitwidth as
2365/// the given type and which represents how SCEV will treat the given
2366/// type, for which isSCEVable must return true. For pointer types,
2367/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002368const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002369 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2370
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002371 if (Ty->isIntegerTy())
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002372 return Ty;
2373
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002374 // The only other support type is pointer.
Duncan Sands1df98592010-02-16 11:11:14 +00002375 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002376 if (TD) return TD->getIntPtrType(getContext());
2377
2378 // Without TargetData, conservatively assume pointers are 64-bit.
2379 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002380}
Chris Lattner53e677a2004-04-02 20:23:17 +00002381
Dan Gohman0bba49c2009-07-07 17:06:11 +00002382const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002383 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002384}
2385
Chris Lattner53e677a2004-04-02 20:23:17 +00002386/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2387/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002388const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002389 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002390
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002391 ValueExprMapType::const_iterator I = ValueExprMap.find(V);
2392 if (I != ValueExprMap.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002393 const SCEV *S = createSCEV(V);
Dan Gohman619d3322010-08-16 16:31:39 +00002394
2395 // The process of creating a SCEV for V may have caused other SCEVs
2396 // to have been created, so it's necessary to insert the new entry
2397 // from scratch, rather than trying to remember the insert position
2398 // above.
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002399 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002400 return S;
2401}
2402
Dan Gohman2d1be872009-04-16 03:18:22 +00002403/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2404///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002405const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002406 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002407 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002408 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002409
2410 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002411 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002412 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002413 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002414}
2415
2416/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002417const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002418 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002419 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002420 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002421
2422 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002423 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002424 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002425 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002426 return getMinusSCEV(AllOnes, V);
2427}
2428
2429/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2430///
Dan Gohman9311ef62009-06-24 14:49:00 +00002431const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2432 const SCEV *RHS) {
Dan Gohmaneb4152c2010-07-20 16:53:00 +00002433 // Fast path: X - X --> 0.
2434 if (LHS == RHS)
2435 return getConstant(LHS->getType(), 0);
2436
Dan Gohman2d1be872009-04-16 03:18:22 +00002437 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002438 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002439}
2440
2441/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2442/// input value to the specified type. If the type must be extended, it is zero
2443/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002444const SCEV *
2445ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002446 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002447 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002448 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2449 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002450 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002451 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002452 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002453 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002454 return getTruncateExpr(V, Ty);
2455 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002456}
2457
2458/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2459/// input value to the specified type. If the type must be extended, it is sign
2460/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002461const SCEV *
2462ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002463 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002464 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002465 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2466 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002467 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002468 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002469 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002470 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002471 return getTruncateExpr(V, Ty);
2472 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002473}
2474
Dan Gohman467c4302009-05-13 03:46:30 +00002475/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2476/// input value to the specified type. If the type must be extended, it is zero
2477/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002478const SCEV *
2479ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002480 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002481 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2482 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002483 "Cannot noop or zero extend with non-integer arguments!");
2484 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2485 "getNoopOrZeroExtend cannot truncate!");
2486 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2487 return V; // No conversion
2488 return getZeroExtendExpr(V, Ty);
2489}
2490
2491/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2492/// input value to the specified type. If the type must be extended, it is sign
2493/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002494const SCEV *
2495ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002496 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002497 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2498 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002499 "Cannot noop or sign extend with non-integer arguments!");
2500 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2501 "getNoopOrSignExtend cannot truncate!");
2502 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2503 return V; // No conversion
2504 return getSignExtendExpr(V, Ty);
2505}
2506
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002507/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2508/// the input value to the specified type. If the type must be extended,
2509/// it is extended with unspecified bits. The conversion must not be
2510/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002511const SCEV *
2512ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002513 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002514 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2515 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002516 "Cannot noop or any extend with non-integer arguments!");
2517 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2518 "getNoopOrAnyExtend cannot truncate!");
2519 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2520 return V; // No conversion
2521 return getAnyExtendExpr(V, Ty);
2522}
2523
Dan Gohman467c4302009-05-13 03:46:30 +00002524/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2525/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002526const SCEV *
2527ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002528 const Type *SrcTy = V->getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002529 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
2530 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002531 "Cannot truncate or noop with non-integer arguments!");
2532 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2533 "getTruncateOrNoop cannot extend!");
2534 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2535 return V; // No conversion
2536 return getTruncateExpr(V, Ty);
2537}
2538
Dan Gohmana334aa72009-06-22 00:31:57 +00002539/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2540/// the types using zero-extension, and then perform a umax operation
2541/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002542const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2543 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002544 const SCEV *PromotedLHS = LHS;
2545 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002546
2547 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2548 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2549 else
2550 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2551
2552 return getUMaxExpr(PromotedLHS, PromotedRHS);
2553}
2554
Dan Gohmanc9759e82009-06-22 15:03:27 +00002555/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2556/// the types using zero-extension, and then perform a umin operation
2557/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002558const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2559 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002560 const SCEV *PromotedLHS = LHS;
2561 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002562
2563 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2564 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2565 else
2566 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2567
2568 return getUMinExpr(PromotedLHS, PromotedRHS);
2569}
2570
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002571/// PushDefUseChildren - Push users of the given Instruction
2572/// onto the given Worklist.
2573static void
2574PushDefUseChildren(Instruction *I,
2575 SmallVectorImpl<Instruction *> &Worklist) {
2576 // Push the def-use children onto the Worklist stack.
2577 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2578 UI != UE; ++UI)
Gabor Greif96f1d8e2010-07-22 13:36:47 +00002579 Worklist.push_back(cast<Instruction>(*UI));
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002580}
2581
2582/// ForgetSymbolicValue - This looks up computed SCEV values for all
2583/// instructions that depend on the given instruction and removes them from
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002584/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002585/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002586void
Dan Gohman85669632010-02-25 06:57:05 +00002587ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002588 SmallVector<Instruction *, 16> Worklist;
Dan Gohman85669632010-02-25 06:57:05 +00002589 PushDefUseChildren(PN, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002590
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002591 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman85669632010-02-25 06:57:05 +00002592 Visited.insert(PN);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002593 while (!Worklist.empty()) {
Dan Gohman85669632010-02-25 06:57:05 +00002594 Instruction *I = Worklist.pop_back_val();
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002595 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002596
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002597 ValueExprMapType::iterator It =
2598 ValueExprMap.find(static_cast<Value *>(I));
2599 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002600 const SCEV *Old = It->second;
2601
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002602 // Short-circuit the def-use traversal if the symbolic name
2603 // ceases to appear in expressions.
Dan Gohman6678e7b2010-11-17 02:44:44 +00002604 if (Old != SymName && !Old->hasOperand(SymName))
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002605 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002606
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002607 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohman85669632010-02-25 06:57:05 +00002608 // structure, it's a PHI that's in the progress of being computed
2609 // by createNodeForPHI, or it's a single-value PHI. In the first case,
2610 // additional loop trip count information isn't going to change anything.
2611 // In the second case, createNodeForPHI will perform the necessary
2612 // updates on its own when it gets to that point. In the third, we do
2613 // want to forget the SCEVUnknown.
2614 if (!isa<PHINode>(I) ||
Dan Gohman6678e7b2010-11-17 02:44:44 +00002615 !isa<SCEVUnknown>(Old) ||
2616 (I != PN && Old == SymName)) {
2617 ValuesAtScopes.erase(Old);
2618 UnsignedRanges.erase(Old);
2619 SignedRanges.erase(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002620 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002621 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002622 }
2623
2624 PushDefUseChildren(I, Worklist);
2625 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002626}
Chris Lattner53e677a2004-04-02 20:23:17 +00002627
2628/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2629/// a loop header, making it a potential recurrence, or it doesn't.
2630///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002631const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman27dead42010-04-12 07:49:36 +00002632 if (const Loop *L = LI->getLoopFor(PN->getParent()))
2633 if (L->getHeader() == PN->getParent()) {
2634 // The loop may have multiple entrances or multiple exits; we can analyze
2635 // this phi as an addrec if it has a unique entry value and a unique
2636 // backedge value.
2637 Value *BEValueV = 0, *StartValueV = 0;
2638 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2639 Value *V = PN->getIncomingValue(i);
2640 if (L->contains(PN->getIncomingBlock(i))) {
2641 if (!BEValueV) {
2642 BEValueV = V;
2643 } else if (BEValueV != V) {
2644 BEValueV = 0;
2645 break;
2646 }
2647 } else if (!StartValueV) {
2648 StartValueV = V;
2649 } else if (StartValueV != V) {
2650 StartValueV = 0;
2651 break;
2652 }
2653 }
2654 if (BEValueV && StartValueV) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002655 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002656 const SCEV *SymbolicName = getUnknown(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002657 assert(ValueExprMap.find(PN) == ValueExprMap.end() &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002658 "PHI node already processed?");
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002659 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002660
2661 // Using this symbolic name for the PHI, analyze the value coming around
2662 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002663 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002664
2665 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2666 // has a special value for the first iteration of the loop.
2667
2668 // If the value coming around the backedge is an add with the symbolic
2669 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002670 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002671 // If there is a single occurrence of the symbolic value, replace it
2672 // with a recurrence.
2673 unsigned FoundIndex = Add->getNumOperands();
2674 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2675 if (Add->getOperand(i) == SymbolicName)
2676 if (FoundIndex == e) {
2677 FoundIndex = i;
2678 break;
2679 }
2680
2681 if (FoundIndex != Add->getNumOperands()) {
2682 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002683 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002684 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2685 if (i != FoundIndex)
2686 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002687 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002688
2689 // This is not a valid addrec if the step amount is varying each
2690 // loop iteration, but is not itself an addrec in this loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002691 if (isLoopInvariant(Accum, L) ||
Chris Lattner53e677a2004-04-02 20:23:17 +00002692 (isa<SCEVAddRecExpr>(Accum) &&
2693 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00002694 bool HasNUW = false;
2695 bool HasNSW = false;
2696
2697 // If the increment doesn't overflow, then neither the addrec nor
2698 // the post-increment will overflow.
2699 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
2700 if (OBO->hasNoUnsignedWrap())
2701 HasNUW = true;
2702 if (OBO->hasNoSignedWrap())
2703 HasNSW = true;
2704 }
2705
Dan Gohman27dead42010-04-12 07:49:36 +00002706 const SCEV *StartVal = getSCEV(StartValueV);
Dan Gohmana10756e2010-01-21 02:09:26 +00002707 const SCEV *PHISCEV =
2708 getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002709
Dan Gohmana10756e2010-01-21 02:09:26 +00002710 // Since the no-wrap flags are on the increment, they apply to the
2711 // post-incremented value as well.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002712 if (isLoopInvariant(Accum, L))
Dan Gohmana10756e2010-01-21 02:09:26 +00002713 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
2714 Accum, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00002715
2716 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002717 // to be symbolic. We now need to go back and purge all of the
2718 // entries for the scalars that use the symbolic expression.
2719 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002720 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002721 return PHISCEV;
2722 }
2723 }
Dan Gohman622ed672009-05-04 22:02:23 +00002724 } else if (const SCEVAddRecExpr *AddRec =
2725 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002726 // Otherwise, this could be a loop like this:
2727 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2728 // In this case, j = {1,+,1} and BEValue is j.
2729 // Because the other in-value of i (0) fits the evolution of BEValue
2730 // i really is an addrec evolution.
2731 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman27dead42010-04-12 07:49:36 +00002732 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattner97156e72006-04-26 18:34:07 +00002733
2734 // If StartVal = j.start - j.stride, we can use StartVal as the
2735 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002736 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman5ee60f72010-04-11 23:44:58 +00002737 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002738 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002739 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002740
2741 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002742 // to be symbolic. We now need to go back and purge all of the
2743 // entries for the scalars that use the symbolic expression.
2744 ForgetSymbolicName(PN, SymbolicName);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00002745 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002746 return PHISCEV;
2747 }
2748 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002749 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002750 }
Dan Gohman27dead42010-04-12 07:49:36 +00002751 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002752
Dan Gohman85669632010-02-25 06:57:05 +00002753 // If the PHI has a single incoming value, follow that value, unless the
2754 // PHI's incoming blocks are in a different loop, in which case doing so
2755 // risks breaking LCSSA form. Instcombine would normally zap these, but
2756 // it doesn't have DominatorTree information, so it may miss cases.
Duncan Sandsa0c52442010-11-17 04:18:45 +00002757 if (Value *V = SimplifyInstruction(PN, TD, DT)) {
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002758 Instruction *I = dyn_cast<Instruction>(V);
2759 // Only instructions are problematic for preserving LCSSA form.
2760 if (!I)
Dan Gohman85669632010-02-25 06:57:05 +00002761 return getSCEV(V);
Duncan Sands6f8a5dd2010-11-17 20:49:12 +00002762
2763 // If the instruction is not defined in a loop, then it can be used freely.
2764 Loop *ILoop = LI->getLoopFor(I->getParent());
2765 if (!ILoop)
2766 return getSCEV(I);
2767
2768 // If the instruction is defined in the same loop as the phi node, or in a
2769 // loop that contains the phi node loop as an inner loop, then using it as
2770 // a replacement for the phi node will not break LCSSA form.
2771 Loop *PNLoop = LI->getLoopFor(PN->getParent());
2772 if (ILoop->contains(PNLoop))
2773 return getSCEV(I);
Dan Gohman85669632010-02-25 06:57:05 +00002774 }
Dan Gohmana653fc52009-07-14 14:06:25 +00002775
Chris Lattner53e677a2004-04-02 20:23:17 +00002776 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002777 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002778}
2779
Dan Gohman26466c02009-05-08 20:26:55 +00002780/// createNodeForGEP - Expand GEP instructions into add and multiply
2781/// operations. This allows them to be analyzed by regular SCEV code.
2782///
Dan Gohmand281ed22009-12-18 02:09:29 +00002783const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002784
Dan Gohmanb9f96512010-06-30 07:16:37 +00002785 // Don't blindly transfer the inbounds flag from the GEP instruction to the
2786 // Add expression, because the Instruction may be guarded by control flow
2787 // and the no-overflow bits may not be valid for the expression in any
Dan Gohman70eff632010-06-30 17:27:11 +00002788 // context.
Dan Gohman7a642572010-06-29 01:41:41 +00002789
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002790 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002791 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002792 // Don't attempt to analyze GEPs over unsized objects.
2793 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2794 return getUnknown(GEP);
Dan Gohmandeff6212010-05-03 22:09:21 +00002795 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002796 gep_type_iterator GTI = gep_type_begin(GEP);
Oscar Fuentesee56c422010-08-02 06:00:15 +00002797 for (GetElementPtrInst::op_iterator I = llvm::next(GEP->op_begin()),
Dan Gohmane810b0d2009-05-08 20:36:47 +00002798 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002799 I != E; ++I) {
2800 Value *Index = *I;
2801 // Compute the (potentially symbolic) offset in bytes for this index.
2802 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2803 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002804 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanb9f96512010-06-30 07:16:37 +00002805 const SCEV *FieldOffset = getOffsetOfExpr(STy, FieldNo);
2806
Dan Gohmanb9f96512010-06-30 07:16:37 +00002807 // Add the field offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002808 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002809 } else {
2810 // For an array, add the element offset, explicitly scaled.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002811 const SCEV *ElementSize = getSizeOfExpr(*GTI);
2812 const SCEV *IndexS = getSCEV(Index);
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002813 // Getelementptr indices are signed.
Dan Gohmanb9f96512010-06-30 07:16:37 +00002814 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
2815
Dan Gohmanb9f96512010-06-30 07:16:37 +00002816 // Multiply the index by the element size to compute the element offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002817 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize);
Dan Gohmanb9f96512010-06-30 07:16:37 +00002818
2819 // Add the element offset to the running total offset.
Dan Gohman70eff632010-06-30 17:27:11 +00002820 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002821 }
2822 }
Dan Gohmanb9f96512010-06-30 07:16:37 +00002823
2824 // Get the SCEV for the GEP base.
2825 const SCEV *BaseS = getSCEV(Base);
2826
Dan Gohmanb9f96512010-06-30 07:16:37 +00002827 // Add the total offset from all the GEP indices to the base.
Dan Gohman70eff632010-06-30 17:27:11 +00002828 return getAddExpr(BaseS, TotalOffset);
Dan Gohman26466c02009-05-08 20:26:55 +00002829}
2830
Nick Lewycky83bb0052007-11-22 07:59:40 +00002831/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2832/// guaranteed to end in (at every loop iteration). It is, at the same time,
2833/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2834/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002835uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002836ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002837 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002838 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002839
Dan Gohman622ed672009-05-04 22:02:23 +00002840 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002841 return std::min(GetMinTrailingZeros(T->getOperand()),
2842 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002843
Dan Gohman622ed672009-05-04 22:02:23 +00002844 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002845 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2846 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2847 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002848 }
2849
Dan Gohman622ed672009-05-04 22:02:23 +00002850 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002851 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2852 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2853 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002854 }
2855
Dan Gohman622ed672009-05-04 22:02:23 +00002856 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002857 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002858 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002859 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002860 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002861 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002862 }
2863
Dan Gohman622ed672009-05-04 22:02:23 +00002864 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002865 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002866 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2867 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002868 for (unsigned i = 1, e = M->getNumOperands();
2869 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002870 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002871 BitWidth);
2872 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002873 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002874
Dan Gohman622ed672009-05-04 22:02:23 +00002875 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002876 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002877 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002878 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002879 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002880 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002881 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002882
Dan Gohman622ed672009-05-04 22:02:23 +00002883 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002884 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002885 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002886 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002887 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002888 return MinOpRes;
2889 }
2890
Dan Gohman622ed672009-05-04 22:02:23 +00002891 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002892 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002893 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002894 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002895 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002896 return MinOpRes;
2897 }
2898
Dan Gohman2c364ad2009-06-19 23:29:04 +00002899 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2900 // For a SCEVUnknown, ask ValueTracking.
2901 unsigned BitWidth = getTypeSizeInBits(U->getType());
2902 APInt Mask = APInt::getAllOnesValue(BitWidth);
2903 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2904 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2905 return Zeros.countTrailingOnes();
2906 }
2907
2908 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002909 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002910}
Chris Lattner53e677a2004-04-02 20:23:17 +00002911
Dan Gohman85b05a22009-07-13 21:35:55 +00002912/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2913///
2914ConstantRange
2915ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00002916 // See if we've computed this range already.
2917 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
2918 if (I != UnsignedRanges.end())
2919 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002920
2921 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002922 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman2c364ad2009-06-19 23:29:04 +00002923
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002924 unsigned BitWidth = getTypeSizeInBits(S->getType());
2925 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
2926
2927 // If the value has known zeros, the maximum unsigned value will have those
2928 // known zeros as well.
2929 uint32_t TZ = GetMinTrailingZeros(S);
2930 if (TZ != 0)
2931 ConservativeResult =
2932 ConstantRange(APInt::getMinValue(BitWidth),
2933 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
2934
Dan Gohman85b05a22009-07-13 21:35:55 +00002935 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2936 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2937 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2938 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002939 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002940 }
2941
2942 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2943 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2944 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2945 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002946 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002947 }
2948
2949 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2950 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2951 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2952 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002953 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002954 }
2955
2956 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2957 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2958 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2959 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002960 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00002961 }
2962
2963 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2964 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2965 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002966 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002967 }
2968
2969 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2970 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002971 return setUnsignedRange(ZExt,
2972 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002973 }
2974
2975 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2976 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002977 return setUnsignedRange(SExt,
2978 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002979 }
2980
2981 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2982 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00002983 return setUnsignedRange(Trunc,
2984 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 unsigned wrap, the value will never be less than its
2989 // initial value.
2990 if (AddRec->hasNoUnsignedWrap())
2991 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanbca091d2010-04-12 23:08:18 +00002992 if (!C->getValue()->isZero())
Dan Gohmanbc7129f2010-04-11 22:12:18 +00002993 ConservativeResult =
Dan Gohman8a18d6b2010-06-30 06:58:35 +00002994 ConservativeResult.intersectWith(
2995 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohman85b05a22009-07-13 21:35:55 +00002996
2997 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00002998 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00002999 const Type *Ty = AddRec->getType();
3000 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003001 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3002 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003003 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3004
3005 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003006 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003007
3008 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003009 ConstantRange StepRange = getSignedRange(Step);
3010 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3011 ConstantRange EndRange =
3012 StartRange.add(MaxBECountRange.multiply(StepRange));
3013
3014 // Check for overflow. This must be done with ConstantRange arithmetic
3015 // because we could be called from within the ScalarEvolution overflow
3016 // checking code.
3017 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3018 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3019 ConstantRange ExtMaxBECountRange =
3020 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3021 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3022 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3023 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003024 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003025
Dan Gohman85b05a22009-07-13 21:35:55 +00003026 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3027 EndRange.getUnsignedMin());
3028 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3029 EndRange.getUnsignedMax());
3030 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003031 return setUnsignedRange(AddRec, ConservativeResult);
3032 return setUnsignedRange(AddRec,
3033 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003034 }
3035 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003036
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003037 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003038 }
3039
3040 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3041 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman2c364ad2009-06-19 23:29:04 +00003042 APInt Mask = APInt::getAllOnesValue(BitWidth);
3043 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
3044 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00003045 if (Ones == ~Zeros + 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003046 return setUnsignedRange(U, ConservativeResult);
3047 return setUnsignedRange(U,
3048 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003049 }
3050
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003051 return setUnsignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003052}
3053
Dan Gohman85b05a22009-07-13 21:35:55 +00003054/// getSignedRange - Determine the signed range for a particular SCEV.
3055///
3056ConstantRange
3057ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003058 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3059 if (I != SignedRanges.end())
3060 return I->second;
Dan Gohman2c364ad2009-06-19 23:29:04 +00003061
Dan Gohman85b05a22009-07-13 21:35:55 +00003062 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003063 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohman85b05a22009-07-13 21:35:55 +00003064
Dan Gohman52fddd32010-01-26 04:40:18 +00003065 unsigned BitWidth = getTypeSizeInBits(S->getType());
3066 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3067
3068 // If the value has known zeros, the maximum signed value will have those
3069 // known zeros as well.
3070 uint32_t TZ = GetMinTrailingZeros(S);
3071 if (TZ != 0)
3072 ConservativeResult =
3073 ConstantRange(APInt::getSignedMinValue(BitWidth),
3074 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3075
Dan Gohman85b05a22009-07-13 21:35:55 +00003076 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3077 ConstantRange X = getSignedRange(Add->getOperand(0));
3078 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3079 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003080 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003081 }
3082
Dan Gohman85b05a22009-07-13 21:35:55 +00003083 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3084 ConstantRange X = getSignedRange(Mul->getOperand(0));
3085 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3086 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003087 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003088 }
3089
Dan Gohman85b05a22009-07-13 21:35:55 +00003090 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3091 ConstantRange X = getSignedRange(SMax->getOperand(0));
3092 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3093 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003094 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003095 }
Dan Gohman62849c02009-06-24 01:05:09 +00003096
Dan Gohman85b05a22009-07-13 21:35:55 +00003097 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3098 ConstantRange X = getSignedRange(UMax->getOperand(0));
3099 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3100 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003101 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohman85b05a22009-07-13 21:35:55 +00003102 }
Dan Gohman62849c02009-06-24 01:05:09 +00003103
Dan Gohman85b05a22009-07-13 21:35:55 +00003104 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3105 ConstantRange X = getSignedRange(UDiv->getLHS());
3106 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003107 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003108 }
Dan Gohman62849c02009-06-24 01:05:09 +00003109
Dan Gohman85b05a22009-07-13 21:35:55 +00003110 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3111 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003112 return setSignedRange(ZExt,
3113 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003114 }
3115
3116 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3117 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003118 return setSignedRange(SExt,
3119 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003120 }
3121
3122 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3123 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003124 return setSignedRange(Trunc,
3125 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohman85b05a22009-07-13 21:35:55 +00003126 }
3127
Dan Gohman85b05a22009-07-13 21:35:55 +00003128 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00003129 // If there's no signed wrap, and all the operands have the same sign or
3130 // zero, the value won't ever change sign.
3131 if (AddRec->hasNoSignedWrap()) {
3132 bool AllNonNeg = true;
3133 bool AllNonPos = true;
3134 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3135 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3136 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3137 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003138 if (AllNonNeg)
Dan Gohman52fddd32010-01-26 04:40:18 +00003139 ConservativeResult = ConservativeResult.intersectWith(
3140 ConstantRange(APInt(BitWidth, 0),
3141 APInt::getSignedMinValue(BitWidth)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003142 else if (AllNonPos)
Dan Gohman52fddd32010-01-26 04:40:18 +00003143 ConservativeResult = ConservativeResult.intersectWith(
3144 ConstantRange(APInt::getSignedMinValue(BitWidth),
3145 APInt(BitWidth, 1)));
Dan Gohmana10756e2010-01-21 02:09:26 +00003146 }
Dan Gohman85b05a22009-07-13 21:35:55 +00003147
3148 // TODO: non-affine addrec
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003149 if (AddRec->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003150 const Type *Ty = AddRec->getType();
3151 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc9c36cb2010-01-26 19:19:05 +00003152 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3153 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohman85b05a22009-07-13 21:35:55 +00003154 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3155
3156 const SCEV *Start = AddRec->getStart();
Dan Gohman646e0472010-04-12 07:39:33 +00003157 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00003158
3159 ConstantRange StartRange = getSignedRange(Start);
Dan Gohman646e0472010-04-12 07:39:33 +00003160 ConstantRange StepRange = getSignedRange(Step);
3161 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3162 ConstantRange EndRange =
3163 StartRange.add(MaxBECountRange.multiply(StepRange));
3164
3165 // Check for overflow. This must be done with ConstantRange arithmetic
3166 // because we could be called from within the ScalarEvolution overflow
3167 // checking code.
3168 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3169 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3170 ConstantRange ExtMaxBECountRange =
3171 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3172 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3173 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3174 ExtEndRange)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003175 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman646e0472010-04-12 07:39:33 +00003176
Dan Gohman85b05a22009-07-13 21:35:55 +00003177 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3178 EndRange.getSignedMin());
3179 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3180 EndRange.getSignedMax());
3181 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003182 return setSignedRange(AddRec, ConservativeResult);
3183 return setSignedRange(AddRec,
3184 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohman62849c02009-06-24 01:05:09 +00003185 }
Dan Gohman62849c02009-06-24 01:05:09 +00003186 }
Dan Gohmana10756e2010-01-21 02:09:26 +00003187
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003188 return setSignedRange(AddRec, ConservativeResult);
Dan Gohman62849c02009-06-24 01:05:09 +00003189 }
3190
Dan Gohman2c364ad2009-06-19 23:29:04 +00003191 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3192 // For a SCEVUnknown, ask ValueTracking.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00003193 if (!U->getValue()->getType()->isIntegerTy() && !TD)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003194 return setSignedRange(U, ConservativeResult);
Dan Gohman85b05a22009-07-13 21:35:55 +00003195 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
3196 if (NS == 1)
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003197 return setSignedRange(U, ConservativeResult);
3198 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohman85b05a22009-07-13 21:35:55 +00003199 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003200 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohman2c364ad2009-06-19 23:29:04 +00003201 }
3202
Dan Gohman7c0fd8e2010-11-17 20:23:08 +00003203 return setSignedRange(S, ConservativeResult);
Dan Gohman2c364ad2009-06-19 23:29:04 +00003204}
3205
Chris Lattner53e677a2004-04-02 20:23:17 +00003206/// createSCEV - We know that there is no SCEV for the specified value.
3207/// Analyze the expression.
3208///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003209const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003210 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003211 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00003212
Dan Gohman6c459a22008-06-22 19:56:46 +00003213 unsigned Opcode = Instruction::UserOp1;
Dan Gohman4ecbca52010-03-09 23:46:50 +00003214 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman6c459a22008-06-22 19:56:46 +00003215 Opcode = I->getOpcode();
Dan Gohman4ecbca52010-03-09 23:46:50 +00003216
3217 // Don't attempt to analyze instructions in blocks that aren't
3218 // reachable. Such instructions don't matter, and they aren't required
3219 // to obey basic rules for definitions dominating uses which this
3220 // analysis depends on.
3221 if (!DT->isReachableFromEntry(I->getParent()))
3222 return getUnknown(V);
3223 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman6c459a22008-06-22 19:56:46 +00003224 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00003225 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
3226 return getConstant(CI);
3227 else if (isa<ConstantPointerNull>(V))
Dan Gohmandeff6212010-05-03 22:09:21 +00003228 return getConstant(V->getType(), 0);
Dan Gohman26812322009-08-25 17:49:57 +00003229 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
3230 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00003231 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003232 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00003233
Dan Gohmanca178902009-07-17 20:47:02 +00003234 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00003235 switch (Opcode) {
Dan Gohmand3f171d2010-08-16 16:03:49 +00003236 case Instruction::Add: {
3237 // The simple thing to do would be to just call getSCEV on both operands
3238 // and call getAddExpr with the result. However if we're looking at a
3239 // bunch of things all added together, this can be quite inefficient,
3240 // because it leads to N-1 getAddExpr calls for N ultimate operands.
3241 // Instead, gather up all the operands and make a single getAddExpr call.
3242 // LLVM IR canonical form means we need only traverse the left operands.
3243 SmallVector<const SCEV *, 4> AddOps;
3244 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman3f19c092010-08-31 22:53:17 +00003245 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
3246 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
3247 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
3248 break;
Dan Gohmand3f171d2010-08-16 16:03:49 +00003249 U = cast<Operator>(Op);
Dan Gohman3f19c092010-08-31 22:53:17 +00003250 const SCEV *Op1 = getSCEV(U->getOperand(1));
3251 if (Opcode == Instruction::Sub)
3252 AddOps.push_back(getNegativeSCEV(Op1));
3253 else
3254 AddOps.push_back(Op1);
Dan Gohmand3f171d2010-08-16 16:03:49 +00003255 }
3256 AddOps.push_back(getSCEV(U->getOperand(0)));
3257 return getAddExpr(AddOps);
3258 }
3259 case Instruction::Mul: {
3260 // See the Add code above.
3261 SmallVector<const SCEV *, 4> MulOps;
3262 MulOps.push_back(getSCEV(U->getOperand(1)));
3263 for (Value *Op = U->getOperand(0);
3264 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
3265 Op = U->getOperand(0)) {
3266 U = cast<Operator>(Op);
3267 MulOps.push_back(getSCEV(U->getOperand(1)));
3268 }
3269 MulOps.push_back(getSCEV(U->getOperand(0)));
3270 return getMulExpr(MulOps);
3271 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003272 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003273 return getUDivExpr(getSCEV(U->getOperand(0)),
3274 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00003275 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003276 return getMinusSCEV(getSCEV(U->getOperand(0)),
3277 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003278 case Instruction::And:
3279 // For an expression like x&255 that merely masks off the high bits,
3280 // use zext(trunc(x)) as the SCEV expression.
3281 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003282 if (CI->isNullValue())
3283 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00003284 if (CI->isAllOnesValue())
3285 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00003286 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003287
3288 // Instcombine's ShrinkDemandedConstant may strip bits out of
3289 // constants, obscuring what would otherwise be a low-bits mask.
3290 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
3291 // knew about to reconstruct a low-bits mask value.
3292 unsigned LZ = A.countLeadingZeros();
3293 unsigned BitWidth = A.getBitWidth();
3294 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
3295 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3296 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3297
3298 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3299
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003300 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003301 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003302 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003303 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003304 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003305 }
3306 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003307
Dan Gohman6c459a22008-06-22 19:56:46 +00003308 case Instruction::Or:
3309 // If the RHS of the Or is a constant, we may have something like:
3310 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3311 // optimizations will transparently handle this case.
3312 //
3313 // In order for this transformation to be safe, the LHS must be of the
3314 // form X*(2^n) and the Or constant must be less than 2^n.
3315 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003316 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003317 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003318 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003319 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3320 // Build a plain add SCEV.
3321 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3322 // If the LHS of the add was an addrec and it has no-wrap flags,
3323 // transfer the no-wrap flags, since an or won't introduce a wrap.
3324 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3325 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3326 if (OldAR->hasNoUnsignedWrap())
3327 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3328 if (OldAR->hasNoSignedWrap())
3329 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3330 }
3331 return S;
3332 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003333 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003334 break;
3335 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003336 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003337 // If the RHS of the xor is a signbit, then this is just an add.
3338 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003339 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003340 return getAddExpr(getSCEV(U->getOperand(0)),
3341 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003342
3343 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003344 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003345 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003346
3347 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3348 // This is a variant of the check for xor with -1, and it handles
3349 // the case where instcombine has trimmed non-demanded bits out
3350 // of an xor with -1.
3351 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3352 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3353 if (BO->getOpcode() == Instruction::And &&
3354 LCI->getValue() == CI->getValue())
3355 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003356 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003357 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003358 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003359 const Type *Z0Ty = Z0->getType();
3360 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3361
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003362 // If C is a low-bits mask, the zero extend is serving to
Dan Gohman82052832009-06-18 00:00:20 +00003363 // mask off the high bits. Complement the operand and
3364 // re-apply the zext.
3365 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3366 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3367
3368 // If C is a single bit, it may be in the sign-bit position
3369 // before the zero-extend. In this case, represent the xor
3370 // using an add, which is equivalent, and re-apply the zext.
3371 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3372 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3373 Trunc.isSignBit())
3374 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3375 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003376 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003377 }
3378 break;
3379
3380 case Instruction::Shl:
3381 // Turn shift left of a constant amount into a multiply.
3382 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003383 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003384
3385 // If the shift count is not less than the bitwidth, the result of
3386 // the shift is undefined. Don't try to analyze it, because the
3387 // resolution chosen here may differ from the resolution chosen in
3388 // other parts of the compiler.
3389 if (SA->getValue().uge(BitWidth))
3390 break;
3391
Owen Andersoneed707b2009-07-24 23:12:02 +00003392 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003393 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003394 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003395 }
3396 break;
3397
Nick Lewycky01eaf802008-07-07 06:15:49 +00003398 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003399 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003400 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman4f8eea82010-02-01 18:27:38 +00003401 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003402
3403 // If the shift count is not less than the bitwidth, the result of
3404 // the shift is undefined. Don't try to analyze it, because the
3405 // resolution chosen here may differ from the resolution chosen in
3406 // other parts of the compiler.
3407 if (SA->getValue().uge(BitWidth))
3408 break;
3409
Owen Andersoneed707b2009-07-24 23:12:02 +00003410 Constant *X = ConstantInt::get(getContext(),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003411 APInt(BitWidth, 1).shl(SA->getZExtValue()));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003412 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003413 }
3414 break;
3415
Dan Gohman4ee29af2009-04-21 02:26:00 +00003416 case Instruction::AShr:
3417 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3418 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003419 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003420 if (L->getOpcode() == Instruction::Shl &&
3421 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003422 uint64_t BitWidth = getTypeSizeInBits(U->getType());
3423
3424 // If the shift count is not less than the bitwidth, the result of
3425 // the shift is undefined. Don't try to analyze it, because the
3426 // resolution chosen here may differ from the resolution chosen in
3427 // other parts of the compiler.
3428 if (CI->getValue().uge(BitWidth))
3429 break;
3430
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003431 uint64_t Amt = BitWidth - CI->getZExtValue();
3432 if (Amt == BitWidth)
3433 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman4ee29af2009-04-21 02:26:00 +00003434 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003435 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanddb3eaf2010-04-22 01:35:11 +00003436 IntegerType::get(getContext(),
3437 Amt)),
3438 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003439 }
3440 break;
3441
Dan Gohman6c459a22008-06-22 19:56:46 +00003442 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003443 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003444
3445 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003446 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003447
3448 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003449 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003450
3451 case Instruction::BitCast:
3452 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003453 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003454 return getSCEV(U->getOperand(0));
3455 break;
3456
Dan Gohman4f8eea82010-02-01 18:27:38 +00003457 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
3458 // lead to pointer expressions which cannot safely be expanded to GEPs,
3459 // because ScalarEvolution doesn't respect the GEP aliasing rules when
3460 // simplifying integer expressions.
Dan Gohman2d1be872009-04-16 03:18:22 +00003461
Dan Gohman26466c02009-05-08 20:26:55 +00003462 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003463 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003464
Dan Gohman6c459a22008-06-22 19:56:46 +00003465 case Instruction::PHI:
3466 return createNodeForPHI(cast<PHINode>(U));
3467
3468 case Instruction::Select:
3469 // This could be a smax or umax that was lowered earlier.
3470 // Try to recover it.
3471 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3472 Value *LHS = ICI->getOperand(0);
3473 Value *RHS = ICI->getOperand(1);
3474 switch (ICI->getPredicate()) {
3475 case ICmpInst::ICMP_SLT:
3476 case ICmpInst::ICMP_SLE:
3477 std::swap(LHS, RHS);
3478 // fall through
3479 case ICmpInst::ICMP_SGT:
3480 case ICmpInst::ICMP_SGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003481 // a >s b ? a+x : b+x -> smax(a, b)+x
3482 // a >s b ? b+x : a+x -> smin(a, b)+x
3483 if (LHS->getType() == U->getType()) {
3484 const SCEV *LS = getSCEV(LHS);
3485 const SCEV *RS = getSCEV(RHS);
3486 const SCEV *LA = getSCEV(U->getOperand(1));
3487 const SCEV *RA = getSCEV(U->getOperand(2));
3488 const SCEV *LDiff = getMinusSCEV(LA, LS);
3489 const SCEV *RDiff = getMinusSCEV(RA, RS);
3490 if (LDiff == RDiff)
3491 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
3492 LDiff = getMinusSCEV(LA, RS);
3493 RDiff = getMinusSCEV(RA, LS);
3494 if (LDiff == RDiff)
3495 return getAddExpr(getSMinExpr(LS, RS), LDiff);
3496 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003497 break;
3498 case ICmpInst::ICMP_ULT:
3499 case ICmpInst::ICMP_ULE:
3500 std::swap(LHS, RHS);
3501 // fall through
3502 case ICmpInst::ICMP_UGT:
3503 case ICmpInst::ICMP_UGE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003504 // a >u b ? a+x : b+x -> umax(a, b)+x
3505 // a >u b ? b+x : a+x -> umin(a, b)+x
3506 if (LHS->getType() == U->getType()) {
3507 const SCEV *LS = getSCEV(LHS);
3508 const SCEV *RS = getSCEV(RHS);
3509 const SCEV *LA = getSCEV(U->getOperand(1));
3510 const SCEV *RA = getSCEV(U->getOperand(2));
3511 const SCEV *LDiff = getMinusSCEV(LA, LS);
3512 const SCEV *RDiff = getMinusSCEV(RA, RS);
3513 if (LDiff == RDiff)
3514 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
3515 LDiff = getMinusSCEV(LA, RS);
3516 RDiff = getMinusSCEV(RA, LS);
3517 if (LDiff == RDiff)
3518 return getAddExpr(getUMinExpr(LS, RS), LDiff);
3519 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003520 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003521 case ICmpInst::ICMP_NE:
Dan Gohman9f93d302010-04-24 03:09:42 +00003522 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
3523 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003524 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003525 cast<ConstantInt>(RHS)->isZero()) {
3526 const SCEV *One = getConstant(LHS->getType(), 1);
3527 const SCEV *LS = getSCEV(LHS);
3528 const SCEV *LA = getSCEV(U->getOperand(1));
3529 const SCEV *RA = getSCEV(U->getOperand(2));
3530 const SCEV *LDiff = getMinusSCEV(LA, LS);
3531 const SCEV *RDiff = getMinusSCEV(RA, One);
3532 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003533 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003534 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003535 break;
3536 case ICmpInst::ICMP_EQ:
Dan Gohman9f93d302010-04-24 03:09:42 +00003537 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
3538 if (LHS->getType() == U->getType() &&
Dan Gohman30fb5122009-06-18 20:21:07 +00003539 isa<ConstantInt>(RHS) &&
Dan Gohman9f93d302010-04-24 03:09:42 +00003540 cast<ConstantInt>(RHS)->isZero()) {
3541 const SCEV *One = getConstant(LHS->getType(), 1);
3542 const SCEV *LS = getSCEV(LHS);
3543 const SCEV *LA = getSCEV(U->getOperand(1));
3544 const SCEV *RA = getSCEV(U->getOperand(2));
3545 const SCEV *LDiff = getMinusSCEV(LA, One);
3546 const SCEV *RDiff = getMinusSCEV(RA, LS);
3547 if (LDiff == RDiff)
Dan Gohman58a85b92010-08-13 20:17:14 +00003548 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohman9f93d302010-04-24 03:09:42 +00003549 }
Dan Gohman30fb5122009-06-18 20:21:07 +00003550 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003551 default:
3552 break;
3553 }
3554 }
3555
3556 default: // We cannot analyze this expression.
3557 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003558 }
3559
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003560 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003561}
3562
3563
3564
3565//===----------------------------------------------------------------------===//
3566// Iteration Count Computation Code
3567//
3568
Dan Gohman46bdfb02009-02-24 18:55:53 +00003569/// getBackedgeTakenCount - If the specified loop has a predictable
3570/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3571/// object. The backedge-taken count is the number of times the loop header
3572/// will be branched to from within the loop. This is one less than the
3573/// trip count of the loop, since it doesn't count the first iteration,
3574/// when the header is branched to from outside the loop.
3575///
3576/// Note that it is not valid to call this method on a loop without a
3577/// loop-invariant backedge-taken count (see
3578/// hasLoopInvariantBackedgeTakenCount).
3579///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003580const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003581 return getBackedgeTakenInfo(L).Exact;
3582}
3583
3584/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3585/// return the least SCEV value that is known never to be less than the
3586/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003587const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003588 return getBackedgeTakenInfo(L).Max;
3589}
3590
Dan Gohman59ae6b92009-07-08 19:23:34 +00003591/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3592/// onto the given Worklist.
3593static void
3594PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3595 BasicBlock *Header = L->getHeader();
3596
3597 // Push all Loop-header PHIs onto the Worklist stack.
3598 for (BasicBlock::iterator I = Header->begin();
3599 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3600 Worklist.push_back(PN);
3601}
3602
Dan Gohmana1af7572009-04-30 20:47:05 +00003603const ScalarEvolution::BackedgeTakenInfo &
3604ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003605 // Initially insert a CouldNotCompute for this loop. If the insertion
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003606 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman01ecca22009-04-27 20:16:15 +00003607 // update the value. The temporary CouldNotCompute value tells SCEV
3608 // code elsewhere that it shouldn't attempt to request a new
3609 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003610 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003611 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3612 if (Pair.second) {
Dan Gohman93dacad2010-01-26 16:46:18 +00003613 BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
3614 if (BECount.Exact != getCouldNotCompute()) {
Dan Gohman17ead4f2010-11-17 21:23:15 +00003615 assert(isLoopInvariant(BECount.Exact, L) &&
3616 isLoopInvariant(BECount.Max, L) &&
Dan Gohman93dacad2010-01-26 16:46:18 +00003617 "Computed backedge-taken count isn't loop invariant for loop!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003618 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003619
Dan Gohman01ecca22009-04-27 20:16:15 +00003620 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003621 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003622 } else {
Dan Gohman93dacad2010-01-26 16:46:18 +00003623 if (BECount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003624 // Update the value in the map.
Dan Gohman93dacad2010-01-26 16:46:18 +00003625 Pair.first->second = BECount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003626 if (isa<PHINode>(L->getHeader()->begin()))
3627 // Only count loops that have phi nodes as not being computable.
3628 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003629 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003630
3631 // Now that we know more about the trip count for this loop, forget any
3632 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003633 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003634 // information. This is similar to the code in forgetLoop, except that
3635 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman93dacad2010-01-26 16:46:18 +00003636 if (BECount.hasAnyInfo()) {
Dan Gohman59ae6b92009-07-08 19:23:34 +00003637 SmallVector<Instruction *, 16> Worklist;
3638 PushLoopPHIs(L, Worklist);
3639
3640 SmallPtrSet<Instruction *, 8> Visited;
3641 while (!Worklist.empty()) {
3642 Instruction *I = Worklist.pop_back_val();
3643 if (!Visited.insert(I)) continue;
3644
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003645 ValueExprMapType::iterator It =
3646 ValueExprMap.find(static_cast<Value *>(I));
3647 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003648 const SCEV *Old = It->second;
3649
Dan Gohman59ae6b92009-07-08 19:23:34 +00003650 // SCEVUnknown for a PHI either means that it has an unrecognized
3651 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003652 // by createNodeForPHI. In the former case, additional loop trip
3653 // count information isn't going to change anything. In the later
3654 // case, createNodeForPHI will perform the necessary updates on its
3655 // own when it gets to that point.
Dan Gohman6678e7b2010-11-17 02:44:44 +00003656 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
3657 ValuesAtScopes.erase(Old);
3658 UnsignedRanges.erase(Old);
3659 SignedRanges.erase(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003660 ValueExprMap.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003661 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003662 if (PHINode *PN = dyn_cast<PHINode>(I))
3663 ConstantEvolutionLoopExitValue.erase(PN);
3664 }
3665
3666 PushDefUseChildren(I, Worklist);
3667 }
3668 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003669 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003670 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003671}
3672
Dan Gohman4c7279a2009-10-31 15:04:55 +00003673/// forgetLoop - This method should be called by the client when it has
3674/// changed a loop in a way that may effect ScalarEvolution's ability to
3675/// compute a trip count, or if the loop is deleted.
3676void ScalarEvolution::forgetLoop(const Loop *L) {
3677 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003678 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003679
Dan Gohman4c7279a2009-10-31 15:04:55 +00003680 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003681 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003682 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003683
Dan Gohman59ae6b92009-07-08 19:23:34 +00003684 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003685 while (!Worklist.empty()) {
3686 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003687 if (!Visited.insert(I)) continue;
3688
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003689 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3690 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003691 const SCEV *Old = It->second;
3692 ValuesAtScopes.erase(Old);
3693 UnsignedRanges.erase(Old);
3694 SignedRanges.erase(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003695 ValueExprMap.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003696 if (PHINode *PN = dyn_cast<PHINode>(I))
3697 ConstantEvolutionLoopExitValue.erase(PN);
3698 }
3699
3700 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003701 }
Dan Gohmane60dcb52010-10-29 20:16:10 +00003702
3703 // Forget all contained loops too, to avoid dangling entries in the
3704 // ValuesAtScopes map.
3705 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3706 forgetLoop(*I);
Dan Gohman60f8a632009-02-17 20:49:49 +00003707}
3708
Eric Christophere6cbfa62010-07-29 01:25:38 +00003709/// forgetValue - This method should be called by the client when it has
3710/// changed a value in a way that may effect its value, or which may
3711/// disconnect it from a def-use chain linking it to a loop.
3712void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003713 Instruction *I = dyn_cast<Instruction>(V);
3714 if (!I) return;
3715
3716 // Drop information about expressions based on loop-header PHIs.
3717 SmallVector<Instruction *, 16> Worklist;
3718 Worklist.push_back(I);
3719
3720 SmallPtrSet<Instruction *, 8> Visited;
3721 while (!Worklist.empty()) {
3722 I = Worklist.pop_back_val();
3723 if (!Visited.insert(I)) continue;
3724
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003725 ValueExprMapType::iterator It = ValueExprMap.find(static_cast<Value *>(I));
3726 if (It != ValueExprMap.end()) {
Dan Gohman6678e7b2010-11-17 02:44:44 +00003727 const SCEV *Old = It->second;
3728 ValuesAtScopes.erase(Old);
3729 UnsignedRanges.erase(Old);
3730 SignedRanges.erase(Old);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00003731 ValueExprMap.erase(It);
Dale Johannesen45a2d7d2010-02-19 07:14:22 +00003732 if (PHINode *PN = dyn_cast<PHINode>(I))
3733 ConstantEvolutionLoopExitValue.erase(PN);
3734 }
3735
3736 PushDefUseChildren(I, Worklist);
3737 }
3738}
3739
Dan Gohman46bdfb02009-02-24 18:55:53 +00003740/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3741/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003742ScalarEvolution::BackedgeTakenInfo
3743ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003744 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003745 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003746
Dan Gohmana334aa72009-06-22 00:31:57 +00003747 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003748 const SCEV *BECount = getCouldNotCompute();
3749 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003750 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003751 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3752 BackedgeTakenInfo NewBTI =
3753 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003754
Dan Gohman1c343752009-06-27 21:21:31 +00003755 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003756 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003757 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003758 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003759 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003760 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003761 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003762 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003763 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003764 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003765 }
Dan Gohman1c343752009-06-27 21:21:31 +00003766 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003767 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003768 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003769 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003770 }
3771
3772 return BackedgeTakenInfo(BECount, MaxBECount);
3773}
3774
3775/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3776/// of the specified loop will execute if it exits via the specified block.
3777ScalarEvolution::BackedgeTakenInfo
3778ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3779 BasicBlock *ExitingBlock) {
3780
3781 // Okay, we've chosen an exiting block. See what condition causes us to
3782 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003783 //
3784 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003785 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003786 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003787 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003788
Chris Lattner8b0e3602007-01-07 02:24:26 +00003789 // At this point, we know we have a conditional branch that determines whether
3790 // the loop is exited. However, we don't know if the branch is executed each
3791 // time through the loop. If not, then the execution count of the branch will
3792 // not be equal to the trip count of the loop.
3793 //
3794 // Currently we check for this by checking to see if the Exit branch goes to
3795 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003796 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003797 // loop header. This is common for un-rotated loops.
3798 //
3799 // If both of those tests fail, walk up the unique predecessor chain to the
3800 // header, stopping if there is an edge that doesn't exit the loop. If the
3801 // header is reached, the execution count of the branch will be equal to the
3802 // trip count of the loop.
3803 //
3804 // More extensive analysis could be done to handle more cases here.
3805 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003806 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003807 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003808 ExitBr->getParent() != L->getHeader()) {
3809 // The simple checks failed, try climbing the unique predecessor chain
3810 // up to the header.
3811 bool Ok = false;
3812 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3813 BasicBlock *Pred = BB->getUniquePredecessor();
3814 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003815 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003816 TerminatorInst *PredTerm = Pred->getTerminator();
3817 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3818 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3819 if (PredSucc == BB)
3820 continue;
3821 // If the predecessor has a successor that isn't BB and isn't
3822 // outside the loop, assume the worst.
3823 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003824 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003825 }
3826 if (Pred == L->getHeader()) {
3827 Ok = true;
3828 break;
3829 }
3830 BB = Pred;
3831 }
3832 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003833 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003834 }
3835
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003836 // Proceed to the next level to examine the exit condition expression.
Dan Gohmana334aa72009-06-22 00:31:57 +00003837 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3838 ExitBr->getSuccessor(0),
3839 ExitBr->getSuccessor(1));
3840}
3841
3842/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3843/// backedge of the specified loop will execute if its exit condition
3844/// were a conditional branch of ExitCond, TBB, and FBB.
3845ScalarEvolution::BackedgeTakenInfo
3846ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3847 Value *ExitCond,
3848 BasicBlock *TBB,
3849 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003850 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003851 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3852 if (BO->getOpcode() == Instruction::And) {
3853 // Recurse on the operands of the and.
3854 BackedgeTakenInfo BTI0 =
3855 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3856 BackedgeTakenInfo BTI1 =
3857 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003858 const SCEV *BECount = getCouldNotCompute();
3859 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003860 if (L->contains(TBB)) {
3861 // Both conditions must be true for the loop to continue executing.
3862 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003863 if (BTI0.Exact == getCouldNotCompute() ||
3864 BTI1.Exact == getCouldNotCompute())
3865 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003866 else
3867 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003868 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003869 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003870 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003871 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003872 else
3873 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003874 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003875 // Both conditions must be true at the same time for the loop to exit.
3876 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003877 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003878 if (BTI0.Max == BTI1.Max)
3879 MaxBECount = BTI0.Max;
3880 if (BTI0.Exact == BTI1.Exact)
3881 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003882 }
3883
3884 return BackedgeTakenInfo(BECount, MaxBECount);
3885 }
3886 if (BO->getOpcode() == Instruction::Or) {
3887 // Recurse on the operands of the or.
3888 BackedgeTakenInfo BTI0 =
3889 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3890 BackedgeTakenInfo BTI1 =
3891 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003892 const SCEV *BECount = getCouldNotCompute();
3893 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003894 if (L->contains(FBB)) {
3895 // Both conditions must be false for the loop to continue executing.
3896 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003897 if (BTI0.Exact == getCouldNotCompute() ||
3898 BTI1.Exact == getCouldNotCompute())
3899 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003900 else
3901 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003902 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003903 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003904 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003905 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003906 else
3907 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003908 } else {
Dan Gohman4ee87392010-08-11 00:12:36 +00003909 // Both conditions must be false at the same time for the loop to exit.
3910 // For now, be conservative.
Dan Gohmana334aa72009-06-22 00:31:57 +00003911 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman4ee87392010-08-11 00:12:36 +00003912 if (BTI0.Max == BTI1.Max)
3913 MaxBECount = BTI0.Max;
3914 if (BTI0.Exact == BTI1.Exact)
3915 BECount = BTI0.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003916 }
3917
3918 return BackedgeTakenInfo(BECount, MaxBECount);
3919 }
3920 }
3921
3922 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003923 // Proceed to the next level to examine the icmp.
Dan Gohmana334aa72009-06-22 00:31:57 +00003924 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3925 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003926
Dan Gohman00cb5b72010-02-19 18:12:07 +00003927 // Check for a constant condition. These are normally stripped out by
3928 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
3929 // preserve the CFG and is temporarily leaving constant conditions
3930 // in place.
3931 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
3932 if (L->contains(FBB) == !CI->getZExtValue())
3933 // The backedge is always taken.
3934 return getCouldNotCompute();
3935 else
3936 // The backedge is never taken.
Dan Gohmandeff6212010-05-03 22:09:21 +00003937 return getConstant(CI->getType(), 0);
Dan Gohman00cb5b72010-02-19 18:12:07 +00003938 }
3939
Eli Friedman361e54d2009-05-09 12:32:42 +00003940 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003941 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3942}
3943
3944/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3945/// backedge of the specified loop will execute if its exit condition
3946/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3947ScalarEvolution::BackedgeTakenInfo
3948ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3949 ICmpInst *ExitCond,
3950 BasicBlock *TBB,
3951 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003952
Reid Spencere4d87aa2006-12-23 06:05:41 +00003953 // If the condition was exit on true, convert the condition to exit on false
3954 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003955 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003956 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003957 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003958 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003959
3960 // Handle common loops like: for (X = "string"; *X; ++X)
3961 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3962 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003963 BackedgeTakenInfo ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003964 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf6d009f2010-02-24 17:31:30 +00003965 if (ItCnt.hasAnyInfo())
3966 return ItCnt;
Chris Lattner673e02b2004-10-12 01:49:27 +00003967 }
3968
Dan Gohman0bba49c2009-07-07 17:06:11 +00003969 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3970 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003971
3972 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003973 LHS = getSCEVAtScope(LHS, L);
3974 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003975
Dan Gohman64a845e2009-06-24 04:48:43 +00003976 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003977 // loop the predicate will return true for these inputs.
Dan Gohman17ead4f2010-11-17 21:23:15 +00003978 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003979 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003980 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003981 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003982 }
3983
Dan Gohman03557dc2010-05-03 16:35:17 +00003984 // Simplify the operands before analyzing them.
3985 (void)SimplifyICmpOperands(Cond, LHS, RHS);
3986
Chris Lattner53e677a2004-04-02 20:23:17 +00003987 // If we have a comparison of a chrec against a constant, try to use value
3988 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003989 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3990 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003991 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003992 // Form the constant range.
3993 ConstantRange CompRange(
3994 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003995
Dan Gohman0bba49c2009-07-07 17:06:11 +00003996 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003997 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003998 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003999
Chris Lattner53e677a2004-04-02 20:23:17 +00004000 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004001 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00004002 // Convert to: while (X-Y != 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004003 BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
4004 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004005 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004006 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004007 case ICmpInst::ICMP_EQ: { // while (X == Y)
4008 // Convert to: while (X-Y == 0)
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004009 BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
4010 if (BTI.hasAnyInfo()) return BTI;
Chris Lattner53e677a2004-04-02 20:23:17 +00004011 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004012 }
4013 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004014 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
4015 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004016 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004017 }
4018 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004019 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4020 getNotSCEV(RHS), L, true);
4021 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004022 break;
4023 }
4024 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004025 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
4026 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00004027 break;
4028 }
4029 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00004030 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
4031 getNotSCEV(RHS), L, false);
4032 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004033 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004034 }
Chris Lattner53e677a2004-04-02 20:23:17 +00004035 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004036#if 0
David Greene25e0e872009-12-23 22:18:14 +00004037 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004038 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greene25e0e872009-12-23 22:18:14 +00004039 dbgs() << "[unsigned] ";
4040 dbgs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00004041 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004042 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004043#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00004044 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00004045 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00004046 return
Dan Gohmana334aa72009-06-22 00:31:57 +00004047 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00004048}
4049
Chris Lattner673e02b2004-10-12 01:49:27 +00004050static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00004051EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
4052 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004053 const SCEV *InVal = SE.getConstant(C);
4054 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00004055 assert(isa<SCEVConstant>(Val) &&
4056 "Evaluation of SCEV at constant didn't fold correctly?");
4057 return cast<SCEVConstant>(Val)->getValue();
4058}
4059
4060/// GetAddressedElementFromGlobal - Given a global variable with an initializer
4061/// and a GEP expression (missing the pointer index) indexing into it, return
4062/// the addressed element of the initializer or null if the index expression is
4063/// invalid.
4064static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004065GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00004066 const std::vector<ConstantInt*> &Indices) {
4067 Constant *Init = GV->getInitializer();
4068 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004069 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00004070 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
4071 assert(Idx < CS->getNumOperands() && "Bad struct index!");
4072 Init = cast<Constant>(CS->getOperand(Idx));
4073 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
4074 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
4075 Init = cast<Constant>(CA->getOperand(Idx));
4076 } else if (isa<ConstantAggregateZero>(Init)) {
4077 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
4078 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00004079 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00004080 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
4081 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00004082 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00004083 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00004084 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00004085 }
4086 return 0;
4087 } else {
4088 return 0; // Unknown initializer type
4089 }
4090 }
4091 return Init;
4092}
4093
Dan Gohman46bdfb02009-02-24 18:55:53 +00004094/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
4095/// 'icmp op load X, cst', try to see if we can compute the backedge
4096/// execution count.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004097ScalarEvolution::BackedgeTakenInfo
Dan Gohman64a845e2009-06-24 04:48:43 +00004098ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
4099 LoadInst *LI,
4100 Constant *RHS,
4101 const Loop *L,
4102 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00004103 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004104
4105 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004106 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattner673e02b2004-10-12 01:49:27 +00004107 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00004108 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004109
4110 // Make sure that it is really a constant global we are gepping, with an
4111 // initializer, and make sure the first IDX is really 0.
4112 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00004113 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004114 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
4115 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00004116 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004117
4118 // Okay, we allow one non-constant index into the GEP instruction.
4119 Value *VarIdx = 0;
4120 std::vector<ConstantInt*> Indexes;
4121 unsigned VarIdxNum = 0;
4122 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
4123 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4124 Indexes.push_back(CI);
4125 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00004126 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00004127 VarIdx = GEP->getOperand(i);
4128 VarIdxNum = i-2;
4129 Indexes.push_back(0);
4130 }
4131
4132 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
4133 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004134 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00004135 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00004136
4137 // We can only recognize very limited forms of loop index expressions, in
4138 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00004139 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohman17ead4f2010-11-17 21:23:15 +00004140 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattner673e02b2004-10-12 01:49:27 +00004141 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
4142 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00004143 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004144
4145 unsigned MaxSteps = MaxBruteForceIterations;
4146 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00004147 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00004148 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004149 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00004150
4151 // Form the GEP offset.
4152 Indexes[VarIdxNum] = Val;
4153
Nick Lewyckyc6501b12009-11-23 03:26:09 +00004154 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00004155 if (Result == 0) break; // Cannot compute!
4156
4157 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004158 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004159 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00004160 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00004161#if 0
David Greene25e0e872009-12-23 22:18:14 +00004162 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004163 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
4164 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00004165#endif
4166 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004167 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00004168 }
4169 }
Dan Gohman1c343752009-06-27 21:21:31 +00004170 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00004171}
4172
4173
Chris Lattner3221ad02004-04-17 22:58:41 +00004174/// CanConstantFold - Return true if we can constant fold an instruction of the
4175/// specified type, assuming that all operands were constants.
4176static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00004177 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00004178 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
4179 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004180
Chris Lattner3221ad02004-04-17 22:58:41 +00004181 if (const CallInst *CI = dyn_cast<CallInst>(I))
4182 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00004183 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00004184 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00004185}
4186
Chris Lattner3221ad02004-04-17 22:58:41 +00004187/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
4188/// in the loop that V is derived from. We allow arbitrary operations along the
4189/// way, but the operands of an operation must either be constants or a value
4190/// derived from a constant PHI. If this expression does not fit with these
4191/// constraints, return null.
4192static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
4193 // If this is not an instruction, or if this is an instruction outside of the
4194 // loop, it can't be derived from a loop PHI.
4195 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00004196 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004197
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004198 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004199 if (L->getHeader() == I->getParent())
4200 return PN;
4201 else
4202 // We don't currently keep track of the control flow needed to evaluate
4203 // PHIs, so we cannot handle PHIs inside of loops.
4204 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00004205 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004206
4207 // If we won't be able to constant fold this expression even if the operands
4208 // are constants, return early.
4209 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004210
Chris Lattner3221ad02004-04-17 22:58:41 +00004211 // Otherwise, we can evaluate this instruction if all of its operands are
4212 // constant or derived from a PHI node themselves.
4213 PHINode *PHI = 0;
4214 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
Dan Gohman9d4588f2010-06-22 13:15:46 +00004215 if (!isa<Constant>(I->getOperand(Op))) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004216 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
4217 if (P == 0) return 0; // Not evolving from PHI
4218 if (PHI == 0)
4219 PHI = P;
4220 else if (PHI != P)
4221 return 0; // Evolving from multiple different PHIs.
4222 }
4223
4224 // This is a expression evolving from a constant PHI!
4225 return PHI;
4226}
4227
4228/// EvaluateExpression - Given an expression that passes the
4229/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
4230/// in the loop has the value PHIVal. If we can't fold this expression for some
4231/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004232static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
4233 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004234 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00004235 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00004236 Instruction *I = cast<Instruction>(V);
4237
Dan Gohman9d4588f2010-06-22 13:15:46 +00004238 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattner3221ad02004-04-17 22:58:41 +00004239
4240 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004241 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004242 if (Operands[i] == 0) return 0;
4243 }
4244
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004245 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00004246 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004247 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00004248 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004249 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004250}
4251
4252/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
4253/// in the header of its containing loop, we know the loop executes a
4254/// constant number of times, and the PHI node is just a recurrence
4255/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00004256Constant *
4257ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00004258 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00004259 const Loop *L) {
Dan Gohman8d9c7a62010-08-16 16:30:01 +00004260 std::map<PHINode*, Constant*>::const_iterator I =
Chris Lattner3221ad02004-04-17 22:58:41 +00004261 ConstantEvolutionLoopExitValue.find(PN);
4262 if (I != ConstantEvolutionLoopExitValue.end())
4263 return I->second;
4264
Dan Gohmane0567812010-04-08 23:03:40 +00004265 if (BEs.ugt(MaxBruteForceIterations))
Chris Lattner3221ad02004-04-17 22:58:41 +00004266 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
4267
4268 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
4269
4270 // Since the loop is canonicalized, the PHI node must have two entries. One
4271 // entry must be a constant (coming in from outside of the loop), and the
4272 // second must be derived from the same PHI.
4273 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4274 Constant *StartCST =
4275 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
4276 if (StartCST == 0)
4277 return RetVal = 0; // Must be a constant.
4278
4279 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004280 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4281 !isa<Constant>(BEValue))
Chris Lattner3221ad02004-04-17 22:58:41 +00004282 return RetVal = 0; // Not derived from same PHI.
4283
4284 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00004285 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00004286 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00004287
Dan Gohman46bdfb02009-02-24 18:55:53 +00004288 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00004289 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00004290 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
4291 if (IterationNum == NumIterations)
4292 return RetVal = PHIVal; // Got exit value!
4293
4294 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004295 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004296 if (NextPHI == PHIVal)
4297 return RetVal = NextPHI; // Stopped evolving!
4298 if (NextPHI == 0)
4299 return 0; // Couldn't evaluate!
4300 PHIVal = NextPHI;
4301 }
4302}
4303
Dan Gohman07ad19b2009-07-27 16:09:48 +00004304/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00004305/// constant number of times (the condition evolves only from constants),
4306/// try to evaluate a few iterations of the loop until we get the exit
4307/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00004308/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00004309const SCEV *
4310ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
4311 Value *Cond,
4312 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004313 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00004314 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00004315
Dan Gohmanb92654d2010-06-19 14:17:24 +00004316 // If the loop is canonicalized, the PHI will have exactly two entries.
4317 // That's the only form we support here.
4318 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
4319
4320 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner7980fb92004-04-17 18:36:24 +00004321 // second must be derived from the same PHI.
4322 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
4323 Constant *StartCST =
4324 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00004325 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00004326
4327 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Dan Gohman9d4588f2010-06-22 13:15:46 +00004328 if (getConstantEvolvingPHI(BEValue, L) != PN &&
4329 !isa<Constant>(BEValue))
4330 return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00004331
4332 // Okay, we find a PHI node that defines the trip count of this loop. Execute
4333 // the loop symbolically to determine when the condition gets a value of
4334 // "ExitWhen".
4335 unsigned IterationNum = 0;
4336 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
4337 for (Constant *PHIVal = StartCST;
4338 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004339 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004340 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00004341
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004342 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004343 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004344
Reid Spencere8019bb2007-03-01 07:25:48 +00004345 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00004346 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00004347 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00004348 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004349
Chris Lattner3221ad02004-04-17 22:58:41 +00004350 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004351 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00004352 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00004353 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00004354 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00004355 }
4356
4357 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00004358 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004359}
4360
Dan Gohmane7125f42009-09-03 15:00:26 +00004361/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00004362/// at the specified scope in the program. The L value specifies a loop
4363/// nest to evaluate the expression at, where null is the top-level or a
4364/// specified loop is immediately inside of the loop.
4365///
4366/// This method can be used to compute the exit value for a variable defined
4367/// in a loop by querying what the value will hold in the parent loop.
4368///
Dan Gohmand594e6f2009-05-24 23:25:42 +00004369/// In the case that a relevant loop exit value cannot be computed, the
4370/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004371const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00004372 // Check to see if we've folded this expression at this loop before.
4373 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
4374 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
4375 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
4376 if (!Pair.second)
4377 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00004378
Dan Gohman42214892009-08-31 21:15:23 +00004379 // Otherwise compute it.
4380 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00004381 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00004382 return C;
4383}
4384
4385const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004386 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004387
Nick Lewycky3e630762008-02-20 06:48:22 +00004388 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00004389 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00004390 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004391 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004392 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00004393 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
4394 if (PHINode *PN = dyn_cast<PHINode>(I))
4395 if (PN->getParent() == LI->getHeader()) {
4396 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00004397 // to see if the loop that contains it has a known backedge-taken
4398 // count. If so, we may be able to force computation of the exit
4399 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004400 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00004401 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00004402 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00004403 // Okay, we know how many times the containing loop executes. If
4404 // this is a constant evolving PHI node, get the final value at
4405 // the specified iteration number.
4406 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00004407 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00004408 LI);
Dan Gohman09987962009-06-29 21:31:18 +00004409 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004410 }
4411 }
4412
Reid Spencer09906f32006-12-04 21:33:23 +00004413 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004414 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004415 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004416 // result. This is particularly useful for computing loop exit values.
4417 if (CanConstantFold(I)) {
Dan Gohman11046452010-06-29 23:43:06 +00004418 SmallVector<Constant *, 4> Operands;
4419 bool MadeImprovement = false;
Chris Lattner3221ad02004-04-17 22:58:41 +00004420 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4421 Value *Op = I->getOperand(i);
4422 if (Constant *C = dyn_cast<Constant>(Op)) {
4423 Operands.push_back(C);
Dan Gohman11046452010-06-29 23:43:06 +00004424 continue;
Chris Lattner3221ad02004-04-17 22:58:41 +00004425 }
Dan Gohman11046452010-06-29 23:43:06 +00004426
4427 // If any of the operands is non-constant and if they are
4428 // non-integer and non-pointer, don't even try to analyze them
4429 // with scev techniques.
4430 if (!isSCEVable(Op->getType()))
4431 return V;
4432
4433 const SCEV *OrigV = getSCEV(Op);
4434 const SCEV *OpV = getSCEVAtScope(OrigV, L);
4435 MadeImprovement |= OrigV != OpV;
4436
4437 Constant *C = 0;
4438 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
4439 C = SC->getValue();
4440 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV))
4441 C = dyn_cast<Constant>(SU->getValue());
4442 if (!C) return V;
4443 if (C->getType() != Op->getType())
4444 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4445 Op->getType(),
4446 false),
4447 C, Op->getType());
4448 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004449 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004450
Dan Gohman11046452010-06-29 23:43:06 +00004451 // Check to see if getSCEVAtScope actually made an improvement.
4452 if (MadeImprovement) {
4453 Constant *C = 0;
4454 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4455 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
4456 Operands[0], Operands[1], TD);
4457 else
4458 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
4459 &Operands[0], Operands.size(), TD);
4460 if (!C) return V;
Dan Gohmane177c9a2010-02-24 19:31:47 +00004461 return getSCEV(C);
Dan Gohman11046452010-06-29 23:43:06 +00004462 }
Chris Lattner3221ad02004-04-17 22:58:41 +00004463 }
4464 }
4465
4466 // This is some other type of SCEVUnknown, just return it.
4467 return V;
4468 }
4469
Dan Gohman622ed672009-05-04 22:02:23 +00004470 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004471 // Avoid performing the look-up in the common case where the specified
4472 // expression has no loop-variant portions.
4473 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004474 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004475 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004476 // Okay, at least one of these operands is loop variant but might be
4477 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004478 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4479 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004480 NewOps.push_back(OpAtScope);
4481
4482 for (++i; i != e; ++i) {
4483 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004484 NewOps.push_back(OpAtScope);
4485 }
4486 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004487 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004488 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004489 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004490 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004491 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004492 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004493 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004494 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004495 }
4496 }
4497 // If we got here, all operands are loop invariant.
4498 return Comm;
4499 }
4500
Dan Gohman622ed672009-05-04 22:02:23 +00004501 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004502 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4503 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004504 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4505 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004506 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004507 }
4508
4509 // If this is a loop recurrence for a loop that does not contain L, then we
4510 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004511 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman11046452010-06-29 23:43:06 +00004512 // First, attempt to evaluate each operand.
4513 // Avoid performing the look-up in the common case where the specified
4514 // expression has no loop-variant portions.
4515 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4516 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
4517 if (OpAtScope == AddRec->getOperand(i))
4518 continue;
4519
4520 // Okay, at least one of these operands is loop variant but might be
4521 // foldable. Build a new instance of the folded commutative expression.
4522 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
4523 AddRec->op_begin()+i);
4524 NewOps.push_back(OpAtScope);
4525 for (++i; i != e; ++i)
4526 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
4527
4528 AddRec = cast<SCEVAddRecExpr>(getAddRecExpr(NewOps, AddRec->getLoop()));
4529 break;
4530 }
4531
4532 // If the scope is outside the addrec's loop, evaluate it by using the
4533 // loop exit value of the addrec.
4534 if (!AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004535 // To evaluate this recurrence, we need to know how many times the AddRec
4536 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004537 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004538 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004539
Eli Friedmanb42a6262008-08-04 23:49:06 +00004540 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004541 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004542 }
Dan Gohman11046452010-06-29 23:43:06 +00004543
Dan Gohmand594e6f2009-05-24 23:25:42 +00004544 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004545 }
4546
Dan Gohman622ed672009-05-04 22:02:23 +00004547 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004548 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004549 if (Op == Cast->getOperand())
4550 return Cast; // must be loop invariant
4551 return getZeroExtendExpr(Op, Cast->getType());
4552 }
4553
Dan Gohman622ed672009-05-04 22:02:23 +00004554 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004555 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004556 if (Op == Cast->getOperand())
4557 return Cast; // must be loop invariant
4558 return getSignExtendExpr(Op, Cast->getType());
4559 }
4560
Dan Gohman622ed672009-05-04 22:02:23 +00004561 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004562 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004563 if (Op == Cast->getOperand())
4564 return Cast; // must be loop invariant
4565 return getTruncateExpr(Op, Cast->getType());
4566 }
4567
Torok Edwinc23197a2009-07-14 16:55:14 +00004568 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004569 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004570}
4571
Dan Gohman66a7e852009-05-08 20:38:54 +00004572/// getSCEVAtScope - This is a convenience function which does
4573/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004574const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004575 return getSCEVAtScope(getSCEV(V), L);
4576}
4577
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004578/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4579/// following equation:
4580///
4581/// A * X = B (mod N)
4582///
4583/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4584/// A and B isn't important.
4585///
4586/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004587static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004588 ScalarEvolution &SE) {
4589 uint32_t BW = A.getBitWidth();
4590 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4591 assert(A != 0 && "A must be non-zero.");
4592
4593 // 1. D = gcd(A, N)
4594 //
4595 // The gcd of A and N may have only one prime factor: 2. The number of
4596 // trailing zeros in A is its multiplicity
4597 uint32_t Mult2 = A.countTrailingZeros();
4598 // D = 2^Mult2
4599
4600 // 2. Check if B is divisible by D.
4601 //
4602 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4603 // is not less than multiplicity of this prime factor for D.
4604 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004605 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004606
4607 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4608 // modulo (N / D).
4609 //
4610 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4611 // bit width during computations.
4612 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4613 APInt Mod(BW + 1, 0);
4614 Mod.set(BW - Mult2); // Mod = N / D
4615 APInt I = AD.multiplicativeInverse(Mod);
4616
4617 // 4. Compute the minimum unsigned root of the equation:
4618 // I * (B / D) mod (N / D)
4619 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4620
4621 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4622 // bits.
4623 return SE.getConstant(Result.trunc(BW));
4624}
Chris Lattner53e677a2004-04-02 20:23:17 +00004625
4626/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4627/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4628/// might be the same) or two SCEVCouldNotCompute objects.
4629///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004630static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004631SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004632 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004633 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4634 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4635 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004636
Chris Lattner53e677a2004-04-02 20:23:17 +00004637 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004638 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004639 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004640 return std::make_pair(CNC, CNC);
4641 }
4642
Reid Spencere8019bb2007-03-01 07:25:48 +00004643 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004644 const APInt &L = LC->getValue()->getValue();
4645 const APInt &M = MC->getValue()->getValue();
4646 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004647 APInt Two(BitWidth, 2);
4648 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004649
Dan Gohman64a845e2009-06-24 04:48:43 +00004650 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004651 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004652 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004653 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4654 // The B coefficient is M-N/2
4655 APInt B(M);
4656 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004657
Reid Spencere8019bb2007-03-01 07:25:48 +00004658 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004659 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004660
Reid Spencere8019bb2007-03-01 07:25:48 +00004661 // Compute the B^2-4ac term.
4662 APInt SqrtTerm(B);
4663 SqrtTerm *= B;
4664 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004665
Reid Spencere8019bb2007-03-01 07:25:48 +00004666 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4667 // integer value or else APInt::sqrt() will assert.
4668 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004669
Dan Gohman64a845e2009-06-24 04:48:43 +00004670 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004671 // The divisions must be performed as signed divisions.
4672 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004673 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004674 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004675 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004676 return std::make_pair(CNC, CNC);
4677 }
4678
Owen Andersone922c022009-07-22 00:24:57 +00004679 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004680
4681 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004682 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004683 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004684 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004685
Dan Gohman64a845e2009-06-24 04:48:43 +00004686 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004687 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004688 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004689}
4690
4691/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004692/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004693ScalarEvolution::BackedgeTakenInfo
4694ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004695 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004696 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004697 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004698 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004699 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004700 }
4701
Dan Gohman35738ac2009-05-04 22:30:44 +00004702 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004703 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004704 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004705
4706 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004707 // If this is an affine expression, the execution count of this branch is
4708 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004709 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004710 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004711 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004712 // equivalent to:
4713 //
4714 // Step*N = -Start (mod 2^BW)
4715 //
4716 // where BW is the common bit width of Start and Step.
4717
Chris Lattner53e677a2004-04-02 20:23:17 +00004718 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004719 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4720 L->getParentLoop());
4721 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4722 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004723
Dan Gohman622ed672009-05-04 22:02:23 +00004724 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004725 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004726
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004727 // First, handle unitary steps.
4728 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004729 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004730 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4731 return Start; // N = Start (as unsigned)
4732
4733 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004734 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004735 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004736 -StartC->getValue()->getValue(),
4737 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004738 }
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004739 } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004740 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4741 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004742 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004743 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004744 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4745 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004746 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004747#if 0
David Greene25e0e872009-12-23 22:18:14 +00004748 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004749 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004750#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004751 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004752 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004753 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004754 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004755 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004756 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004757
Chris Lattner53e677a2004-04-02 20:23:17 +00004758 // We can only use this value if the chrec ends up with an exact zero
4759 // value at this index. When solving for "X*X != 5", for example, we
4760 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004761 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004762 if (Val->isZero())
4763 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004764 }
4765 }
4766 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004767
Dan Gohman1c343752009-06-27 21:21:31 +00004768 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004769}
4770
4771/// HowFarToNonZero - Return the number of times a backedge checking the
4772/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004773/// CouldNotCompute
Dan Gohmanf6d009f2010-02-24 17:31:30 +00004774ScalarEvolution::BackedgeTakenInfo
4775ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004776 // Loops that look like: while (X == 0) are very strange indeed. We don't
4777 // handle them yet except for the trivial case. This could be expanded in the
4778 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004779
Chris Lattner53e677a2004-04-02 20:23:17 +00004780 // If the value is a constant, check to see if it is known to be non-zero
4781 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004782 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004783 if (!C->getValue()->isNullValue())
Dan Gohmandeff6212010-05-03 22:09:21 +00004784 return getConstant(C->getType(), 0);
Dan Gohman1c343752009-06-27 21:21:31 +00004785 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004786 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004787
Chris Lattner53e677a2004-04-02 20:23:17 +00004788 // We could implement others, but I really doubt anyone writes loops like
4789 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004790 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004791}
4792
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004793/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4794/// (which may not be an immediate predecessor) which has exactly one
4795/// successor from which BB is reachable, or null if no such block is
4796/// found.
4797///
Dan Gohman005752b2010-04-15 16:19:08 +00004798std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004799ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004800 // If the block has a unique predecessor, then there is no path from the
4801 // predecessor to the block that does not go through the direct edge
4802 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004803 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman005752b2010-04-15 16:19:08 +00004804 return std::make_pair(Pred, BB);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004805
4806 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004807 // If the header has a unique predecessor outside the loop, it must be
4808 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004809 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman605c14f2010-06-22 23:43:28 +00004810 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004811
Dan Gohman005752b2010-04-15 16:19:08 +00004812 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004813}
4814
Dan Gohman763bad12009-06-20 00:35:32 +00004815/// HasSameValue - SCEV structural equivalence is usually sufficient for
4816/// testing whether two expressions are equal, however for the purposes of
4817/// looking for a condition guarding a loop, it can be useful to be a little
4818/// more general, since a front-end may have replicated the controlling
4819/// expression.
4820///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004821static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004822 // Quick check to see if they are the same SCEV.
4823 if (A == B) return true;
4824
4825 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4826 // two different instructions with the same value. Check for this case.
4827 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4828 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4829 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4830 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004831 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004832 return true;
4833
4834 // Otherwise assume they may have a different value.
4835 return false;
4836}
4837
Dan Gohmane9796502010-04-24 01:28:42 +00004838/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
4839/// predicate Pred. Return true iff any changes were made.
4840///
4841bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
4842 const SCEV *&LHS, const SCEV *&RHS) {
4843 bool Changed = false;
4844
4845 // Canonicalize a constant to the right side.
4846 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
4847 // Check for both operands constant.
4848 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
4849 if (ConstantExpr::getICmp(Pred,
4850 LHSC->getValue(),
4851 RHSC->getValue())->isNullValue())
4852 goto trivially_false;
4853 else
4854 goto trivially_true;
4855 }
4856 // Otherwise swap the operands to put the constant on the right.
4857 std::swap(LHS, RHS);
4858 Pred = ICmpInst::getSwappedPredicate(Pred);
4859 Changed = true;
4860 }
4861
4862 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohman3abb69c2010-05-03 17:00:11 +00004863 // addrec's loop, put the addrec on the left. Also make a dominance check,
4864 // as both operands could be addrecs loop-invariant in each other's loop.
4865 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
4866 const Loop *L = AR->getLoop();
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00004867 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohmane9796502010-04-24 01:28:42 +00004868 std::swap(LHS, RHS);
4869 Pred = ICmpInst::getSwappedPredicate(Pred);
4870 Changed = true;
4871 }
Dan Gohman3abb69c2010-05-03 17:00:11 +00004872 }
Dan Gohmane9796502010-04-24 01:28:42 +00004873
4874 // If there's a constant operand, canonicalize comparisons with boundary
4875 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
4876 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4877 const APInt &RA = RC->getValue()->getValue();
4878 switch (Pred) {
4879 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4880 case ICmpInst::ICMP_EQ:
4881 case ICmpInst::ICMP_NE:
4882 break;
4883 case ICmpInst::ICMP_UGE:
4884 if ((RA - 1).isMinValue()) {
4885 Pred = ICmpInst::ICMP_NE;
4886 RHS = getConstant(RA - 1);
4887 Changed = true;
4888 break;
4889 }
4890 if (RA.isMaxValue()) {
4891 Pred = ICmpInst::ICMP_EQ;
4892 Changed = true;
4893 break;
4894 }
4895 if (RA.isMinValue()) goto trivially_true;
4896
4897 Pred = ICmpInst::ICMP_UGT;
4898 RHS = getConstant(RA - 1);
4899 Changed = true;
4900 break;
4901 case ICmpInst::ICMP_ULE:
4902 if ((RA + 1).isMaxValue()) {
4903 Pred = ICmpInst::ICMP_NE;
4904 RHS = getConstant(RA + 1);
4905 Changed = true;
4906 break;
4907 }
4908 if (RA.isMinValue()) {
4909 Pred = ICmpInst::ICMP_EQ;
4910 Changed = true;
4911 break;
4912 }
4913 if (RA.isMaxValue()) goto trivially_true;
4914
4915 Pred = ICmpInst::ICMP_ULT;
4916 RHS = getConstant(RA + 1);
4917 Changed = true;
4918 break;
4919 case ICmpInst::ICMP_SGE:
4920 if ((RA - 1).isMinSignedValue()) {
4921 Pred = ICmpInst::ICMP_NE;
4922 RHS = getConstant(RA - 1);
4923 Changed = true;
4924 break;
4925 }
4926 if (RA.isMaxSignedValue()) {
4927 Pred = ICmpInst::ICMP_EQ;
4928 Changed = true;
4929 break;
4930 }
4931 if (RA.isMinSignedValue()) goto trivially_true;
4932
4933 Pred = ICmpInst::ICMP_SGT;
4934 RHS = getConstant(RA - 1);
4935 Changed = true;
4936 break;
4937 case ICmpInst::ICMP_SLE:
4938 if ((RA + 1).isMaxSignedValue()) {
4939 Pred = ICmpInst::ICMP_NE;
4940 RHS = getConstant(RA + 1);
4941 Changed = true;
4942 break;
4943 }
4944 if (RA.isMinSignedValue()) {
4945 Pred = ICmpInst::ICMP_EQ;
4946 Changed = true;
4947 break;
4948 }
4949 if (RA.isMaxSignedValue()) goto trivially_true;
4950
4951 Pred = ICmpInst::ICMP_SLT;
4952 RHS = getConstant(RA + 1);
4953 Changed = true;
4954 break;
4955 case ICmpInst::ICMP_UGT:
4956 if (RA.isMinValue()) {
4957 Pred = ICmpInst::ICMP_NE;
4958 Changed = true;
4959 break;
4960 }
4961 if ((RA + 1).isMaxValue()) {
4962 Pred = ICmpInst::ICMP_EQ;
4963 RHS = getConstant(RA + 1);
4964 Changed = true;
4965 break;
4966 }
4967 if (RA.isMaxValue()) goto trivially_false;
4968 break;
4969 case ICmpInst::ICMP_ULT:
4970 if (RA.isMaxValue()) {
4971 Pred = ICmpInst::ICMP_NE;
4972 Changed = true;
4973 break;
4974 }
4975 if ((RA - 1).isMinValue()) {
4976 Pred = ICmpInst::ICMP_EQ;
4977 RHS = getConstant(RA - 1);
4978 Changed = true;
4979 break;
4980 }
4981 if (RA.isMinValue()) goto trivially_false;
4982 break;
4983 case ICmpInst::ICMP_SGT:
4984 if (RA.isMinSignedValue()) {
4985 Pred = ICmpInst::ICMP_NE;
4986 Changed = true;
4987 break;
4988 }
4989 if ((RA + 1).isMaxSignedValue()) {
4990 Pred = ICmpInst::ICMP_EQ;
4991 RHS = getConstant(RA + 1);
4992 Changed = true;
4993 break;
4994 }
4995 if (RA.isMaxSignedValue()) goto trivially_false;
4996 break;
4997 case ICmpInst::ICMP_SLT:
4998 if (RA.isMaxSignedValue()) {
4999 Pred = ICmpInst::ICMP_NE;
5000 Changed = true;
5001 break;
5002 }
5003 if ((RA - 1).isMinSignedValue()) {
5004 Pred = ICmpInst::ICMP_EQ;
5005 RHS = getConstant(RA - 1);
5006 Changed = true;
5007 break;
5008 }
5009 if (RA.isMinSignedValue()) goto trivially_false;
5010 break;
5011 }
5012 }
5013
5014 // Check for obvious equality.
5015 if (HasSameValue(LHS, RHS)) {
5016 if (ICmpInst::isTrueWhenEqual(Pred))
5017 goto trivially_true;
5018 if (ICmpInst::isFalseWhenEqual(Pred))
5019 goto trivially_false;
5020 }
5021
Dan Gohman03557dc2010-05-03 16:35:17 +00005022 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
5023 // adding or subtracting 1 from one of the operands.
5024 switch (Pred) {
5025 case ICmpInst::ICMP_SLE:
5026 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
5027 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
5028 /*HasNUW=*/false, /*HasNSW=*/true);
5029 Pred = ICmpInst::ICMP_SLT;
5030 Changed = true;
5031 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005032 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005033 /*HasNUW=*/false, /*HasNSW=*/true);
5034 Pred = ICmpInst::ICMP_SLT;
5035 Changed = true;
5036 }
5037 break;
5038 case ICmpInst::ICMP_SGE:
5039 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005040 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005041 /*HasNUW=*/false, /*HasNSW=*/true);
5042 Pred = ICmpInst::ICMP_SGT;
5043 Changed = true;
5044 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
5045 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
5046 /*HasNUW=*/false, /*HasNSW=*/true);
5047 Pred = ICmpInst::ICMP_SGT;
5048 Changed = true;
5049 }
5050 break;
5051 case ICmpInst::ICMP_ULE:
5052 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005053 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005054 /*HasNUW=*/true, /*HasNSW=*/false);
5055 Pred = ICmpInst::ICMP_ULT;
5056 Changed = true;
5057 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005058 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005059 /*HasNUW=*/true, /*HasNSW=*/false);
5060 Pred = ICmpInst::ICMP_ULT;
5061 Changed = true;
5062 }
5063 break;
5064 case ICmpInst::ICMP_UGE:
5065 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005066 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005067 /*HasNUW=*/true, /*HasNSW=*/false);
5068 Pred = ICmpInst::ICMP_UGT;
5069 Changed = true;
5070 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohmanf16c6802010-05-03 20:23:47 +00005071 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Dan Gohman03557dc2010-05-03 16:35:17 +00005072 /*HasNUW=*/true, /*HasNSW=*/false);
5073 Pred = ICmpInst::ICMP_UGT;
5074 Changed = true;
5075 }
5076 break;
5077 default:
5078 break;
5079 }
5080
Dan Gohmane9796502010-04-24 01:28:42 +00005081 // TODO: More simplifications are possible here.
5082
5083 return Changed;
5084
5085trivially_true:
5086 // Return 0 == 0.
5087 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5088 Pred = ICmpInst::ICMP_EQ;
5089 return true;
5090
5091trivially_false:
5092 // Return 0 != 0.
5093 LHS = RHS = getConstant(Type::getInt1Ty(getContext()), 0);
5094 Pred = ICmpInst::ICMP_NE;
5095 return true;
5096}
5097
Dan Gohman85b05a22009-07-13 21:35:55 +00005098bool ScalarEvolution::isKnownNegative(const SCEV *S) {
5099 return getSignedRange(S).getSignedMax().isNegative();
5100}
5101
5102bool ScalarEvolution::isKnownPositive(const SCEV *S) {
5103 return getSignedRange(S).getSignedMin().isStrictlyPositive();
5104}
5105
5106bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
5107 return !getSignedRange(S).getSignedMin().isNegative();
5108}
5109
5110bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
5111 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
5112}
5113
5114bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
5115 return isKnownNegative(S) || isKnownPositive(S);
5116}
5117
5118bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
5119 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmand19bba62010-04-24 01:38:36 +00005120 // Canonicalize the inputs first.
5121 (void)SimplifyICmpOperands(Pred, LHS, RHS);
5122
Dan Gohman53c66ea2010-04-11 22:16:48 +00005123 // If LHS or RHS is an addrec, check to see if the condition is true in
5124 // every iteration of the loop.
5125 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
5126 if (isLoopEntryGuardedByCond(
5127 AR->getLoop(), Pred, AR->getStart(), RHS) &&
5128 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005129 AR->getLoop(), Pred, AR->getPostIncExpr(*this), RHS))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005130 return true;
5131 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS))
5132 if (isLoopEntryGuardedByCond(
5133 AR->getLoop(), Pred, LHS, AR->getStart()) &&
5134 isLoopBackedgeGuardedByCond(
Dan Gohmanacd8cab2010-05-04 01:12:27 +00005135 AR->getLoop(), Pred, LHS, AR->getPostIncExpr(*this)))
Dan Gohman53c66ea2010-04-11 22:16:48 +00005136 return true;
Dan Gohman85b05a22009-07-13 21:35:55 +00005137
Dan Gohman53c66ea2010-04-11 22:16:48 +00005138 // Otherwise see what can be done with known constant ranges.
5139 return isKnownPredicateWithRanges(Pred, LHS, RHS);
5140}
5141
5142bool
5143ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
5144 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005145 if (HasSameValue(LHS, RHS))
5146 return ICmpInst::isTrueWhenEqual(Pred);
5147
Dan Gohman53c66ea2010-04-11 22:16:48 +00005148 // This code is split out from isKnownPredicate because it is called from
5149 // within isLoopEntryGuardedByCond.
Dan Gohman85b05a22009-07-13 21:35:55 +00005150 switch (Pred) {
5151 default:
Dan Gohman850f7912009-07-16 17:34:36 +00005152 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00005153 break;
5154 case ICmpInst::ICMP_SGT:
5155 Pred = ICmpInst::ICMP_SLT;
5156 std::swap(LHS, RHS);
5157 case ICmpInst::ICMP_SLT: {
5158 ConstantRange LHSRange = getSignedRange(LHS);
5159 ConstantRange RHSRange = getSignedRange(RHS);
5160 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
5161 return true;
5162 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
5163 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005164 break;
5165 }
5166 case ICmpInst::ICMP_SGE:
5167 Pred = ICmpInst::ICMP_SLE;
5168 std::swap(LHS, RHS);
5169 case ICmpInst::ICMP_SLE: {
5170 ConstantRange LHSRange = getSignedRange(LHS);
5171 ConstantRange RHSRange = getSignedRange(RHS);
5172 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
5173 return true;
5174 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
5175 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005176 break;
5177 }
5178 case ICmpInst::ICMP_UGT:
5179 Pred = ICmpInst::ICMP_ULT;
5180 std::swap(LHS, RHS);
5181 case ICmpInst::ICMP_ULT: {
5182 ConstantRange LHSRange = getUnsignedRange(LHS);
5183 ConstantRange RHSRange = getUnsignedRange(RHS);
5184 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
5185 return true;
5186 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
5187 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005188 break;
5189 }
5190 case ICmpInst::ICMP_UGE:
5191 Pred = ICmpInst::ICMP_ULE;
5192 std::swap(LHS, RHS);
5193 case ICmpInst::ICMP_ULE: {
5194 ConstantRange LHSRange = getUnsignedRange(LHS);
5195 ConstantRange RHSRange = getUnsignedRange(RHS);
5196 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
5197 return true;
5198 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
5199 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005200 break;
5201 }
5202 case ICmpInst::ICMP_NE: {
5203 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
5204 return true;
5205 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
5206 return true;
5207
5208 const SCEV *Diff = getMinusSCEV(LHS, RHS);
5209 if (isKnownNonZero(Diff))
5210 return true;
5211 break;
5212 }
5213 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00005214 // The check at the top of the function catches the case where
5215 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00005216 break;
5217 }
5218 return false;
5219}
5220
5221/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
5222/// protected by a conditional between LHS and RHS. This is used to
5223/// to eliminate casts.
5224bool
5225ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
5226 ICmpInst::Predicate Pred,
5227 const SCEV *LHS, const SCEV *RHS) {
5228 // Interpret a null as meaning no loop, where there is obviously no guard
5229 // (interprocedural conditions notwithstanding).
5230 if (!L) return true;
5231
5232 BasicBlock *Latch = L->getLoopLatch();
5233 if (!Latch)
5234 return false;
5235
5236 BranchInst *LoopContinuePredicate =
5237 dyn_cast<BranchInst>(Latch->getTerminator());
5238 if (!LoopContinuePredicate ||
5239 LoopContinuePredicate->isUnconditional())
5240 return false;
5241
Dan Gohmanaf08a362010-08-10 23:46:30 +00005242 return isImpliedCond(Pred, LHS, RHS,
5243 LoopContinuePredicate->getCondition(),
Dan Gohman0f4b2852009-07-21 23:03:19 +00005244 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00005245}
5246
Dan Gohman3948d0b2010-04-11 19:27:13 +00005247/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohman85b05a22009-07-13 21:35:55 +00005248/// by a conditional between LHS and RHS. This is used to help avoid max
5249/// expressions in loop trip counts, and to eliminate casts.
5250bool
Dan Gohman3948d0b2010-04-11 19:27:13 +00005251ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
5252 ICmpInst::Predicate Pred,
5253 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00005254 // Interpret a null as meaning no loop, where there is obviously no guard
5255 // (interprocedural conditions notwithstanding).
5256 if (!L) return false;
5257
Dan Gohman859b4822009-05-18 15:36:09 +00005258 // Starting at the loop predecessor, climb up the predecessor chain, as long
5259 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00005260 // leading to the original header.
Dan Gohman005752b2010-04-15 16:19:08 +00005261 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman605c14f2010-06-22 23:43:28 +00005262 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman005752b2010-04-15 16:19:08 +00005263 Pair.first;
5264 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman38372182008-08-12 20:17:31 +00005265
5266 BranchInst *LoopEntryPredicate =
Dan Gohman005752b2010-04-15 16:19:08 +00005267 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00005268 if (!LoopEntryPredicate ||
5269 LoopEntryPredicate->isUnconditional())
5270 continue;
5271
Dan Gohmanaf08a362010-08-10 23:46:30 +00005272 if (isImpliedCond(Pred, LHS, RHS,
5273 LoopEntryPredicate->getCondition(),
Dan Gohman005752b2010-04-15 16:19:08 +00005274 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman38372182008-08-12 20:17:31 +00005275 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00005276 }
5277
Dan Gohman38372182008-08-12 20:17:31 +00005278 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00005279}
5280
Dan Gohman0f4b2852009-07-21 23:03:19 +00005281/// isImpliedCond - Test whether the condition described by Pred, LHS,
5282/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005283bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005284 const SCEV *LHS, const SCEV *RHS,
Dan Gohmanaf08a362010-08-10 23:46:30 +00005285 Value *FoundCondValue,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005286 bool Inverse) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005287 // Recursively handle And and Or conditions.
Dan Gohmanaf08a362010-08-10 23:46:30 +00005288 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005289 if (BO->getOpcode() == Instruction::And) {
5290 if (!Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005291 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5292 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005293 } else if (BO->getOpcode() == Instruction::Or) {
5294 if (Inverse)
Dan Gohmanaf08a362010-08-10 23:46:30 +00005295 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
5296 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005297 }
5298 }
5299
Dan Gohmanaf08a362010-08-10 23:46:30 +00005300 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005301 if (!ICI) return false;
5302
Dan Gohman85b05a22009-07-13 21:35:55 +00005303 // Bail if the ICmp's operands' types are wider than the needed type
5304 // before attempting to call getSCEV on them. This avoids infinite
5305 // recursion, since the analysis of widening casts can require loop
5306 // exit condition information for overflow checking, which would
5307 // lead back here.
5308 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00005309 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00005310 return false;
5311
Dan Gohman0f4b2852009-07-21 23:03:19 +00005312 // Now that we found a conditional branch that dominates the loop, check to
5313 // see if it is the comparison we are looking for.
5314 ICmpInst::Predicate FoundPred;
5315 if (Inverse)
5316 FoundPred = ICI->getInversePredicate();
5317 else
5318 FoundPred = ICI->getPredicate();
5319
5320 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
5321 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00005322
5323 // Balance the types. The case where FoundLHS' type is wider than
5324 // LHS' type is checked for above.
5325 if (getTypeSizeInBits(LHS->getType()) >
5326 getTypeSizeInBits(FoundLHS->getType())) {
5327 if (CmpInst::isSigned(Pred)) {
5328 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
5329 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
5330 } else {
5331 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
5332 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
5333 }
5334 }
5335
Dan Gohman0f4b2852009-07-21 23:03:19 +00005336 // Canonicalize the query to match the way instcombine will have
5337 // canonicalized the comparison.
Dan Gohmand4da5af2010-04-24 01:34:53 +00005338 if (SimplifyICmpOperands(Pred, LHS, RHS))
5339 if (LHS == RHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005340 return CmpInst::isTrueWhenEqual(Pred);
Dan Gohmand4da5af2010-04-24 01:34:53 +00005341 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
5342 if (FoundLHS == FoundRHS)
Dan Gohman34c3e362010-05-03 18:00:24 +00005343 return CmpInst::isFalseWhenEqual(Pred);
Dan Gohman0f4b2852009-07-21 23:03:19 +00005344
5345 // Check to see if we can make the LHS or RHS match.
5346 if (LHS == FoundRHS || RHS == FoundLHS) {
5347 if (isa<SCEVConstant>(RHS)) {
5348 std::swap(FoundLHS, FoundRHS);
5349 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
5350 } else {
5351 std::swap(LHS, RHS);
5352 Pred = ICmpInst::getSwappedPredicate(Pred);
5353 }
5354 }
5355
5356 // Check whether the found predicate is the same as the desired predicate.
5357 if (FoundPred == Pred)
5358 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
5359
5360 // Check whether swapping the found predicate makes it the same as the
5361 // desired predicate.
5362 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
5363 if (isa<SCEVConstant>(RHS))
5364 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
5365 else
5366 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
5367 RHS, LHS, FoundLHS, FoundRHS);
5368 }
5369
5370 // Check whether the actual condition is beyond sufficient.
5371 if (FoundPred == ICmpInst::ICMP_EQ)
5372 if (ICmpInst::isTrueWhenEqual(Pred))
5373 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
5374 return true;
5375 if (Pred == ICmpInst::ICMP_NE)
5376 if (!ICmpInst::isTrueWhenEqual(FoundPred))
5377 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
5378 return true;
5379
5380 // Otherwise assume the worst.
5381 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00005382}
5383
Dan Gohman0f4b2852009-07-21 23:03:19 +00005384/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005385/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005386/// and FoundRHS is true.
5387bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
5388 const SCEV *LHS, const SCEV *RHS,
5389 const SCEV *FoundLHS,
5390 const SCEV *FoundRHS) {
5391 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
5392 FoundLHS, FoundRHS) ||
5393 // ~x < ~y --> x > y
5394 isImpliedCondOperandsHelper(Pred, LHS, RHS,
5395 getNotSCEV(FoundRHS),
5396 getNotSCEV(FoundLHS));
5397}
5398
5399/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005400/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman0f4b2852009-07-21 23:03:19 +00005401/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00005402bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00005403ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
5404 const SCEV *LHS, const SCEV *RHS,
5405 const SCEV *FoundLHS,
5406 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00005407 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00005408 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
5409 case ICmpInst::ICMP_EQ:
5410 case ICmpInst::ICMP_NE:
5411 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
5412 return true;
5413 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00005414 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00005415 case ICmpInst::ICMP_SLE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005416 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
5417 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005418 return true;
5419 break;
5420 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005421 case ICmpInst::ICMP_SGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005422 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
5423 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005424 return true;
5425 break;
5426 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00005427 case ICmpInst::ICMP_ULE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005428 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
5429 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005430 return true;
5431 break;
5432 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00005433 case ICmpInst::ICMP_UGE:
Dan Gohman53c66ea2010-04-11 22:16:48 +00005434 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
5435 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohman85b05a22009-07-13 21:35:55 +00005436 return true;
5437 break;
5438 }
5439
5440 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00005441}
5442
Dan Gohman51f53b72009-06-21 23:46:38 +00005443/// getBECount - Subtract the end and start values and divide by the step,
5444/// rounding up, to get the number of times the backedge is executed. Return
5445/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005446const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00005447 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00005448 const SCEV *Step,
5449 bool NoWrap) {
Dan Gohman52fddd32010-01-26 04:40:18 +00005450 assert(!isKnownNegative(Step) &&
5451 "This code doesn't handle negative strides yet!");
5452
Dan Gohman51f53b72009-06-21 23:46:38 +00005453 const Type *Ty = Start->getType();
Dan Gohmandeff6212010-05-03 22:09:21 +00005454 const SCEV *NegOne = getConstant(Ty, (uint64_t)-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005455 const SCEV *Diff = getMinusSCEV(End, Start);
5456 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00005457
5458 // Add an adjustment to the difference between End and Start so that
5459 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005460 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00005461
Dan Gohman1f96e672009-09-17 18:05:20 +00005462 if (!NoWrap) {
5463 // Check Add for unsigned overflow.
5464 // TODO: More sophisticated things could be done here.
5465 const Type *WideTy = IntegerType::get(getContext(),
5466 getTypeSizeInBits(Ty) + 1);
5467 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
5468 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
5469 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
5470 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
5471 return getCouldNotCompute();
5472 }
Dan Gohman51f53b72009-06-21 23:46:38 +00005473
5474 return getUDivExpr(Add, Step);
5475}
5476
Chris Lattnerdb25de42005-08-15 23:33:51 +00005477/// HowManyLessThans - Return the number of times a backedge containing the
5478/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00005479/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00005480ScalarEvolution::BackedgeTakenInfo
5481ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
5482 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00005483 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman17ead4f2010-11-17 21:23:15 +00005484 if (!isLoopInvariant(RHS, L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005485
Dan Gohman35738ac2009-05-04 22:30:44 +00005486 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005487 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00005488 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005489
Dan Gohman1f96e672009-09-17 18:05:20 +00005490 // Check to see if we have a flag which makes analysis easy.
5491 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
5492 AddRec->hasNoUnsignedWrap();
5493
Chris Lattnerdb25de42005-08-15 23:33:51 +00005494 if (AddRec->isAffine()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005495 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00005496 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00005497
Dan Gohman52fddd32010-01-26 04:40:18 +00005498 if (Step->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00005499 return getCouldNotCompute();
Dan Gohman52fddd32010-01-26 04:40:18 +00005500 if (Step->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00005501 // With unit stride, the iteration never steps past the limit value.
Dan Gohman52fddd32010-01-26 04:40:18 +00005502 } else if (isKnownPositive(Step)) {
Dan Gohmanf451cb82010-02-10 16:03:48 +00005503 // Test whether a positive iteration can step past the limit
Dan Gohman52fddd32010-01-26 04:40:18 +00005504 // value and past the maximum value for its type in a single step.
5505 // Note that it's not sufficient to check NoWrap here, because even
5506 // though the value after a wrap is undefined, it's not undefined
5507 // behavior, so if wrap does occur, the loop could either terminate or
Dan Gohman155eec72010-01-26 18:32:54 +00005508 // loop infinitely, but in either case, the loop is guaranteed to
Dan Gohman52fddd32010-01-26 04:40:18 +00005509 // iterate at least until the iteration where the wrapping occurs.
Dan Gohmandeff6212010-05-03 22:09:21 +00005510 const SCEV *One = getConstant(Step->getType(), 1);
Dan Gohman52fddd32010-01-26 04:40:18 +00005511 if (isSigned) {
5512 APInt Max = APInt::getSignedMaxValue(BitWidth);
5513 if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
5514 .slt(getSignedRange(RHS).getSignedMax()))
5515 return getCouldNotCompute();
5516 } else {
5517 APInt Max = APInt::getMaxValue(BitWidth);
5518 if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
5519 .ult(getUnsignedRange(RHS).getUnsignedMax()))
5520 return getCouldNotCompute();
5521 }
Dan Gohmana1af7572009-04-30 20:47:05 +00005522 } else
Dan Gohman52fddd32010-01-26 04:40:18 +00005523 // TODO: Handle negative strides here and below.
Dan Gohman1c343752009-06-27 21:21:31 +00005524 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005525
Dan Gohmana1af7572009-04-30 20:47:05 +00005526 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
5527 // m. So, we count the number of iterations in which {n,+,s} < m is true.
5528 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00005529 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00005530
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005531 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00005532 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005533
Dan Gohmana1af7572009-04-30 20:47:05 +00005534 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005535 const SCEV *MinStart = getConstant(isSigned ?
5536 getSignedRange(Start).getSignedMin() :
5537 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00005538
Dan Gohmana1af7572009-04-30 20:47:05 +00005539 // If we know that the condition is true in order to enter the loop,
5540 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00005541 // only know that it will execute (max(m,n)-n)/s times. In both cases,
5542 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005543 const SCEV *End = RHS;
Dan Gohman3948d0b2010-04-11 19:27:13 +00005544 if (!isLoopEntryGuardedByCond(L,
5545 isSigned ? ICmpInst::ICMP_SLT :
5546 ICmpInst::ICMP_ULT,
5547 getMinusSCEV(Start, Step), RHS))
Dan Gohmana1af7572009-04-30 20:47:05 +00005548 End = isSigned ? getSMaxExpr(RHS, Start)
5549 : getUMaxExpr(RHS, Start);
5550
5551 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00005552 const SCEV *MaxEnd = getConstant(isSigned ?
5553 getSignedRange(End).getSignedMax() :
5554 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00005555
Dan Gohman52fddd32010-01-26 04:40:18 +00005556 // If MaxEnd is within a step of the maximum integer value in its type,
5557 // adjust it down to the minimum value which would produce the same effect.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005558 // This allows the subsequent ceiling division of (N+(step-1))/step to
Dan Gohman52fddd32010-01-26 04:40:18 +00005559 // compute the correct value.
5560 const SCEV *StepMinusOne = getMinusSCEV(Step,
Dan Gohmandeff6212010-05-03 22:09:21 +00005561 getConstant(Step->getType(), 1));
Dan Gohman52fddd32010-01-26 04:40:18 +00005562 MaxEnd = isSigned ?
5563 getSMinExpr(MaxEnd,
5564 getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
5565 StepMinusOne)) :
5566 getUMinExpr(MaxEnd,
5567 getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
5568 StepMinusOne));
5569
Dan Gohmana1af7572009-04-30 20:47:05 +00005570 // Finally, we subtract these two values and divide, rounding up, to get
5571 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00005572 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005573
5574 // The maximum backedge count is similar, except using the minimum start
5575 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00005576 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00005577
5578 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00005579 }
5580
Dan Gohman1c343752009-06-27 21:21:31 +00005581 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00005582}
5583
Chris Lattner53e677a2004-04-02 20:23:17 +00005584/// getNumIterationsInRange - Return the number of iterations of this loop that
5585/// produce values in the specified constant range. Another way of looking at
5586/// this is that it returns the first iteration number where the value is not in
5587/// the condition, thus computing the exit count. If the iteration count can't
5588/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005589const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00005590 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00005591 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005592 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005593
5594 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00005595 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00005596 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00005597 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00005598 Operands[0] = SE.getConstant(SC->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00005599 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00005600 if (const SCEVAddRecExpr *ShiftedAddRec =
5601 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00005602 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00005603 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00005604 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005605 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005606 }
5607
5608 // The only time we can solve this is when we have all constant indices.
5609 // Otherwise, we cannot determine the overflow conditions.
5610 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5611 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005612 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005613
5614
5615 // Okay at this point we know that all elements of the chrec are constants and
5616 // that the start element is zero.
5617
5618 // First check to see if the range contains zero. If not, the first
5619 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005620 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005621 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohmandeff6212010-05-03 22:09:21 +00005622 return SE.getConstant(getType(), 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005623
Chris Lattner53e677a2004-04-02 20:23:17 +00005624 if (isAffine()) {
5625 // If this is an affine expression then we have this situation:
5626 // Solve {0,+,A} in Range === Ax in Range
5627
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005628 // We know that zero is in the range. If A is positive then we know that
5629 // the upper value of the range must be the first possible exit value.
5630 // If A is negative then the lower of the range is the last possible loop
5631 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005632 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005633 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5634 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005635
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005636 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005637 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005638 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005639
5640 // Evaluate at the exit value. If we really did fall out of the valid
5641 // range, then we computed our trip count, otherwise wrap around or other
5642 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005643 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005644 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005645 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005646
5647 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005648 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005649 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005650 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005651 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005652 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005653 } else if (isQuadratic()) {
5654 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5655 // quadratic equation to solve it. To do this, we must frame our problem in
5656 // terms of figuring out when zero is crossed, instead of when
5657 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005658 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005659 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005660 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005661
5662 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005663 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005664 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005665 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5666 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005667 if (R1) {
5668 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005669 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005670 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005671 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005672 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005673 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005674
Chris Lattner53e677a2004-04-02 20:23:17 +00005675 // Make sure the root is not off by one. The returned iteration should
5676 // not be in the range, but the previous one should be. When solving
5677 // for "X*X < 5", for example, we should not return a root of 2.
5678 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005679 R1->getValue(),
5680 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005681 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005682 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005683 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005684 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005685
Dan Gohman246b2562007-10-22 18:31:58 +00005686 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005687 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005688 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005689 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005690 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005691
Chris Lattner53e677a2004-04-02 20:23:17 +00005692 // If R1 was not in the range, then it is a good return value. Make
5693 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005694 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005695 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005696 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005697 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005698 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005699 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005700 }
5701 }
5702 }
5703
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005704 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005705}
5706
5707
5708
5709//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005710// SCEVCallbackVH Class Implementation
5711//===----------------------------------------------------------------------===//
5712
Dan Gohman1959b752009-05-19 19:22:47 +00005713void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005714 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005715 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5716 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005717 SE->ValueExprMap.erase(getValPtr());
Dan Gohman35738ac2009-05-04 22:30:44 +00005718 // this now dangles!
5719}
5720
Dan Gohman81f91212010-07-28 01:09:07 +00005721void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005722 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christophere6cbfa62010-07-29 01:25:38 +00005723
Dan Gohman35738ac2009-05-04 22:30:44 +00005724 // Forget all the expressions associated with users of the old value,
5725 // so that future queries will recompute the expressions using the new
5726 // value.
Dan Gohmanab37f502010-08-02 23:49:30 +00005727 Value *Old = getValPtr();
Dan Gohman35738ac2009-05-04 22:30:44 +00005728 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005729 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005730 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5731 UI != UE; ++UI)
5732 Worklist.push_back(*UI);
5733 while (!Worklist.empty()) {
5734 User *U = Worklist.pop_back_val();
5735 // Deleting the Old value will cause this to dangle. Postpone
5736 // that until everything else is done.
Dan Gohman59846ac2010-07-28 00:28:25 +00005737 if (U == Old)
Dan Gohman35738ac2009-05-04 22:30:44 +00005738 continue;
Dan Gohman69fcae92009-07-14 14:34:04 +00005739 if (!Visited.insert(U))
5740 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005741 if (PHINode *PN = dyn_cast<PHINode>(U))
5742 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005743 SE->ValueExprMap.erase(U);
Dan Gohman69fcae92009-07-14 14:34:04 +00005744 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5745 UI != UE; ++UI)
5746 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005747 }
Dan Gohman59846ac2010-07-28 00:28:25 +00005748 // Delete the Old value.
5749 if (PHINode *PN = dyn_cast<PHINode>(Old))
5750 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005751 SE->ValueExprMap.erase(Old);
Dan Gohman59846ac2010-07-28 00:28:25 +00005752 // this now dangles!
Dan Gohman35738ac2009-05-04 22:30:44 +00005753}
5754
Dan Gohman1959b752009-05-19 19:22:47 +00005755ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005756 : CallbackVH(V), SE(se) {}
5757
5758//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005759// ScalarEvolution Class Implementation
5760//===----------------------------------------------------------------------===//
5761
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005762ScalarEvolution::ScalarEvolution()
Owen Anderson90c579d2010-08-06 18:33:48 +00005763 : FunctionPass(ID), FirstUnknown(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +00005764 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005765}
5766
Chris Lattner53e677a2004-04-02 20:23:17 +00005767bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005768 this->F = &F;
5769 LI = &getAnalysis<LoopInfo>();
5770 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohman454d26d2010-02-22 04:11:59 +00005771 DT = &getAnalysis<DominatorTree>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005772 return false;
5773}
5774
5775void ScalarEvolution::releaseMemory() {
Dan Gohmanab37f502010-08-02 23:49:30 +00005776 // Iterate through all the SCEVUnknown instances and call their
5777 // destructors, so that they release their references to their values.
5778 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
5779 U->~SCEVUnknown();
5780 FirstUnknown = 0;
5781
Dan Gohmane8ac3f32010-08-27 18:55:03 +00005782 ValueExprMap.clear();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005783 BackedgeTakenCounts.clear();
5784 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005785 ValuesAtScopes.clear();
Dan Gohman6678e7b2010-11-17 02:44:44 +00005786 UnsignedRanges.clear();
5787 SignedRanges.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005788 UniqueSCEVs.clear();
5789 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005790}
5791
5792void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5793 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005794 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman1cd92752010-01-19 22:21:27 +00005795 AU.addRequiredTransitive<DominatorTree>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005796}
5797
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005798bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005799 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005800}
5801
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005802static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005803 const Loop *L) {
5804 // Print all inner loops first
5805 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5806 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005807
Dan Gohman30733292010-01-09 18:17:45 +00005808 OS << "Loop ";
5809 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5810 OS << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005811
Dan Gohman5d984912009-12-18 01:14:11 +00005812 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005813 L->getExitBlocks(ExitBlocks);
5814 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005815 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005816
Dan Gohman46bdfb02009-02-24 18:55:53 +00005817 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5818 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005819 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005820 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005821 }
5822
Dan Gohman30733292010-01-09 18:17:45 +00005823 OS << "\n"
5824 "Loop ";
5825 WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
5826 OS << ": ";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005827
5828 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5829 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5830 } else {
5831 OS << "Unpredictable max backedge-taken count. ";
5832 }
5833
5834 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005835}
5836
Dan Gohman5d984912009-12-18 01:14:11 +00005837void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00005838 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005839 // out SCEV values of all instructions that are interesting. Doing
5840 // this potentially causes it to create new SCEV objects though,
5841 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005842 // observable from outside the class though, so casting away the
5843 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005844 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005845
Dan Gohman30733292010-01-09 18:17:45 +00005846 OS << "Classifying expressions for: ";
5847 WriteAsOperand(OS, F, /*PrintType=*/false);
5848 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005849 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmana189bae2010-05-03 17:03:23 +00005850 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005851 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005852 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005853 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005854 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005855
Dan Gohman0c689c52009-06-19 17:49:54 +00005856 const Loop *L = LI->getLoopFor((*I).getParent());
5857
Dan Gohman0bba49c2009-07-07 17:06:11 +00005858 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005859 if (AtUse != SV) {
5860 OS << " --> ";
5861 AtUse->print(OS);
5862 }
5863
5864 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005865 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005866 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00005867 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005868 OS << "<<Unknown>>";
5869 } else {
5870 OS << *ExitValue;
5871 }
5872 }
5873
Chris Lattner53e677a2004-04-02 20:23:17 +00005874 OS << "\n";
5875 }
5876
Dan Gohman30733292010-01-09 18:17:45 +00005877 OS << "Determining loop execution counts for: ";
5878 WriteAsOperand(OS, F, /*PrintType=*/false);
5879 OS << "\n";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005880 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5881 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005882}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005883
Dan Gohman17ead4f2010-11-17 21:23:15 +00005884bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
5885 switch (S->getSCEVType()) {
5886 case scConstant:
5887 return true;
5888 case scTruncate:
5889 case scZeroExtend:
5890 case scSignExtend:
5891 return isLoopInvariant(cast<SCEVCastExpr>(S)->getOperand(), L);
5892 case scAddRecExpr: {
5893 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
5894
5895 // Add recurrences are never invariant in the function-body (null loop).
5896 if (!L)
5897 return false;
5898
5899 // This recurrence is variant w.r.t. L if L contains AR's loop.
5900 if (L->contains(AR->getLoop()))
5901 return false;
5902
5903 // This recurrence is invariant w.r.t. L if AR's loop contains L.
5904 if (AR->getLoop()->contains(L))
5905 return true;
5906
5907 // This recurrence is variant w.r.t. L if any of its operands
5908 // are variant.
5909 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
5910 I != E; ++I)
5911 if (!isLoopInvariant(*I, L))
5912 return false;
5913
5914 // Otherwise it's loop-invariant.
5915 return true;
5916 }
5917 case scAddExpr:
5918 case scMulExpr:
5919 case scUMaxExpr:
5920 case scSMaxExpr: {
5921 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
5922 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
5923 I != E; ++I)
5924 if (!isLoopInvariant(*I, L))
5925 return false;
5926 return true;
5927 }
5928 case scUDivExpr: {
5929 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
5930 return isLoopInvariant(UDiv->getLHS(), L) &&
5931 isLoopInvariant(UDiv->getRHS(), L);
5932 }
5933 case scUnknown:
5934 // All non-instruction values are loop invariant. All instructions are loop
5935 // invariant if they are not contained in the specified loop.
5936 // Instructions are never considered invariant in the function body
5937 // (null loop) because they are defined within the "loop".
5938 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
5939 return L && !L->contains(I);
5940 return true;
5941 case scCouldNotCompute:
5942 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
5943 return false;
5944 default: break;
5945 }
5946 llvm_unreachable("Unknown SCEV kind!");
5947 return false;
5948}
5949
5950bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
5951 switch (S->getSCEVType()) {
5952 case scConstant:
5953 return false;
5954 case scTruncate:
5955 case scZeroExtend:
5956 case scSignExtend:
5957 return hasComputableLoopEvolution(cast<SCEVCastExpr>(S)->getOperand(), L);
5958 case scAddRecExpr:
5959 return cast<SCEVAddRecExpr>(S)->getLoop() == L;
5960 case scAddExpr:
5961 case scMulExpr:
5962 case scUMaxExpr:
5963 case scSMaxExpr: {
5964 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
5965 bool HasVarying = false;
5966 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
5967 I != E; ++I) {
5968 const SCEV *Op = *I;
5969 if (!isLoopInvariant(Op, L)) {
5970 if (hasComputableLoopEvolution(Op, L))
5971 HasVarying = true;
5972 else
5973 return false;
5974 }
5975 }
5976 return HasVarying;
5977 }
5978 case scUDivExpr: {
5979 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
5980 bool HasVarying = false;
5981 if (!isLoopInvariant(UDiv->getLHS(), L)) {
5982 if (hasComputableLoopEvolution(UDiv->getLHS(), L))
5983 HasVarying = true;
5984 else
5985 return false;
5986 }
5987 if (!isLoopInvariant(UDiv->getRHS(), L)) {
5988 if (hasComputableLoopEvolution(UDiv->getRHS(), L))
5989 HasVarying = true;
5990 else
5991 return false;
5992 }
5993 return HasVarying;
5994 }
5995 case scUnknown:
5996 return false;
5997 case scCouldNotCompute:
5998 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
5999 return false;
6000 default: break;
6001 }
6002 llvm_unreachable("Unknown SCEV kind!");
6003 return false;
6004}
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00006005
6006bool ScalarEvolution::dominates(const SCEV *S, BasicBlock *BB) const {
6007 switch (S->getSCEVType()) {
6008 case scConstant:
6009 return true;
6010 case scTruncate:
6011 case scZeroExtend:
6012 case scSignExtend:
6013 return dominates(cast<SCEVCastExpr>(S)->getOperand(), BB);
6014 case scAddRecExpr: {
6015 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6016 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6017 return false;
6018 }
6019 // FALL THROUGH into SCEVNAryExpr handling.
6020 case scAddExpr:
6021 case scMulExpr:
6022 case scUMaxExpr:
6023 case scSMaxExpr: {
6024 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6025 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6026 I != E; ++I)
6027 if (!dominates(*I, BB))
6028 return false;
6029 return true;
6030 }
6031 case scUDivExpr: {
6032 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6033 return dominates(UDiv->getLHS(), BB) && dominates(UDiv->getRHS(), BB);
6034 }
6035 case scUnknown:
6036 if (Instruction *I =
6037 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6038 return DT->dominates(I->getParent(), BB);
6039 return true;
6040 case scCouldNotCompute:
6041 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6042 return false;
6043 default: break;
6044 }
6045 llvm_unreachable("Unknown SCEV kind!");
6046 return false;
6047}
6048
6049bool ScalarEvolution::properlyDominates(const SCEV *S, BasicBlock *BB) const {
6050 switch (S->getSCEVType()) {
6051 case scConstant:
6052 return true;
6053 case scTruncate:
6054 case scZeroExtend:
6055 case scSignExtend:
6056 return properlyDominates(cast<SCEVCastExpr>(S)->getOperand(), BB);
6057 case scAddRecExpr: {
6058 // This uses a "dominates" query instead of "properly dominates" query
6059 // because the instruction which produces the addrec's value is a PHI, and
6060 // a PHI effectively properly dominates its entire containing block.
6061 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
6062 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
6063 return false;
6064 }
6065 // FALL THROUGH into SCEVNAryExpr handling.
6066 case scAddExpr:
6067 case scMulExpr:
6068 case scUMaxExpr:
6069 case scSMaxExpr: {
6070 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
6071 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
6072 I != E; ++I)
6073 if (!properlyDominates(*I, BB))
6074 return false;
6075 return true;
6076 }
6077 case scUDivExpr: {
6078 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6079 return properlyDominates(UDiv->getLHS(), BB) &&
6080 properlyDominates(UDiv->getRHS(), BB);
6081 }
6082 case scUnknown:
6083 if (Instruction *I =
6084 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
6085 return DT->properlyDominates(I->getParent(), BB);
6086 return true;
6087 case scCouldNotCompute:
6088 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6089 return false;
6090 default: break;
6091 }
6092 llvm_unreachable("Unknown SCEV kind!");
6093 return false;
6094}